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

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jeequan.jeepay.core.constants.CS;
import com.jeequan.jeepay.core.entity.MchApplyment;
import com.jeequan.jeepay.core.entity.MchInfo;
import com.jeequan.jeepay.core.entity.MchModifyApplyment;
import com.jeequan.jeepay.core.interfaces.paychannel.IIsvmchModifyApplymentService;
import com.jeequan.jeepay.core.model.applyment.DgpayApplymentInfo;
import com.jeequan.jeepay.core.model.applyment.MchModifyApplymentModel;
import com.jeequan.jeepay.core.model.applyment.PaywayFee;
import com.jeequan.jeepay.core.model.context.MchAppConfigContext;
import com.jeequan.jeepay.core.model.params.dgpay.DgpayIsvParams;
import com.jeequan.jeepay.service.impl.SysConfigService;
import com.jeequan.jeepay.thirdparty.service.ConfigContextQueryService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.tuple.MutablePair;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

@Slf4j
@Service
public class DgpayIsvmchModifyApplymentService implements IIsvmchModifyApplymentService {

    @Autowired
    protected SysConfigService sysConfigService;

    @Autowired
    private ConfigContextQueryService configContextQueryService;

    @Override
    public MutablePair<MchModifyApplyment, MchApplyment> localModifyBase(MutablePair<MchModifyApplyment, MchApplyment> mchDataPair) {
        MchModifyApplyment resultModifyApplyment = new MchModifyApplyment();
        MchApplyment resultMchApplyment = new MchApplyment();

        MchModifyApplyment mchModifyApplyment = mchDataPair.getKey();
        resultModifyApplyment.setModifyApplyId(mchModifyApplyment.getModifyApplyId());
        resultModifyApplyment.setState(MchApplyment.STATE_SUCCESS);
        MchApplyment mchApplyment = mchDataPair.getValue();
        resultMchApplyment.setApplyId(mchApplyment.getApplyId());

        String applyDetailInfo = mchModifyApplyment.getApplyDetailInfo();
        MchModifyApplymentModel mchModifyData = JSON.parseObject(applyDetailInfo, MchModifyApplymentModel.class);

        String originApplyDetailInfo = mchApplyment.getApplyDetailInfo();
        DgpayApplymentInfo originMchModifyData = JSON.parseObject(originApplyDetailInfo, DgpayApplymentInfo.class);
        resultMchApplyment.setApplyDetailInfo(JSON.toJSONString(originMchModifyData));

        originMchModifyData.setMchShortName(mchModifyData.getMchShortName());
        resultMchApplyment.setMchShortName(mchModifyData.getMchShortName());

        return new MutablePair<>(resultModifyApplyment, resultMchApplyment);
    }

    @Override
    public MutablePair<MchModifyApplyment, MchApplyment> localModifySettlement(MutablePair<MchModifyApplyment, MchApplyment> mchDataPair) {
        MchModifyApplyment resultModifyApplyment = new MchModifyApplyment();
        MchApplyment resultMchApplyment = new MchApplyment();

        MchModifyApplyment mchModifyApplyment = mchDataPair.getKey();
        resultModifyApplyment.setModifyApplyId(mchModifyApplyment.getModifyApplyId());
        resultModifyApplyment.setState(MchApplyment.STATE_SUCCESS);
        MchApplyment mchApplyment = mchDataPair.getValue();
        resultMchApplyment.setApplyId(mchApplyment.getApplyId());

        String applyDetailInfo = mchModifyApplyment.getApplyDetailInfo();
        MchModifyApplymentModel mchModifyData = JSON.parseObject(applyDetailInfo, MchModifyApplymentModel.class);

        String originApplyDetailInfo = mchApplyment.getApplyDetailInfo();
        DgpayApplymentInfo originMchModifyData = JSON.parseObject(originApplyDetailInfo, DgpayApplymentInfo.class);
        resultMchApplyment.setApplyDetailInfo(JSON.toJSONString(originMchModifyData));

        originMchModifyData.setSettAccountType(mchModifyData.getSettAccountType());
        if ("Y".equals(mchModifyData.getIllegal())) {
            originMchModifyData.setSettAccountIdcardNo(mchModifyData.getSettAccountIdcardNo());
            originMchModifyData.setSettAccountIdcard1Img(mchModifyData.getSettAccountIdcard1Img());
            originMchModifyData.setSettAccountIdcard2Img(mchModifyData.getSettAccountIdcard2Img());
            originMchModifyData.setSettAccountIdcardEffectBegin(mchModifyData.getSettAccountIdcardEffectBegin());
            originMchModifyData.setSettAccountIdcardEffectEnd(mchModifyData.getSettAccountIdcardEffectEnd());
        }

        originMchModifyData.setSettAccountLicenseImg(mchModifyData.getSettAccountLicenseImg());
        originMchModifyData.setSettAccountName(mchModifyData.getSettAccountName());
        originMchModifyData.setSettAccountNo(mchModifyData.getSettAccountNo());
        originMchModifyData.setSettAccountBankName(mchModifyData.getSettAccountBankName());
        originMchModifyData.setAuthEnturstPic(mchModifyData.getNonLegSettleAuthPic());

        return new MutablePair<>(resultModifyApplyment, resultMchApplyment);
    }

    @Override
    public MutablePair<MchModifyApplyment, MchApplyment> localModifyRate(MutablePair<MchModifyApplyment, MchApplyment> mchDataPair) {
        return null;
    }

    @Override
    public MutablePair<MchModifyApplyment, MchApplyment> syncChannelModifyBase(MutablePair<MchModifyApplyment, MchApplyment> mchDataPair) {
        MchModifyApplyment resultModifyApplyment = new MchModifyApplyment();

        MchModifyApplyment mchModifyApplyment = mchDataPair.getKey();
        resultModifyApplyment.setModifyApplyId(mchModifyApplyment.getModifyApplyId());
        resultModifyApplyment.setState(MchApplyment.STATE_AUDITING);
        MchApplyment mchApplyment = mchDataPair.getValue();

        String applyDetailInfo = mchModifyApplyment.getApplyDetailInfo();
        MchModifyApplymentModel mchModifyData = JSON.parseObject(applyDetailInfo, MchModifyApplymentModel.class);

        DgpayIsvParams isvParams = ((DgpayIsvParams) configContextQueryService.queryIsvParams(mchApplyment));

        JSONObject param = new JSONObject();
        Date today = new Date();
        String formatDate = DateUtil.format(today, DatePattern.PURE_DATE_PATTERN);
        param.put("req_seq_id", formatDate + mchModifyApplyment.getApplyId());
        param.put("req_date", formatDate);
        param.put("upper_huifu_id", isvParams.getSysId());
        param.put("huifu_id", mchApplyment.getChannelMchNo());
        param.put("short_name", mchModifyData.getMchShortName());
        param.put("async_return_url", getCallbackUrl(mchApplyment.getIfCode()));

        JSONObject agreementInfo = new JSONObject();
        agreementInfo.put("agreement_type", "0");
        param.put("agreement_info", agreementInfo.toJSONString());

        JSONObject signUserInfo = new JSONObject();
        param.put("sign_user_info", signUserInfo);

        DgpayApplymentInfo applymentInfo = JSON.parseObject(mchApplyment.getApplyDetailInfo(), DgpayApplymentInfo.class);
        switch (applymentInfo.getSettAccountType()) {
            case "B":
            case "C":
                // 对公
                signUserInfo.put("type", "LEGAL");
                signUserInfo.put("mobile_no", applymentInfo.getIdCardPhone());
                break;
            case "D":
                signUserInfo.put("type", "OTHER");
                signUserInfo.put("name", applymentInfo.getSettAccountName());
                signUserInfo.put("mobile_no", applymentInfo.getSettAccountBindPhone());
                signUserInfo.put("cert_no", applymentInfo.getSettAccountIdcardNo());
                break;
        }

        MchAppConfigContext mchAppConfigContext = new MchAppConfigContext();
        mchAppConfigContext.setMchType(MchInfo.TYPE_ISVSUB);
        mchAppConfigContext.setMchApplyment(mchApplyment);

        try {
            JSONObject applyResp = DgPayKit.request(mchAppConfigContext, param, DgPayKit.MCH_APPLY_MODIFY_URL, mchApplyment.getIfCode());
            JSONObject applyRespData = applyResp.getJSONObject("data");
            String code = applyRespData.getString("sub_resp_code");
            String msg = applyRespData.getString("sub_resp_desc");

            if ("00000000".equals(code)) {
                // 请求成功
                String applyNo = applyRespData.getString("apply_no");
                resultModifyApplyment.setChannelApplyNo(applyNo);
                resultModifyApplyment.setState(MchApplyment.STATE_SUCCESS);
                return localModifyBase(new MutablePair<>(resultModifyApplyment, mchDataPair.right));
            } else if ("90000000".equals(code)) {
                // 审核中
                String applyNo = applyRespData.getString("apply_no");
                resultModifyApplyment.setChannelApplyNo(applyNo);
                resultModifyApplyment.setState(MchApplyment.STATE_AUDITING);
            } else {
                // 其他暂定为失败
                resultModifyApplyment.setApplyErrorInfo("[" + msg + "]");
                resultModifyApplyment.setState(MchApplyment.STATE_REJECT_WAIT_MODIFY);
            }

            resultModifyApplyment.setChannelVar1(applyRespData.toJSONString());

            String remark = "斗拱支付基本信息变更已发起";
            resultModifyApplyment.setRemark(remark);
            log.debug("斗拱支付基本信息变更发起成功");
        } catch (Exception e) {
            resultModifyApplyment.setApplyErrorInfo("[" + e.getMessage() + "]");
            resultModifyApplyment.setState(MchApplyment.STATE_REJECT_WAIT_MODIFY);
        }

        return new MutablePair<>(resultModifyApplyment, null);
    }

    @Override
    public MutablePair<MchModifyApplyment, MchApplyment> syncChannelModifySettlement(MutablePair<MchModifyApplyment, MchApplyment> mchDataPair) {
        MchModifyApplyment resultModifyApplyment = new MchModifyApplyment();

        MchModifyApplyment mchModifyApplyment = mchDataPair.getKey();
        resultModifyApplyment.setModifyApplyId(mchModifyApplyment.getModifyApplyId());
        resultModifyApplyment.setState(MchApplyment.STATE_AUDITING);
        MchApplyment mchApplyment = mchDataPair.getValue();

        String applyDetailInfo = mchModifyApplyment.getApplyDetailInfo();
        MchModifyApplymentModel mchModifyData = JSON.parseObject(applyDetailInfo, MchModifyApplymentModel.class);

        DgpayIsvParams isvParams = ((DgpayIsvParams) configContextQueryService.queryIsvParams(mchApplyment));

        JSONObject param = new JSONObject();
        Date today = new Date();
        String formatDate = DateUtil.format(today, DatePattern.PURE_DATE_PATTERN);
        param.put("req_seq_id", formatDate + mchModifyApplyment.getApplyId());
        param.put("req_date", formatDate);
        param.put("upper_huifu_id", isvParams.getSysId());
        param.put("huifu_id", mchApplyment.getChannelMchNo());

        param.put("async_return_url", getCallbackUrl(mchApplyment.getIfCode()));

        JSONObject cardInfo = new JSONObject();

        if ("B".equals(mchModifyData.getSettAccountType())) {
            String f13 = DgPayKit.uploadFile(mchApplyment.getIsvNo(), "F13", mchModifyData.getSettAccountLicenseImg(), mchApplyment.getIfCode());
            cardInfo.put("settle_card_front_pic", f13);
        } else {
            String f08 = DgPayKit.uploadFile(mchApplyment.getIsvNo(), "F08", mchModifyData.getChangeFormPic(), mchApplyment.getIfCode());
            cardInfo.put("reg_acct_pic", f08);
        }
        String f55 = DgPayKit.uploadFile(mchApplyment.getIsvNo(), "F55", mchModifyData.getSettAccountIdcard1Img(), mchApplyment.getIfCode());
        cardInfo.put("settle_cert_front_pic", f55);
        String f56 = DgPayKit.uploadFile(mchApplyment.getIsvNo(), "F56", mchModifyData.getSettAccountIdcard2Img(), mchApplyment.getIfCode());
        cardInfo.put("settle_cert_back_pic", f56);
        String f15 = DgPayKit.uploadFile(mchApplyment.getIsvNo(), "F15", mchModifyData.getNonLegSettleAuthPic(), mchApplyment.getIfCode());
        cardInfo.put("auth_enturst_pic", f15);

        param.put("card_info", cardInfo);
        if ("Y".equals(mchModifyData.getIllegal())) {
            cardInfo.put("card_type", "2");
        } else {
            if ("B".equals(mchModifyData.getSettAccountType())) {
                cardInfo.put("card_type", "0");
            } else {
                cardInfo.put("card_type", "1");
            }
        }

        if (!"B".equals(mchModifyData.getSettAccountType())) {
            cardInfo.put("prov_id", mchModifyData.getSettAccountBankBranchAreaCode().getString(0));
            cardInfo.put("area_id", mchModifyData.getSettAccountBankBranchAreaCode().getString(1));
        } else {
            cardInfo.put("branch_code", mchModifyData.getBankSubCode());
            cardInfo.put("branch_name", mchModifyData.getSettAccountBankBranchName());
        }

        cardInfo.put("card_name", mchModifyData.getSettAccountName());
        cardInfo.put("card_no", mchModifyData.getSettAccountNo());
        cardInfo.put("bank_code", mchModifyData.getBankCode());

        if ("Y".equals(mchModifyData.getIllegal())) {
            cardInfo.put("cert_validity_type", mchModifyData.getSettAccountIdcardEffectEnd().equals("长期")? "1": "0");
            cardInfo.put("cert_begin_date", mchModifyData.getSettAccountIdcardEffectBegin().replace("-", ""));
            if (!mchModifyData.getSettAccountIdcardEffectEnd().equals("长期")) {
                cardInfo.put("cert_end_date", mchModifyData.getSettAccountIdcardEffectEnd().replace("-", ""));
            }
            cardInfo.put("cert_no", mchModifyData.getSettAccountIdcardNo());
            cardInfo.put("cert_type", "00");
            cardInfo.put("mp", mchModifyData.getPhone());
        }


        if ("Y".equals(mchModifyData.getIllegal())) {
            cardInfo.put("card_type", "2");
        }

        cardInfo.put("card_type", mchModifyData.getMchShortName());
        cardInfo.put("receipt_name", mchModifyData.getMchShortName());
        param.put("deal_type", "1");

        JSONObject agreementInfo = new JSONObject();
        agreementInfo.put("agreement_type", "0");
        param.put("agreement_info", agreementInfo.toJSONString());

        MchAppConfigContext mchAppConfigContext = new MchAppConfigContext();
        mchAppConfigContext.setMchType(MchInfo.TYPE_ISVSUB);
        mchAppConfigContext.setMchApplyment(mchApplyment);

        try {
            JSONObject applyResp = DgPayKit.request(mchAppConfigContext, param, DgPayKit.MCH_APPLY_MODIFY_URL, mchApplyment.getIfCode());
            JSONObject applyRespData = applyResp.getJSONObject("data");
            String code = applyRespData.getString("sub_resp_code");
            String msg = applyRespData.getString("sub_resp_desc");

            if ("00000000".equals(code)) {
                // 请求成功
                String applyNo = applyRespData.getString("apply_no");
                resultModifyApplyment.setChannelApplyNo(applyNo);
                resultModifyApplyment.setState(MchApplyment.STATE_AUDITING);
            } else if ("90000000".equals(code)) {
                // 审核中
                String applyNo = applyRespData.getString("apply_no");
                resultModifyApplyment.setChannelApplyNo(applyNo);
                resultModifyApplyment.setState(MchApplyment.STATE_AUDITING);
            } else {
                // 其他暂定为失败
                resultModifyApplyment.setApplyErrorInfo("[" + msg + "]");
                resultModifyApplyment.setState(MchApplyment.STATE_REJECT_WAIT_MODIFY);
            }

            String changeSysFlowId = applyRespData.getString("changeSysFlowId");

            resultModifyApplyment.setChannelApplyNo(changeSysFlowId);
            resultModifyApplyment.setChannelVar1(applyRespData.toJSONString());
            resultModifyApplyment.setState(MchApplyment.STATE_AUDITING);

            String remark = "斗拱支付结算信息变更已发起";
            resultModifyApplyment.setRemark(remark);
            log.debug("斗拱支付结算信息变更发起成功");
        } catch (Exception e) {
            resultModifyApplyment.setApplyErrorInfo("[" + e.getMessage() + "]");
            resultModifyApplyment.setState(MchApplyment.STATE_REJECT_WAIT_MODIFY);
        }

        return new MutablePair<>(resultModifyApplyment, null);
    }

    @Override
    public MutablePair<MchModifyApplyment, MchApplyment> syncChannelModifyRate(MutablePair<MchModifyApplyment, MchApplyment> mchDataPair) {
        return null;
    }

    @Override
    public MutablePair<MchModifyApplyment, MchApplyment> syncChannelModifySettlementType(MutablePair<MchModifyApplyment, MchApplyment> mchDataPair) {
        MchModifyApplyment resultModifyApplyment = new MchModifyApplyment();

        MchModifyApplyment mchModifyApplyment = mchDataPair.getKey();
        resultModifyApplyment.setModifyApplyId(mchModifyApplyment.getModifyApplyId());
        resultModifyApplyment.setState(MchApplyment.STATE_AUDITING);
        MchApplyment mchApplyment = mchDataPair.getValue();

        String applyDetailInfo = mchModifyApplyment.getApplyDetailInfo();
        MchModifyApplymentModel mchModifyData = JSON.parseObject(applyDetailInfo, MchModifyApplymentModel.class);

        DgpayApplymentInfo applymentInfo = JSON.parseObject(mchDataPair.right.getApplyDetailInfo(), DgpayApplymentInfo.class);

        DgpayIsvParams isvParams = ((DgpayIsvParams) configContextQueryService.queryIsvParams(mchApplyment));

        JSONObject param = new JSONObject();
        Date today = new Date();
        String formatDate = DateUtil.format(today, DatePattern.PURE_DATE_PATTERN);
        param.put("req_seq_id", formatDate + mchModifyApplyment.getApplyId());
        param.put("req_date", formatDate);
        param.put("upper_huifu_id", isvParams.getSysId());
        param.put("huifu_id", mchApplyment.getChannelMchNo());

        JSONObject settleConfig = new JSONObject();
        settleConfig.put("settle_status", "1");
        settleConfig.put("settle_cycle", mchModifyData.getSettlementType());

        PaywayFee d0 = null;
        PaywayFee d1 = null;
        for (PaywayFee paywayFee : applymentInfo.getPaywayFeeList()) {
            if (CS.PAY_WAY_CODE.D0.equals(paywayFee.getFeeType())) {
                d0 = paywayFee;
            }
            if (CS.PAY_WAY_CODE.D1.equals(paywayFee.getFeeType())) {
                d1 = paywayFee;
            }
        }

        if (d1 != null) {
            settleConfig.put("fixed_ratio", DgpayApplymentInfo.convertRate(d1.getFeeRate()));
        } else {
            // 默认D1提现费率为0.01%
            settleConfig.put("fixed_ratio", "0.01");
        }

        param.put("settle_config", settleConfig.toJSONString());

        JSONObject signUserInfo = new JSONObject();
        signUserInfo.put("type", "LEGAL");
        signUserInfo.put("mobile_no", mchApplyment.getContactPhone());

        param.put("sign_user_info", signUserInfo);

        param.put("async_return_url", getCallbackUrl(mchApplyment.getIfCode()));

        JSONObject cashConfig = new JSONObject();
        param.put("deal_type", "2");

        cashConfig.put("switch_state", "0");
        cashConfig.put("cash_type", mchModifyData.getSettlementType());



        if (d0 != null) {
            cashConfig.put("fee_rate", DgpayApplymentInfo.convertRate(d0.getFeeRate()));
        } else {
            // 默认D0提现费率设置为 0.1%
            cashConfig.put("fee_rate", "0.10");
        }

        // 电子协议
        JSONObject agreementInfo = new JSONObject();
        agreementInfo.put("agreement_type", "0");
        param.put("agreement_info", agreementInfo.toJSONString());

        // 结算卡信息
        JSONObject cardInfoJson = new JSONObject();

        DgpayApplymentInfo info = JSON.parseObject(mchApplyment.getApplyDetailInfo(), DgpayApplymentInfo.class);
        String settAccountType = info.getSettAccountType();
        if ("B".equals(settAccountType)) {
            // 对公
            cardInfoJson.put("card_type", "0");
            // 持卡人证件类型 默认为身份证
            cardInfoJson.put("cert_type", "");
            // 银行编码
            cardInfoJson.put("bank_code", info.getBankCode());
            // 联行号
            cardInfoJson.put("branch_code", info.getBranchCode());
            // 支行名称
            cardInfoJson.put("branch_name", info.getBranchName());

            cardInfoJson.put("mp", "");

            // 签约人类型
//            signUserInfoJson.put("type", "LEGAL");

        } else if ("C".equals(settAccountType)) {
            cardInfoJson.put("mp", info.getSettAccountBindPhone());

            // 对私
            cardInfoJson.put("card_type", "1");
            // 持卡人证件类型 默认为身份证
            cardInfoJson.put("cert_type", "00");
            // 持卡人证件号码
            cardInfoJson.put("cert_no", info.getSettAccountIdcardNo());
            // 持卡人证件有效期类型
            cardInfoJson.put("cert_validity_type", info.getCertValidityType(info.getSettAccountIdcardEffectEnd()));
            // 持卡人证件有效期 起始
            cardInfoJson.put("cert_begin_date", info.getSettAccountIdcardEffectBegin().replace("-", ""));
            // 持卡人证件有效期 截止
            if (!"长期".equals(info.getSettAccountIdcardEffectEnd())) {
                cardInfoJson.put("cert_end_date", info.getSettAccountIdcardEffectEnd().replace("-", ""));
            }
            // 结算卡正面
//            fileJson.put("settle_card_front_pic", DgPayKit.uploadFile(mchApplyment.getIsvNo(), "F13", info.getSettAccountLicenseImg(), mchApplyment.getIfCode()));
//            // 结算卡反面
//            fileJson.put("settle_card_back_pic", DgPayKit.uploadFile(mchApplyment.getIsvNo(), "F14", info.getSettBankCardBackImg(), mchApplyment.getIfCode()));
//            // 结算人身份证人像面
//            fileJson.put("settle_cert_front_pic", DgPayKit.uploadFile(mchApplyment.getIsvNo(), "F55", info.getSettAccountIdcard1Img(), mchApplyment.getIfCode()));
//            // 结算人身份证国徽面
//            fileJson.put("settle_cert_back_pic", DgPayKit.uploadFile(mchApplyment.getIsvNo(), "F56", info.getSettAccountIdcard2Img(), mchApplyment.getIfCode()));
//            // 授权委托书
//            fileJson.put("auth_enturst_pic", DgPayKit.uploadFile(mchApplyment.getIsvNo(), "F15", info.getAuthEnturstPic(), mchApplyment.getIfCode()));
//
//            // 签约人类型
//            signUserInfoJson.put("type", "LEGAL");
        } else {
            cardInfoJson.put("mp", info.getSettAccountBindPhone());
            // 对私非法人
            cardInfoJson.put("card_type", "2");
            // 持卡人证件类型 默认为身份证
            cardInfoJson.put("cert_type", "00");
            // 持卡人证件号码
            cardInfoJson.put("cert_no", info.getSettAccountIdcardNo());
            // 持卡人证件有效期类型
            cardInfoJson.put("cert_validity_type", info.getCertValidityType(info.getSettAccountIdcardEffectEnd()));
            // 持卡人证件有效期 起始
            cardInfoJson.put("cert_begin_date", info.getSettAccountIdcardEffectBegin().replace("-", ""));
            // 持卡人证件有效期 截止
            if (!"长期".equals(info.getSettAccountIdcardEffectEnd())) {
                cardInfoJson.put("cert_end_date", info.getSettAccountIdcardEffectEnd().replace("-", ""));
            }
//            // 结算卡正面
//            fileJson.put("settle_card_front_pic", DgPayKit.uploadFile(mchApplyment.getIsvNo(), "F13", info.getSettAccountLicenseImg(), mchApplyment.getIfCode()));
//            // 结算卡反面
//            fileJson.put("settle_card_back_pic", DgPayKit.uploadFile(mchApplyment.getIsvNo(), "F14", info.getSettBankCardBackImg(), mchApplyment.getIfCode()));
//            // 结算人身份证人像面
//            fileJson.put("settle_cert_front_pic", DgPayKit.uploadFile(mchApplyment.getIsvNo(), "F55", info.getSettAccountIdcard1Img(), mchApplyment.getIfCode()));
//            // 结算人身份证国徽面
//            fileJson.put("settle_cert_back_pic", DgPayKit.uploadFile(mchApplyment.getIsvNo(), "F56", info.getSettAccountIdcard2Img(), mchApplyment.getIfCode()));
//            // 授权委托书
//            fileJson.put("auth_enturst_pic", DgPayKit.uploadFile(mchApplyment.getIsvNo(), "F15", info.getAuthEnturstPic(), mchApplyment.getIfCode()));
//            // 签约人法人授权书
//            fileJson.put("sign_auth_file_id", DgPayKit.uploadFile(mchApplyment.getIsvNo(), "F245", info.getSignAuthFileId(), mchApplyment.getIfCode()));
//
//            // 签约人类型
//            signUserInfoJson.put("type", "OTHER");
        }
        // 卡户名
        cardInfoJson.put("card_name", info.getSettAccountName());
        // 银行卡号
        cardInfoJson.put("card_no", info.getSettAccountNo());
        // 银行所在省
        cardInfoJson.put("prov_id", info.getSettAccountBankBranchAreaCode().get(0));
        // 银行所在市
        cardInfoJson.put("area_id", info.getSettAccountBankBranchAreaCode().get(1));
        // 银行卡绑定手机号
        cardInfoJson.put("mp", info.getSettAccountBindPhone());

        param.put("card_info", cardInfoJson.toJSONString());

        JSONArray casArr = new JSONArray();
        casArr.add(cashConfig);
        param.put("cash_config", casArr.toJSONString());
        MchAppConfigContext mchAppConfigContext = new MchAppConfigContext();
        mchAppConfigContext.setMchType(MchInfo.TYPE_ISVSUB);
        mchAppConfigContext.setMchApplyment(mchApplyment);

        try {
            JSONObject applyResp = DgPayKit.request(mchAppConfigContext, param, DgPayKit.MCH_APPLY_MODIFY_URL, mchApplyment.getIfCode());
            JSONObject applyRespData = applyResp.getJSONObject("data");
            String code = applyRespData.getString("resp_code");
            String msg = applyRespData.getString("resp_desc");

            if ("00000000".equals(code)) {
                // 请求通过
                String applyNo = applyRespData.getString("apply_no");
                resultModifyApplyment.setChannelApplyNo(applyNo);
                resultModifyApplyment.setState(MchApplyment.STATE_SUCCESS);

                return localModifySettlementType(mchDataPair);
            } else if ("90000000".equals(code)) {
                String applyNo = applyRespData.getString("apply_no");
                resultModifyApplyment.setChannelApplyNo(applyNo);
                resultModifyApplyment.setState(MchApplyment.STATE_AUDITING);
            } else {
                resultModifyApplyment.setState(MchApplyment.STATE_REJECT_WAIT_MODIFY);
                resultModifyApplyment.setApplyErrorInfo("[" + msg + "]");
            }

            resultModifyApplyment.setChannelVar1(applyRespData.toJSONString());

            String remark = "斗拱支付结算方式变更已发起";
            resultModifyApplyment.setRemark(remark);
            log.info("斗拱支付结算方式变更发起成功");
        } catch (Exception e) {
            resultModifyApplyment.setApplyErrorInfo("[" + e.getMessage() + "]");
            resultModifyApplyment.setState(MchApplyment.STATE_REJECT_WAIT_MODIFY);
        }

        return new MutablePair<>(resultModifyApplyment, null);
    }

    @Override
    public MutablePair<MchModifyApplyment, MchApplyment> queryModifyResult(MutablePair<MchModifyApplyment, MchApplyment> mchDataPair) {
        MchModifyApplyment resultModifyApplyment = new MchModifyApplyment();

        MchModifyApplyment modifyApplyment = mchDataPair.getLeft();
        resultModifyApplyment.setModifyApplyId(modifyApplyment.getModifyApplyId());

        MchApplyment mchApplyment = mchDataPair.getValue();

        JSONObject reqParams = new JSONObject();
        reqParams.put("huifu_id", mchApplyment.getChannelMchNo());
        reqParams.put("apply_no", modifyApplyment.getChannelApplyNo());

        MchAppConfigContext mchAppConfigContext = new MchAppConfigContext();
        mchAppConfigContext.setMchType(MchInfo.TYPE_ISVSUB);
        mchAppConfigContext.setMchApplyment(mchApplyment);

        // 发送请求
        JSONObject response = DgPayKit.request(mchAppConfigContext, reqParams, DgPayKit.MCH_APPLY_QUERY_URL, mchApplyment.getIfCode());

        JSONObject bizData = response.getJSONObject("data");
        String code = bizData.getString("resp_code");
        if ("00000000".equals(code)) {
            String applStatus = bizData.getString("apply_status");
            if ("Y".equals(applStatus)) {
                // 审核通过
                resultModifyApplyment.setChannelVar1(processChannelValue(modifyApplyment.getChannelVar1(), bizData));
                return handleSuccessCase(modifyApplyment, mchDataPair);
            }
            if ("N".equals(applStatus) || "F".equals(applStatus)) {
                resultModifyApplyment.setChannelVar1(processChannelValue(modifyApplyment.getChannelVar1(), bizData));
                resultModifyApplyment.setState(MchApplyment.STATE_REJECT_WAIT_MODIFY);
                resultModifyApplyment.setApplyErrorInfo("[" + bizData.getString("note") + "]");

                return new MutablePair<>(resultModifyApplyment, null);
            }

            if ("P".equals(applStatus)) {
                // 审核中，需要查询签约状态
                JSONObject signReqParams = new JSONObject();
                signReqParams.put("huifu_id", mchApplyment.getChannelMchNo());
                JSONObject signResp = DgPayKit.request(mchAppConfigContext, signReqParams, DgPayKit.MCH_INFO_QUERY_URL, mchApplyment.getIfCode());
                JSONObject signRespBizData = signResp.getJSONObject("data");
                String respCode = signRespBizData.getString("resp_code");

                if ("00000000".equals(respCode)) {
                    JSONArray agreementInfoList = signRespBizData.getJSONArray("agreement_info_list");

                    JSONObject item = agreementInfoList.getJSONObject(0);

                    String conStat = item.getString("con_stat");

                    if ("3".equals(conStat)) {
                        // 待签约
                        resultModifyApplyment.setState(MchApplyment.STATE_WAIT_SIGN);

                        return new MutablePair<>(resultModifyApplyment, null);
                    }

                    if ("5".equals(conStat)) {
                        // 签约完成
                        resultModifyApplyment.setState(MchApplyment.STATE_FINISH_SIGN);

                        return new MutablePair<>(resultModifyApplyment, null);
                    }
                }
            }
        }

        return mchDataPair;
    }

    private MutablePair<MchModifyApplyment, MchApplyment> handleSuccessCase(MchModifyApplyment modifyApplyment, MutablePair<MchModifyApplyment, MchApplyment> mchDataPair) {
        switch (modifyApplyment.getModifyApplyType()) {
            case MchModifyApplyment.MODIFY_TYPE_BASE:
                return localModifyBase(mchDataPair);
            case MchModifyApplyment.MODIFY_TYPE_SETTLEMENT:
                return localModifySettlement(mchDataPair);
            case MchModifyApplyment.MODIFY_TYPE_SETTLEMENT_TYPE:
                return localModifySettlementType(mchDataPair);
            default:
                return mchDataPair;
        }
    }

    private String processChannelValue(String channelVal, JSONObject bizData) {
        JSONObject channelValJSON = StrUtil.isEmptyIfStr(channelVal) ? new JSONObject() : JSON.parseObject(channelVal);
        channelValJSON.putAll(bizData);
        return channelValJSON.toJSONString();
    }

    protected String getCallbackUrl(String ifCode) {
        return sysConfigService.getDBApplicationConfig().getPaySiteUrl() + "/api/mchApplyment/notify/" + ifCode;
    }
}
