package com.izouma.nineth.service;

import com.alibaba.fastjson.JSONObject;
import com.izouma.nineth.config.RedisKeys;
import com.izouma.nineth.domain.RechargeOrder;
import com.izouma.nineth.domain.UserBankCard;
import com.izouma.nineth.domain.WalletRenewOrder;
import com.izouma.nineth.domain.WithdrawApply;
import com.izouma.nineth.dto.pay.UniformNotifyRequest;
import com.izouma.nineth.dto.pay.UniformNotifyResult;
import com.izouma.nineth.enums.FundChangeType;
import com.izouma.nineth.enums.PayStatus;
import com.izouma.nineth.enums.RechargeStatus;
import com.izouma.nineth.enums.WithdrawStatus;
import com.izouma.nineth.exception.BusinessException;
import com.izouma.nineth.lock.RedisLockable;
import com.izouma.nineth.repo.RechargeOrderRepo;
import com.izouma.nineth.repo.UserBankCardRepo;
import com.izouma.nineth.repo.WalletRenewOrderRepo;
import com.izouma.nineth.repo.WithdrawApplyRepo;
import com.izouma.nineth.service.pay.UniformPayConstants;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

/**
 * 通知消息适配
 */
@Service
@Slf4j
@AllArgsConstructor
public class UserFundAccountNotifyAdapter {

    private RechargeOrderRepo rechargeOrderRepo;

    private WithdrawApplyRepo withdrawApplyRepo;

    private UserBankCardRepo userBankCardRepo;

    private WalletRenewOrderRepo walletRenewOrderRepo;

    private UserFundAccountForSandpayService userFundAccountForSandpayService;

    private UserFundAccountForLianlianpayService userFundAccountForLianlianpayService;



    /**
     * 续费通知适配
     *
     * @param request
     * @return
     */
    @RedisLockable(prefix = RedisKeys.WALLET_PAY_CONFIRM_LOCK, key = "#request.orderNo",
            isWaiting = true, retryCount=20, retryWaitingTime = 100)
    public UniformNotifyResult renewNotify(UniformNotifyRequest request){
        UniformNotifyResult result = UniformNotifyResult.builder().build();
        result.setContent("ERROR");
        String orderNo = request.getOrderNo();
        WalletRenewOrder renewOrder = walletRenewOrderRepo.findByOrderNo(orderNo).orElseThrow(new BusinessException("续费订单未找到"));
        if(renewOrder.getStatus() == PayStatus.HAVE_PAID){
            result.setContent("Success");
        }

        if(renewOrder.getStatus() != PayStatus.PENDING){
            log.error("通知的续费订单状态不正确，orderNo:{}, status:{}", renewOrder.getOrderNo(), renewOrder.getStatus());
            //已处理过
            return result;
        }

        //判断钱包平台
        if(UniformPayConstants.LIANLIANPAY_PLATFORM.equals(renewOrder.getPayPlatform())){
            String content = userFundAccountForLianlianpayService.renewNotify(request);
            result.setContent(content);
        }else{
            log.error("续费通知失败，不支持的平台订单：{}", orderNo);
            throw new BusinessException("不支持的平台订单：" + orderNo);
        }

        return result;
    }


    /**
     * 统一通知适配
     *
     * @param request
     * @return
     */
    @RedisLockable(prefix = RedisKeys.WALLET_PAY_CONFIRM_LOCK, key = "#request.orderNo",
            isWaiting = true, retryCount=20, retryWaitingTime = 100)
    public UniformNotifyResult rechargeNotify(UniformNotifyRequest request){
        UniformNotifyResult result = UniformNotifyResult.builder().build();
        result.setContent("ERROR");
        String orderNo = request.getOrderNo();
        String reqData = request.getRequestBody();
        RechargeOrder rechargeOrder = rechargeOrderRepo.findByOrderNo(orderNo).orElseThrow(new BusinessException("充值订单未找到"));
        if(rechargeOrder.getStatus() == RechargeStatus.SUCCESS){
            result.setContent("Success");
        }
        if(rechargeOrder.getStatus() != RechargeStatus.PENDING){
            log.error("通知的充值订单状态不正确，orderNo:{}, status:{}", rechargeOrder.getOrderNo(), rechargeOrder.getStatus());
            //已处理过
            return result;
        }

        //判断钱包平台
        if(UniformPayConstants.SANDPAY_PLATFORM.equals(rechargeOrder.getPayPlatform())){
            JSONObject res = userFundAccountForSandpayService.rechargeNotify(orderNo, reqData);
            result.setContent(res.toJSONString());
        }else if(UniformPayConstants.LIANLIANPAY_PLATFORM.equals(rechargeOrder.getPayPlatform())){
            String content = userFundAccountForLianlianpayService.rechargeNotify(request);
            result.setContent(content);
        }else{
            log.error("充值通知失败，不支持的平台订单：{}", orderNo);
            throw new BusinessException("不支持的平台订单：" + orderNo);
        }

        return result;
    }

    /**
     * 提现通知适配
     *
     * @param request
     * @return
     */
    @RedisLockable(prefix = RedisKeys.WALLET_PAY_CONFIRM_LOCK, key = "#request.orderNo",
            isWaiting = true, retryCount=20, retryWaitingTime = 100)
    public UniformNotifyResult withdrawNotify(UniformNotifyRequest request){
        UniformNotifyResult result = UniformNotifyResult.builder().build();
        result.setContent("ERROR");
        String orderNo = request.getOrderNo();
        String reqData = request.getRequestBody();
        WithdrawApply withdrawApply = withdrawApplyRepo.findByOrderNo(orderNo).orElseThrow(new BusinessException("提现订单未找到"));
        if(withdrawApply.getStatus() == WithdrawStatus.SUCCESS){
            result.setContent("Success");
        }

        if(withdrawApply.getStatus() != WithdrawStatus.PENDING){
            log.error("通知的提现订单状态不正确，orderNo:{}, status:{}", withdrawApply.getOrderNo(), withdrawApply.getStatus());
            //已处理过
            return result;
        }

        //判断钱包平台
        if(UniformPayConstants.SANDPAY_PLATFORM.equals(withdrawApply.getPayPlatform())){
            JSONObject res = userFundAccountForSandpayService.withdrawNotify(orderNo, reqData);
            result.setContent(res.toJSONString());
        }else if(UniformPayConstants.LIANLIANPAY_PLATFORM.equals(withdrawApply.getPayPlatform())){
            String content = userFundAccountForLianlianpayService.withdrawNotify(request);
            result.setContent(content);
        }else{
            throw new BusinessException("不支持的平台订单：" + orderNo);
        }

        return result;
    }

    /**
     * 解绑卡通知适配
     *
     * @param request
     * @return
     */
    public UniformNotifyResult bindCardNotify(UniformNotifyRequest request){
        UniformNotifyResult result = UniformNotifyResult.builder().build();
        result.setContent("ERROR");
        String orderNo = request.getOrderNo();

        UserBankCard userBankCard = userBankCardRepo.findByBindOrderNo(orderNo).orElse(null);
        if(userBankCard == null){
            userBankCard = userBankCardRepo.findByUnbindOrderNo(orderNo).orElse(null);
        }

        if(userBankCard == null){
            log.error("未找到解绑卡记录:" + orderNo);
            return result;
        }

        //判断支付平台
        if(UniformPayConstants.LIANLIANPAY_PLATFORM.equals(userBankCard.getPayPlatform())){
            String content = userFundAccountForLianlianpayService.bindOrUnbindCardNotify(request);
            result.setContent(content);
        }else{
            throw new BusinessException("不支持的平台订单：" + orderNo);
        }

        return result;
    }


}
