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

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
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.exception.BizException;
import com.jeequan.jeepay.core.interfaces.paychannel.IIsvmchApplymentService;
import com.jeequan.jeepay.core.model.DBApplicationConfig;
import com.jeequan.jeepay.core.model.applyment.ApplymentSignInfo;
import com.jeequan.jeepay.core.model.applyment.DgpayApplymentInfo;
import com.jeequan.jeepay.core.model.applyment.PaywayFee;
import com.jeequan.jeepay.core.model.context.MchAppConfigContext;
import com.jeequan.jeepay.core.model.oauth2.WxpayOauth2Params;
import com.jeequan.jeepay.core.model.params.dgpay.DgpayIsvParams;
import com.jeequan.jeepay.core.model.params.dgpay.DgpayIsvsubMchParams;
import com.jeequan.jeepay.core.utils.DateKit;
import com.jeequan.jeepay.core.utils.JsonKit;
import com.jeequan.jeepay.service.impl.RateConfigService;
import com.jeequan.jeepay.service.impl.SysConfigService;
import com.jeequan.jeepay.thirdparty.channel.dgpay.utils.DgUtils;
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.Date;
import java.util.List;

/**
 * 斗拱接口进件
 *
 * @author xiaoyu
 * @date 2022/6/7 10:23
 */
@Service
@Slf4j
public class DgpayMchApplymentService implements IIsvmchApplymentService<DgpayApplymentInfo> {

    @Autowired
    protected SysConfigService sysConfigService;

    @Autowired
    private ConfigContextQueryService configContextQueryService;

    @Autowired
    private RateConfigService rateConfigService;

    @Override
    public MchApplyment firstApplyment(MchApplyment mchApplyment) {
        // 直接丢到异步处理进件逻辑, 通用请求可照此逻辑
        MchApplyment result = new MchApplyment();
        result.setApplyId(mchApplyment.getApplyId());
        result.setState(com.jeequan.jeepay.core.entity.MchApplyment.STATE_AUDITING_WAIT);
        result.setRemainStep((byte) 1);

        DgpayApplymentInfo applymentInfo = JSON.parseObject(mchApplyment.getApplyDetailInfo(), DgpayApplymentInfo.class);
        result.setSettlementType(applymentInfo.getSettleCycle());

        return result;
    }

    @Override
    public MchApplyment rejectModify(MchApplyment mchApplyment) {
        String logPrefix = "【斗拱商户进件】";
        MchApplyment result = new MchApplyment();
        try {

            // 如果未进件成功执行第一次进件方法
            String succResParameter = mchApplyment.getSuccResParameter();
            if (StringUtils.isEmpty(succResParameter)) {
                return firstApplyment(mchApplyment);
            }

            JSONObject succJson = JSON.parseObject(succResParameter);
            String huifuId = succJson.getString("huifuId");
            // 缺少必要参数 执行第一次进件
            if (StringUtils.isEmpty(huifuId)) {
                return firstApplyment(mchApplyment);
            }

            // 获取支付参数
            MchAppConfigContext mchAppConfigContext = new MchAppConfigContext();
            mchAppConfigContext.setMchType(MchInfo.TYPE_ISVSUB);
            mchAppConfigContext.setMchApplyment(mchApplyment);
            // 获取详细参数
            JSONObject reqParams = getApplymentParams(mchApplyment);
            reqParams.put("huifu_id", huifuId);
            // 业务处理类型 1：基本信息修改 2：业务开通 3：业务修改 4：审核材料补充（审核材料补充除必填字段外仅需要传入file_info字段）
            reqParams.put("deal_type", "3");

            // 发送请求
            JSONObject response = DgPayKit.request(mchAppConfigContext, reqParams, DgPayKit.MCH_APPLY_UPDATE_URL, mchApplyment.getIfCode());
            JSONObject resData = response.getJSONObject("data");
            String code = resData.getString("resp_code");
            if ("00000000".equals(code)) {
                // 渠道号
                String channelOrderNo = resData.getString("apply_no");
                result.setChannelApplyNo(channelOrderNo);
                // 进件响应参数
                result.setChannelVar1(resData.toJSONString());
                result.setState(MchApplyment.STATE_AUDITING);
            } else if ("90000000".equals(code)) {
                result.setState(MchApplyment.STATE_AUDITING);
            } else {
                result.setState(MchApplyment.STATE_REJECT_WAIT_MODIFY);
                result.setApplyErrorInfo(code + "[" + resData.getString("resp_desc") + "]");
                log.error("{} 请求失败：code={}, msg={}", logPrefix, code, resData.getString("resp_desc"));
                return result;
            }

        } catch (Exception e) {
            result.setState(MchApplyment.STATE_REJECT_WAIT_MODIFY);
            result.setApplyErrorInfo("[" + e.getMessage() + "]");
            log.error("{} 进件失败：", logPrefix, e);
        }
        return result;
    }

    @Override
    public MchApplyment replenishInfo(MchApplyment mchApplyment) {
        return null;
    }

    @Override
    public MchApplyment query(MchApplyment mchApplyment) {
        String logPrefix = "【斗拱商户进件状态查询】";
        MchApplyment result = new MchApplyment();
        try {
            String succResParameter = mchApplyment.getSuccResParameter();
            JSONObject succJson = JSON.parseObject(succResParameter);
            String huifuId = succJson.getString("huifuId");
            // 获取支付参数
            MchAppConfigContext mchAppConfigContext = new MchAppConfigContext();
            mchAppConfigContext.setMchType(MchInfo.TYPE_ISVSUB)
                    .setMchApplyment(mchApplyment);

            // 请求参数
            JSONObject reqParams = new JSONObject();
            reqParams.put("huifu_id", huifuId);
            reqParams.put("apply_no", mchApplyment.getChannelApplyNo());
            reqParams.put("req_date", DateUtil.format(new Date(), DatePattern.PURE_DATE_PATTERN));
            reqParams.put("req_seq_id", DateKit.currentTimeMillis());
            // 发送请求
            JSONObject response = DgPayKit.request(mchAppConfigContext, reqParams, DgPayKit.MCH_APPLY_QUERY_URL, mchApplyment.getIfCode());

            JSONObject resData = response.getJSONObject("data");
            String code = resData.getString("resp_code");
            if ("00000000".equals(code)) {
                String applStatus = resData.getString("apply_status");
                // 入驻状态
                String regStatus = resData.getString("reg_status");
                if ("Y".equals(applStatus)) {
                    // 进件查询响应参数
//                    result.setChannelVar1(resData.toJSONString());
                    // 更新错误信息
                    result.setApplyErrorInfo("");
                    result.setState(MchApplyment.STATE_WAIT_SIGN);
                    if ("S".equals(regStatus)) {
                        // 入驻成功
//                        result.setChannelVar2(resData.toJSONString());
                        result.setState(MchApplyment.STATE_SUCCESS);
                        result.setChannelMchNo(huifuId);

                        // 参数重写 商户号+绑卡序列号
                        queryMchInfo(result, mchAppConfigContext, huifuId, mchApplyment.getIfCode());

                    } else {
                        result.setApplyErrorInfo(code + "[" + resData.getString("apply_reason") + "]");
                    }
                } else if ("P".equals(applStatus)) {
                    if ("S".equals(regStatus)) {
                        result.setState(MchApplyment.STATE_WAIT_SIGN);
                    } else {
                        result.setState(MchApplyment.STATE_AUDITING);
                    }
                } else {
                    result.setState(MchApplyment.STATE_REJECT_WAIT_MODIFY);
                    result.setApplyErrorInfo(code + "[" + resData.getString("apply_reason") + "]");
                }
            } else if ("90000000".equals(code)) {
                result.setState(MchApplyment.STATE_AUDITING);
            } else {
                result.setState(MchApplyment.STATE_REJECT_WAIT_MODIFY);
                result.setApplyErrorInfo(code + "[" + resData.getString("resp_desc") + "]");
                log.error("{} 请求失败：code={}, msg={}", logPrefix, code, resData.getString("resp_desc"));
                return result;
            }

        } catch (BizException e) {
            result.setState(MchApplyment.STATE_REJECT_WAIT_MODIFY);
            result.setApplyErrorInfo("[" + e.getMessage() + "]");
            log.error("{} 进件失败：", logPrefix, e);
        } catch (Exception e) {
            log.info("未知异常", e);
            throw new BizException(e.getMessage());
        }
        return result;
    }

    @Override
    public ApplymentSignInfo signInfo(MchApplyment mchApplyment) {
        return null;
    }

    public JSONObject getApplymentParams(MchApplyment mchApplyment) {
        // 获取支付参数
        DgpayIsvParams isvParams = (DgpayIsvParams) configContextQueryService.queryIsvParams(mchApplyment);
        // 获取详细参数
        DgpayApplymentInfo info = JSON.parseObject(mchApplyment.getApplyDetailInfo(), DgpayApplymentInfo.class);
        // 请求参数
        JSONObject reqParams = new JSONObject();
        // 文件信息
        JSONObject fileJson = new JSONObject();

        // 认证信息
        JSONObject realNameInfoJson = new JSONObject();
        // 请求日期
        reqParams.put("req_date", DateUtil.format(new Date(), DatePattern.PURE_DATE_PATTERN));
        // 业务申请编号
        reqParams.put("req_seq_id", DateKit.currentTimeMillis());
        // 渠道商户号
        reqParams.put("upper_huifu_id", isvParams.getSysId());
        // ONLINE：线上场景，OFFLINE：线下场景，ALL线上线下 场景类型
        reqParams.put("scene_type", "1".equals(isvParams.getPayScene()) ? "OFFLINE" : "ONLINE");

        // 实名认证类型
        realNameInfoJson.put("realname_info_type", "AW");
        // 支付场景 -- 线下场景
        realNameInfoJson.put("pay_scene", "1");

        if (CollUtil.isEmpty(info.getAreaCode())) {
            throw new BizException("请选择店铺经营省市区地址");
        }

        boolean bankAllow = DgUtils.checkBankLimitArea(info.getAreaCode().getString(0));

        // 经营地址 省
        reqParams.put("prov_id", info.getAreaCode().get(0));
        // 经营地址 市
        reqParams.put("area_id", info.getAreaCode().get(1));
        // 经营地址 区
        reqParams.put("district_id", info.getAreaCode().get(2));
        // 详细经营地址
        reqParams.put("detail_addr", info.getAddress());

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

        // 异步通知地址
        String notifyUrl = sysConfigService.getDBApplicationConfig().getPaySiteUrl() + "/api/mchApplyment/notify/" + CS.IF_CODE.DGPAY;
        reqParams.put("async_return_url", notifyUrl);
        reqParams.put("busi_async_return_url", notifyUrl);
        // 是否发送短信通知到商户 设置为发送
        reqParams.put("sms_send_flag", "A");

        // 卡信息
        JSONObject cardInfoJson = new JSONObject();
        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());

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

        } else if ("C".equals(settAccountType)) {
            // 对私
            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("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());
        // 结算卡信息
        reqParams.put("card_info", cardInfoJson);
        // 结算配置
        JSONObject settConfig = new JSONObject();
        // 结算周期
        settConfig.put("settle_cycle", info.getSettleCycle());
        // 起结金额
        settConfig.put("min_amt", "0.00");
        // 留存金额
        settConfig.put("remained_amt", "0.00");


        if ("D1".equals(info.getSettleCycle())) {
            // D1费率 [0.00 - 100.00]

            List<PaywayFee> paywayFeeList = info.getPaywayFeeList();
            for (PaywayFee paywayFee : paywayFeeList) {
                if (CS.PAY_WAY_CODE.D1.equals(paywayFee.getWayCode())) {
                    settConfig.put("fixed_ratio", DgpayApplymentInfo.convertRate(paywayFee.getFeeRate()));
                }
            }

            settConfig.put("fixed_ratio", isvParams.getSettleFee());
            // D1结算协议图片文件
            if (StringUtils.isNotEmpty(info.getSettleAgreePic())) {
                fileJson.put("settle_agree_pic", DgPayKit.uploadFile(mchApplyment.getIsvNo(), "F116", info.getSettleAgreePic(), mchApplyment.getIfCode()));
            }
        }
        reqParams.put("settle_config", settConfig.toJSONString());
        // 取现配置
        if (!"0".equals(isvParams.getMchSettManual())) {
            JSONObject cashJson = new JSONObject();
            // 取现类型
            cashJson.put("cash_type", isvParams.getMchSettManual());
            if (StringUtils.isNotEmpty(isvParams.getCashFee())) {
                cashJson.put("fee_rate", isvParams.getCashFee());
            } else {
                cashJson.put("fix_amt", "0.00");
                cashJson.put("fee_rate", "0.00");
            }
            JSONArray casArr = new JSONArray();
            casArr.add(cashJson);
            reqParams.put("cash_config", casArr.toJSONString());
        }

        if (StringUtils.isNotEmpty(info.getLoginUserName())) {
            // 管理员账号
            reqParams.put("login_name", info.getLoginUserName().trim());
        }

        // 所属行业MCC
        reqParams.put("mcc", info.getMccCode());

        // 个人商户
        if (info.getMerchantType() == 1) {
            // 个人商户
            reqParams.put("ent_type", "0");
            // 商户名
            reqParams.put("reg_name", info.getContactName());
            // 商户简称
            reqParams.put("short_name", info.getMchFullName());
            JSONObject contactInfoJson = new JSONObject();
            // 联系人姓名
            contactInfoJson.put("contact_name", info.getContactName());
            // 联系人手机号
            contactInfoJson.put("contact_mobile_no", info.getContactPhone());
            // 联系人邮箱
            contactInfoJson.put("contact_email", info.getContactEmail());
            // 联系人身份证号
            contactInfoJson.put("contact_cert_no", info.getContactIdcardNo());
            // 联系人信息
            reqParams.put("contact_info", contactInfoJson);
            // 签约人手机号
            signUserInfoJson.put("sign_mobile_no", info.getContactPhone());
            // 签约人姓名
            signUserInfoJson.put("name", info.getContactName());
            // 签约人手机号
            signUserInfoJson.put("mobile_no", info.getContactPhone());
            // 签约人身份证号
            signUserInfoJson.put("cert_no", info.getContactIdcardNo());
            // TODO **** 兼容 旧接口 ****
            // 签约人姓名
            signUserInfoJson.put("sign_name", info.getContactName());
            // 签约人身份证号
            signUserInfoJson.put("sign_cert_no", info.getContactIdcardNo());

            reqParams.put("sign_user_info", signUserInfoJson);

            // 联系人姓名
            realNameInfoJson.put("name", info.getContactName());
            // 联系人手机号
            realNameInfoJson.put("mobile", info.getContactPhone());
            // 联系人证件号
            realNameInfoJson.put("contact_id_card_number", info.getContactIdcardNo());

            // 法人身份证人像面照片
            fileJson.put("identification_front_pic", DgPayKit.uploadFile(mchApplyment.getIsvNo(), "F40", info.getIdcard1Img(), mchApplyment.getIfCode()));
            // 法人身份证国徽面照片
            fileJson.put("identification_back_pic", DgPayKit.uploadFile(mchApplyment.getIsvNo(), "F41", info.getIdcard2Img(), mchApplyment.getIfCode()));

        } else {
            // 公司类型
            reqParams.put("ent_type", info.getEntType());
            // 商户名称
            reqParams.put("reg_name", info.getMchFullName());
            // 商户英文名称
            reqParams.put("mer_en_name", info.getMerEnName());
            // 经营名称
            reqParams.put("short_name", info.getMchShortName());
            // 小票名称
            reqParams.put("receipt_name", info.getReceiptName());
            // 经营类型
            reqParams.put("busi_type", info.getBusiType());
            // 注册资本
            reqParams.put("reg_capital", info.getRegCapital());

            // 执照类型 NATIONAL_LEGAL-营业执照 NATIONAL_LEGAL_MERGE-多证合一
            reqParams.put("license_type", "NATIONAL_LEGAL");
            // 营业执照编号
            reqParams.put("license_code", info.getLicenseNo());
            // 经营范围
            reqParams.put("business_scope", info.getLicenseBusiness());

            // 营业执照有效期类型
            reqParams.put("license_validity_type", info.getCertValidityType(info.getLicenseEffectEnd()));
            // 营业执照有效期开始日期
            reqParams.put("license_begin_date", info.getLicenseEffectBegin().replace("-", ""));
            // 营业执照有效期截止日期
            if (!"长期".equals(info.getLicenseEffectEnd())) {
                reqParams.put("license_end_date", info.getLicenseEffectEnd().replace("-", ""));
            }

            JSONObject contactInfoJson = new JSONObject();
            // 联系人姓名
            contactInfoJson.put("contact_name", info.getIdcardName());
            // 联系人手机号
            contactInfoJson.put("contact_mobile_no", info.getIdCardPhone());
            // 联系人邮箱
            contactInfoJson.put("contact_email", info.getIdCardEmail());
            // 联系人身份证号
            contactInfoJson.put("contact_cert_no", info.getIdcardNo());
            // 联系人信息
            reqParams.put("contact_info", contactInfoJson);

            // 非法人结算签约人信息
            if (StringUtils.isNotEmpty(info.getSettAccountType()) && "D".equals(info.getSettAccountType())) {
                // 签约人手机号
                signUserInfoJson.put("sign_mobile_no", info.getSettAccountBindPhone());
                // 签约人姓名
                signUserInfoJson.put("name", info.getSettAccountName());
                // 签约人手机号
                signUserInfoJson.put("mobile_no", info.getSettAccountBindPhone());
                // 签约人身份证号
                signUserInfoJson.put("cert_no", info.getSettAccountIdcardNo());
                // TODO **** 兼容 旧接口 ****
                // 签约人姓名
                signUserInfoJson.put("sign_name", info.getSettAccountName());
                // 签约人身份证号
                signUserInfoJson.put("sign_cert_no", info.getSettAccountIdcardNo());

            } else {
                // 签约人手机号
                signUserInfoJson.put("sign_mobile_no", info.getIdCardPhone());
                signUserInfoJson.put("mobile_no", info.getIdCardPhone());
                // 签约人姓名
                signUserInfoJson.put("name", info.getIdcardName());
                // 签约人身份证号
                signUserInfoJson.put("cert_no", info.getIdcardNo());

                // TODO **** 兼容 旧接口 ****
                // 签约人姓名
                signUserInfoJson.put("sign_name", info.getIdcardName());
                // 签约人身份证号
                signUserInfoJson.put("sign_cert_no", info.getIdcardNo());
            }

            reqParams.put("sign_user_info", signUserInfoJson);

            // 联系人姓名
            realNameInfoJson.put("name", info.getIdcardName());
            // 联系人手机号
            realNameInfoJson.put("mobile", info.getIdCardPhone());
            // 联系人证件号
            realNameInfoJson.put("contact_id_card_number", info.getIdcardNo());

            // 注册 省
            reqParams.put("reg_prov_id", info.getAreaCode().get(0));
            // 注册 市
            reqParams.put("reg_area_id", info.getAreaCode().get(1));
            // 注册 区
            reqParams.put("reg_district_id", info.getAreaCode().get(2));
            // 注册地址
            reqParams.put("reg_detail", info.getAddress());

            // 法人信息
            JSONObject legalInfoJson = new JSONObject();
            // 法人姓名
            legalInfoJson.put("legal_name", info.getIdcardName());
            // 法人证件类型 默认身份证
            legalInfoJson.put("legal_cert_type", "00");
            // 法人证件号码
            legalInfoJson.put("legal_cert_no", info.getIdcardNo());
            // 法人手机号
            legalInfoJson.put("legal_mobile_no", info.getIdCardPhone());
            // 法人证件居住地
            legalInfoJson.put("legal_identification_address", info.getIdcardAddress());
            // 法人证件有效期类型
            legalInfoJson.put("legal_cert_validity_type", info.getCertValidityType(info.getIdcardEffectEnd()));
            // 法人证件有效期开始日期
            legalInfoJson.put("legal_cert_begin_date", info.getIdcardEffectBegin().replace("-", ""));
            if ("0".equals(info.getCertValidityType(info.getIdcardEffectEnd()))) {
                // 法人证件有效期截止日期
                legalInfoJson.put("legal_cert_end_date", info.getIdcardEffectEnd().replace("-", ""));
            }
            reqParams.put("legal_info", legalInfoJson);

            // 客服电话
            reqParams.put("service_phone", info.getServicePhone());

            // 门头照
            reqParams.put("store_header_pic", DgPayKit.uploadFile(mchApplyment.getIsvNo(), "F18", info.getStoreOuterImg(), mchApplyment.getIfCode()));
            // 内景照
            reqParams.put("store_indoor_pic", DgPayKit.uploadFile(mchApplyment.getIsvNo(), "F19", info.getStoreInnerImg(), mchApplyment.getIfCode()));
            // 收银台照
            reqParams.put("store_cashier_desk_pic", DgPayKit.uploadFile(mchApplyment.getIsvNo(), "F20", info.getStoreCashierImg(), mchApplyment.getIfCode()));

            // 开户许可证
            fileJson.put("reg_acct_pic", DgPayKit.uploadFile(mchApplyment.getIsvNo(), "F08", info.getCompanyAccountLicenseImg(), mchApplyment.getIfCode()));
            // 法人身份证人像面照片
            fileJson.put("legal_cert_front_pic", DgPayKit.uploadFile(mchApplyment.getIsvNo(), "F02", info.getIdcard1Img(), mchApplyment.getIfCode()));
            // 法人身份证国徽面照片
            fileJson.put("legal_cert_back_pic", DgPayKit.uploadFile(mchApplyment.getIsvNo(), "F03", info.getIdcard2Img(), mchApplyment.getIfCode()));
            // 营业执照
            fileJson.put("license_pic", DgPayKit.uploadFile(mchApplyment.getIsvNo(), "F07", info.getLicenseImg(), mchApplyment.getIfCode()));
            // 组织机构代码证
//                fileJson.put("org_code_pic", DgPayKit.uploadFile(mchApplyment.getIsvNo(), "F57", info.getOrgCodePic()));
            // 签约人身份证照片-人像照
            fileJson.put("sign_identity_front_file_id", DgPayKit.uploadFile(mchApplyment.getIsvNo(), "F244", info.getIdcard1Img(), mchApplyment.getIfCode()));
            // 签约人身份证照片-国徽照
            fileJson.put("sign_identity_back_file_id", DgPayKit.uploadFile(mchApplyment.getIsvNo(), "F247", info.getIdcard2Img(), mchApplyment.getIfCode()));
        }

        // 扩展资料包
        JSONArray extendedList = new JSONArray();
        if (StringUtils.isNotEmpty(info.getServiceAgreement())) {
            // 【商户】斗拱平台综合支付服务协议（纸质合同版）
            JSONObject paramJson = JsonKit.newJson("file_id", DgPayKit.uploadFile(mchApplyment.getIsvNo(), "F479", info.getServiceAgreement(), mchApplyment.getIfCode()));
            paramJson.put("file_type", "F479");
            extendedList.add(paramJson);
        }
        if (StringUtils.isNotEmpty(info.getPriceConfirmation())) {
            // 【商户】斗拱平台综合支付服务功能及价格确认表（纸质合同版）
            JSONObject paramJson = JsonKit.newJson("file_id", DgPayKit.uploadFile(mchApplyment.getIsvNo(), "F480", info.getPriceConfirmation(), mchApplyment.getIfCode()));
            paramJson.put("file_type", "F480");
            extendedList.add(paramJson);
        }
        if (StringUtils.isNotEmpty(info.getStoreInnerImg())) {
            // （线上场景）办公场所照片-工作区域
            JSONObject paramJson = JsonKit.newJson("file_id", DgPayKit.uploadFile(mchApplyment.getIsvNo(), "F371", info.getStoreInnerImg(), mchApplyment.getIfCode()));
            paramJson.put("file_type", "F371");
            extendedList.add(paramJson);
        }
        if (StringUtils.isNotEmpty(info.getStoreOuterImg())) {
            // （线上场景）办公场所照片-公司前台
            JSONObject paramJson = JsonKit.newJson("file_id", DgPayKit.uploadFile(mchApplyment.getIsvNo(), "F478", info.getStoreOuterImg(), mchApplyment.getIfCode()));
            paramJson.put("file_type", "F478");
            extendedList.add(paramJson);
        }
        if (StringUtils.isNotEmpty(info.getStoreOuterImg())) {
            // 门头照
            JSONObject paramJson = JsonKit.newJson("file_id", DgPayKit.uploadFile(mchApplyment.getIsvNo(), "F22", info.getStoreOuterImg(), mchApplyment.getIfCode()));
            paramJson.put("file_type", "F22");
            extendedList.add(paramJson);
        }
        if (StringUtils.isNotEmpty(info.getStoreInnerImg())) {
            // 内景照
            JSONObject paramJson = JsonKit.newJson("file_id", DgPayKit.uploadFile(mchApplyment.getIsvNo(), "F24", info.getStoreInnerImg(), mchApplyment.getIfCode()));
            paramJson.put("file_type", "F24");
            extendedList.add(paramJson);
        }
        if (StringUtils.isNotEmpty(info.getStoreCashierImg())) {
            // 收银台照
            JSONObject paramJson = JsonKit.newJson("file_id", DgPayKit.uploadFile(mchApplyment.getIsvNo(), "F105", info.getStoreCashierImg(), mchApplyment.getIfCode()));
            paramJson.put("file_type", "F105");
            extendedList.add(paramJson);
        }

        reqParams.put("extended_material_list", extendedList.toJSONString());

        JSONObject agreementJson = new JSONObject();
        // 如果配置了协议信息 走电子协议 未配置则纸质协议
        if (StringUtils.isNotEmpty(isvParams.getAgreementModel())) {
            // 协议类型
            agreementJson.put("agreement_type", "0");
            // 协议模板号
            agreementJson.put("agreement_model", isvParams.getAgreementModel());
            // 协议模板名称
            agreementJson.put("agreement_name", isvParams.getAgreementName());
        } else {
            // 协议类型
            agreementJson.put("agreement_type", "1");
        }
        reqParams.put("agreement_info", agreementJson.toJSONString());

        // 业务开关配置
        JSONObject bizConfJson = new JSONObject();
        // 延迟入账开关
        bizConfJson.put("delay_flag", "Y");
        // 是否开通补贴支付
        bizConfJson.put("combine_pay_flag", "Y");
        // 是否开通余额支付
        bizConfJson.put("balance_pay_flag", "Y");
        // 是否开通结算
        bizConfJson.put("settle_flag", "Y");
//            // 商户开通强制延迟标记
//            bizConfJson.put("forced_delay_flag", "Y");
//            // 是否开通网银
//            bizConfJson.put("online_flag", "Y");
//            // 是否开通快捷
//            bizConfJson.put("quick_flag", "Y");
//            // 是否开通代扣
//            bizConfJson.put("withhold_flag", "Y");
//            // 是否开通微信预授权
//            bizConfJson.put("wechatpay_pre_auth_flag", "Y");
//            // 是否开通支付宝预授权
//            bizConfJson.put("alipay_pre_auth_flag", "Y");

        reqParams.put("biz_conf", bizConfJson);


        // 支付宝配置对象
        List<JSONObject> aliPayFeeList = info.convertAliPayFee(isvParams);
        if (CollUtil.isNotEmpty(aliPayFeeList)) {
            reqParams.put("ali_conf_list", JSON.toJSONString(aliPayFeeList));
        }

        WxpayOauth2Params wxpayOauth2Params = (WxpayOauth2Params) configContextQueryService.queryIsvOauth2Params(mchApplyment.getIsvNo(), CS.IF_CODE.WXPAY);
        DBApplicationConfig dbApplicationConfig = sysConfigService.getDBApplicationConfig();
        // 微信配置对象
        List<JSONObject> wxPayFeeList = info.convertWxPayFee(isvParams, wxpayOauth2Params, dbApplicationConfig);
        if (CollUtil.isNotEmpty(wxPayFeeList)) {
            reqParams.put("wx_conf_list", JSON.toJSONString(wxPayFeeList));
        }

        if (bankAllow) {
            // 银联配置对象
            List<JSONObject> unionList = info.convertUniPayFee();
            if (CollUtil.isNotEmpty(unionList)) {
                reqParams.put("union_conf_list", unionList.toString());
            }
            // 银行卡业务配置
            JSONObject bankPayFee = info.convertBankPayFee();
            if (bankPayFee != null && bankPayFee.size() > 1) {
                reqParams.put("bank_card_conf", bankPayFee.toJSONString());
            }
            // 银联小微参数配置
            if (CollUtil.isNotEmpty(unionList)) {
                reqParams.put("union_micro_info", info.getMicroInfo());
            }
        }

        // 文件集
        reqParams.put("file_info", fileJson);
        // 实名认证信息
        reqParams.put("wx_realname_info", realNameInfoJson);

        return reqParams;
    }

    public void setAccountInfo(MchApplyment mchApplyment, JSONObject reqParams) {
        DgpayApplymentInfo info = JSON.parseObject(mchApplyment.getApplyDetailInfo(), DgpayApplymentInfo.class);
        if (info.getMerchantType() == 1) {
            reqParams.put("name", info.getContactName());
            // 银行卡绑定手机号
            reqParams.put("mobile_no", info.getSettAccountBindPhone());
            // 持卡人证件类型 默认为身份证
            reqParams.put("cert_type", "00");
            // 持卡人证件号码
            reqParams.put("cert_no", info.getSettAccountIdcardNo());
            // 持卡人证件有效期类型
            reqParams.put("cert_validity_type", info.getCertValidityType(info.getSettAccountIdcardEffectEnd()));
            // 持卡人证件有效期 起始
            reqParams.put("cert_begin_date", info.getSettAccountIdcardEffectBegin().replace("-", ""));
            // 持卡人证件有效期 截止
            if (!"长期".equals(info.getSettAccountIdcardEffectEnd())) {
                reqParams.put("cert_end_date", info.getSettAccountIdcardEffectEnd().replace("-", ""));
            }
        } else {
            // 联系人姓名
            reqParams.put("contact_name", info.getIdcardName());
            // 联系人手机号
            reqParams.put("contact_mobile", info.getIdCardPhone());
            // 联系人邮箱
            reqParams.put("contact_email", info.getIdCardEmail());
            // 联系人身份证号
            reqParams.put("contact_cert_no", info.getIdcardNo());

            // 法人姓名
            reqParams.put("legal_name", info.getIdcardName());
            // 法人证件类型 默认身份证
            reqParams.put("legal_cert_type", "00");
            // 法人证件号码
            reqParams.put("legal_cert_no", info.getIdcardNo());
            // 法人证件有效期类型
            reqParams.put("legal_cert_validity_type", info.getCertValidityType(info.getIdcardEffectEnd()));
            // 法人证件有效期开始日期
            reqParams.put("legal_cert_begin_date", info.getIdcardEffectBegin().replace("-", ""));
            if ("0".equals(info.getCertValidityType(info.getIdcardEffectEnd()))) {
                // 法人证件有效期截止日期
                reqParams.put("legal_cert_end_date", info.getIdcardEffectEnd().replace("-", ""));
            }
        }
        // 发送短信标识
        reqParams.put("sms_send_flag", "Y");

        reqParams.remove("area_id");
        reqParams.remove("detail_addr");
        reqParams.remove("prov_id");
        reqParams.remove("district_id");
        reqParams.remove("busi_type");
        reqParams.remove("mcc");
        reqParams.remove("receipt_name");
        reqParams.remove("ent_type");
        reqParams.remove("upper_huifu_id");
        reqParams.put("noMchId", true);
    }

    /**
     * 查询商户详细信息
     **/
    public void queryMchInfo(MchApplyment result, MchAppConfigContext mchAppConfigContext, String huifuId, String ifCode) {
        String logPrefix = "【斗拱】查询商户详细信息";
        try {
            // 请求参数
            JSONObject reqParams = new JSONObject();
            reqParams.put("huifu_id", huifuId);
            // 发送请求
            log.info("{}请求开始", logPrefix);
            JSONObject response = DgPayKit.request(mchAppConfigContext, reqParams, DgPayKit.MCH_INFO_QUERY_URL, ifCode);
            log.info("{}请求结束", logPrefix);

            JSONObject resData = response.getJSONObject("data");
            String code = resData.getString("resp_code");
            if ("00000000".equals(code)) {
                JSONArray infoList = resData.getJSONArray("qry_cash_card_info_list");
                if (CollUtil.isNotEmpty(infoList)) {
                    // 取第一个卡信息
                    JSONObject infoJson = (JSONObject) JSON.toJSON(infoList.get(0));
                    // 绑卡序列号
                    String tokenNo = infoJson.getString("token_no");
                    DgpayIsvsubMchParams mchParams = new DgpayIsvsubMchParams();
                    mchParams.setHuifuId(huifuId);
                    mchParams.setTokenNo(tokenNo);
                    result.setSuccResParameter(JSON.toJSONString(mchParams));
                }


            }
        } catch (Exception e) {
            log.error("{} 异常：", logPrefix, e);
        }
    }
}
