package com.jeequan.jeepay.thirdparty.channel.zftpay;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.domain.*;
import com.alipay.api.request.AlipayTradeOrderOnsettleQueryRequest;
import com.alipay.api.request.AlipayTradeOrderSettleRequest;
import com.alipay.api.request.AlipayTradeRoyaltyRelationBindRequest;
import com.alipay.api.response.AlipayTradeOrderOnsettleQueryResponse;
import com.alipay.api.response.AlipayTradeOrderSettleResponse;
import com.alipay.api.response.AlipayTradeRoyaltyRelationBindResponse;
import com.jeequan.jeepay.core.constants.CS;
import com.jeequan.jeepay.core.entity.*;
import com.jeequan.jeepay.core.exception.ChannelException;
import com.jeequan.jeepay.core.exception.openapi.ParamException;
import com.jeequan.jeepay.core.model.context.MchAppConfigContext;
import com.jeequan.jeepay.core.model.params.IsvParams;
import com.jeequan.jeepay.core.model.params.zftpay.ZftpayIsvParams;
import com.jeequan.jeepay.core.model.rqrs.msg.ChannelRetMsg;
import com.jeequan.jeepay.core.utils.AmountUtil;
import com.jeequan.jeepay.core.utils.SeqKit;
import com.jeequan.jeepay.thirdparty.channel.AbstractDivisionService;
import com.jeequan.jeepay.thirdparty.model.ZftpayClientWrapper;
import com.jeequan.jeepay.thirdparty.service.ConfigContextQueryService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * 直付通分账接口
 * @author crystal
 * @date 2024/04/18 18:45
 */
@Slf4j
@Service
public class ZftpayDivisionService extends AbstractDivisionService {

    @Autowired private ConfigContextQueryService configContextQueryService;

    @Override
    public String getIfCode() {
        return CS.IF_CODE.ZFTPAY;
    }

    @Override
    public boolean isSupport() {
        return true;
    }

    @Override
    public ChannelRetMsg bind(DivisionSubjectEx subjectEx, String isvNo) {
        ZftpayIsvParams isvParams = (ZftpayIsvParams)configContextQueryService.queryIsvParams(isvNo, getIfCode());
        AlipayClient alipayClient = ZftpayClientWrapper.buildZftpayClientWrapper(isvParams).getAlipayClient();
        AlipayTradeRoyaltyRelationBindRequest request = new AlipayTradeRoyaltyRelationBindRequest();
        AlipayTradeRoyaltyRelationBindModel model = new AlipayTradeRoyaltyRelationBindModel();
        subjectEx.setChannelDivisionNo(subjectEx.getChannelExt().getBankCardNo());
        model.setOutRequestNo(subjectEx.getDivisionNo());
        List<RoyaltyEntity> receiverList = new ArrayList<>();
        RoyaltyEntity receiver = new RoyaltyEntity();
        //默认写死吧
        receiver.setType("loginName");
        receiver.setBindLoginName(subjectEx.getChannelDivisionNo());
        receiver.setName(subjectEx.getChannelExt().getIdCardName());
        receiver.setLoginName(subjectEx.getChannelDivisionNo());
        receiver.setAccount(subjectEx.getChannelDivisionNo());
        receiver.setMemo(StringUtils.isNotEmpty(subjectEx.getRemark()) ? subjectEx.getRemark() :"分账收款方");
        receiverList.add(receiver);
        model.setReceiverList(receiverList);
        request.setBizModel(model);
        try {
            AlipayTradeRoyaltyRelationBindResponse response = alipayClient.execute(request);
            if (response.isSuccess()) {
                ChannelRetMsg retMsg = ChannelRetMsg.confirmSuccess(null);
                retMsg.setChannelAttach(subjectEx.getChannelExt().getBankCardNo());
                return retMsg;
            } else {
                return ChannelRetMsg.confirmFail(response.getSubCode(),response.getSubMsg());
            }
        } catch (AlipayApiException e) {
            return ChannelRetMsg.confirmFail(null,e.getErrMsg());
        }
    }

    @Override
    public ChannelRetMsg singleDivision(PayOrder payOrder, List<PayOrderDivisionRecord> recordList, MchAppConfigContext mchAppConfigContext) {
        try {
            AlipayClient alipayClient = configContextQueryService.getZftpayClientWrapper(mchAppConfigContext).getAlipayClient();
            AlipayTradeOrderSettleRequest request = new AlipayTradeOrderSettleRequest();
            AlipayTradeOrderSettleModel model = new AlipayTradeOrderSettleModel();
            // 设置结算请求流水号
            model.setOutRequestNo(SeqKit.genDivisionBatchId());
            // 设置支付宝订单号
            model.setTradeNo(payOrder.getChannelOrderNo());
            List<OpenApiRoyaltyDetailInfoPojo> royaltyParameters = new ArrayList<>();
            recordList.forEach(item -> {
                OpenApiRoyaltyDetailInfoPojo royaltyParameters0 = new OpenApiRoyaltyDetailInfoPojo();
                royaltyParameters0.setRoyaltyType("transfer");
                royaltyParameters0.setTransInType("loginName");
                royaltyParameters0.setTransInName(item.getAccName());
                royaltyParameters0.setTransIn(item.getChannelAccNo());
                royaltyParameters0.setAmount(AmountUtil.convertCent2Dollar(item.getCalDivisionAmount()));
                royaltyParameters0.setDesc(StringUtils.isNotEmpty(item.getRemark()) ? item.getRemark() : "订单分账");
                royaltyParameters.add(royaltyParameters0);
            });
            model.setRoyaltyParameters(royaltyParameters);
            request.setBizModel(model);
            AlipayTradeOrderSettleResponse response = alipayClient.execute(request);
            if(response.isSuccess()){
                return ChannelRetMsg.confirmSuccess(response.getSettleNo());
            }
            return ChannelRetMsg.confirmFail().setChannelErrCode(response.getSubCode()).setChannelErrMsg(response.getSubMsg());
        } catch (ChannelException e) {
            ChannelRetMsg channelRetMsg = ChannelRetMsg.confirmFail();
            channelRetMsg.setChannelErrCode(e.getChannelRetMsg().getChannelErrCode());
            channelRetMsg.setChannelErrMsg(e.getChannelRetMsg().getChannelErrMsg());
            return channelRetMsg;
        } catch (Exception e) {
            log.error("直付通分账异常", e);
            ChannelRetMsg channelRetMsg = ChannelRetMsg.confirmFail();
            channelRetMsg.setChannelErrMsg(e.getMessage());
            return channelRetMsg;
        }
    }

    @Override
    public ChannelRetMsg divisionRefund(PayOrderDivisionRecord payOrderDivisionRecord, PayOrderDivisionRefundRecord payOrderDivisionRefundRecord, RefundOrder refundOrder, PayOrder payOrder, MchAppConfigContext mchAppConfigContext) {
        return null;
    }

    @Override
    public Long queryBalanceAmount(MchDivisionReceiver mchDivisionReceiver, MchAppConfigContext mchAppConfigContext) {
        AlipayClient alipayClient = configContextQueryService.getZftpayClientWrapper(mchAppConfigContext).getAlipayClient();
        AlipayTradeOrderOnsettleQueryRequest request = new AlipayTradeOrderOnsettleQueryRequest();
        AlipayTradeOrderOnsettleQueryModel model = new AlipayTradeOrderOnsettleQueryModel();
        //TODO 这里有问题
        model.setTradeNo(mchDivisionReceiver.getChannelAccNo());
        request.setBizModel(model);
        try {
            AlipayTradeOrderOnsettleQueryResponse response = alipayClient.execute(request);
            if(response.isSuccess()){
                return AmountUtil.convertDollar2CentLong(response.getUnsettledAmount());
            } else {
                throw new ParamException(response.getSubMsg());
            }
        } catch (AlipayApiException e) {
            throw new ParamException(e.getErrMsg());
        }
    }

    @Override
    public ChannelRetMsg cashout(MchDivisionReceiver mchDivisionReceiver, Long amount, MchAppConfigContext mchAppConfigContext) {
        return null;
    }

}
