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

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.jeequan.jeepay.core.exception.BizException;
import com.jeequan.jeepay.core.interfaces.paychannel.IIsvmchApplymentService;
import com.jeequan.jeepay.core.model.applyment.ApplymentSignInfo;
import com.jeequan.jeepay.core.model.applyment.YspayApplymentInfo;
import com.jeequan.jeepay.core.model.params.yspay.YspayIsvParams;
import com.jeequan.jeepay.core.utils.SpringBeansUtil;
import com.jeequan.jeepay.db.entity.MchApplyment;
import com.jeequan.jeepay.db.entity.MchSubInfoEntity;
import com.jeequan.jeepay.service.impl.MchSubInfoService;
import com.jeequan.jeepay.service.impl.SysConfigService;
import com.jeequan.jeepay.thirdparty.channel.yspay.utils.ApplymentNotify;
import com.jeequan.jeepay.thirdparty.channel.yspay.utils.YspayKit;
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.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import org.springframework.util.ObjectUtils;

import java.util.*;

/**
 * 银盛 接口进件 3.0
 *
 * @author xiaoyu
 * @date 2022/6/7 10:23
 */
@Service
@Slf4j
public class YspayMchApplymentService implements IIsvmchApplymentService<YspayApplymentInfo> {

    @Autowired
    protected SysConfigService sysConfigService;

    @Autowired
    private YspayApplymentApiService yspayApplymentApiService;

    @Autowired
    private MchSubInfoService mchSubInfoService;

    @Autowired
    private ConfigContextQueryService configContextQueryService;

    @Override
    public com.jeequan.jeepay.core.entity.MchApplyment firstApplyment(com.jeequan.jeepay.core.entity.MchApplyment mchApplyment) {
        String logPrefix = "【银盛商户进件】";
        com.jeequan.jeepay.core.entity.MchApplyment result = new com.jeequan.jeepay.core.entity.MchApplyment();

        // 获取支付参数
        YspayIsvParams isvParams = (YspayIsvParams) configContextQueryService.queryIsvParams(mchApplyment.getIsvNo(), mchApplyment.getIfCode());

        Assert.notNull(mchApplyment.getApplyId(), "商户号[applyId]不能为空");

        try {
            // 获取详细参数
            YspayApplymentInfo info = JSON.parseObject(mchApplyment.getApplyDetailInfo(), YspayApplymentInfo.class);

            Map<String, String> picMap = new HashMap<>();

            JSONObject bizContent = new JSONObject();
            // 请求参数
            bizContentApplyment(picMap, info, bizContent, isvParams, mchApplyment);

            bizContent.put("sysFlowId", mchApplyment.getChannelApplyNo());
            // 发送请求
            String resultStr = YspayKit.applymentRequest("/openapi/t1/smsc/addCustInfoApply", "t1.smsc.addCustInfoApply", isvParams, bizContent);

            JSONObject response = JSON.parseObject(resultStr);
            JSONObject resData = response.getJSONObject("data");
            if (resData == null) {
                result.setState(com.jeequan.jeepay.core.entity.MchApplyment.STATE_REJECT_WAIT_MODIFY);
                result.setApplyErrorInfo(response.getString("code") + "[" + response.getString("msg") + "]");
                log.error("{} 请求失败：code={}, msg={}", logPrefix, response.getString("code"), response.getString("msg"));
                return result;
            }

            String channelOrderNo = resData.getString("sysFlowId");
            if (StringUtils.isNotEmpty(channelOrderNo)) {
                result.setChannelApplyNo(channelOrderNo);
            }

            // 完成第一步信息提交之后，保存流水号和剩余发起进件步骤数
            result.setApplyId(mchApplyment.getApplyId());
            result.setSettlementType(info.getSettAccountCut());
            result.setState(MchApplyment.STATE_AUDITING_WAIT);
            result.setRemainStep(((byte) 2));
            result.setChannelMchNo(channelOrderNo);
            result.setChannelVar1(resData.toJSONString());

            // 后续操作由进件调度程序去处理
            return result;
        } catch (Exception e) {
            result.setState(com.jeequan.jeepay.core.entity.MchApplyment.STATE_REJECT_WAIT_MODIFY);
            result.setApplyErrorInfo("[" + e.getMessage() + "]");
            log.error("{} 进件失败：", logPrefix, e);
        }
        return result;
    }

    @Override
    public com.jeequan.jeepay.core.entity.MchApplyment rejectModify(com.jeequan.jeepay.core.entity.MchApplyment mchApplyment) {
        // 这里直接调用新增的接口
        return firstApplyment(mchApplyment);
    }

    @Override
    public com.jeequan.jeepay.core.entity.MchApplyment replenishInfo(com.jeequan.jeepay.core.entity.MchApplyment mchApplyment) {
        return null;
    }

    @Override
    public com.jeequan.jeepay.core.entity.MchApplyment query(com.jeequan.jeepay.core.entity.MchApplyment mchApplyment) {
        String logPrefix = "【银盛商户进件状态查询】";
        com.jeequan.jeepay.core.entity.MchApplyment result = new com.jeequan.jeepay.core.entity.MchApplyment();
        result.setState(mchApplyment.getState());
        result.setApplyId(mchApplyment.getApplyId());

        if (mchApplyment.getState() == com.jeequan.jeepay.core.entity.MchApplyment.STATE_AUDITING) {
            // 资料确认状态查询
            // 获取支付参数
            YspayIsvParams isvParams = (YspayIsvParams) configContextQueryService.queryIsvParams(mchApplyment);
            JSONObject bizContent = new JSONObject();
            // 请求参数
            bizContent.put("sysFlowId", mchApplyment.getChannelApplyNo());
            // 发送请求
            String resultStr = YspayKit.applymentRequest("/openapi/smsc/queryCustApply", "smsc.queryCustApply", isvParams, bizContent);
            JSONObject response = JSON.parseObject(resultStr);

            // 解密后数据
            JSONObject resData = response.getJSONObject("data");
            if (resData == null) {
                result.setState(com.jeequan.jeepay.core.entity.MchApplyment.STATE_REJECT_WAIT_MODIFY);
                result.setApplyErrorInfo(response.getString("code") + "[" + response.getString("note") + "]");
                log.error("{} 请求失败：code={}, msg={}", logPrefix, response.getString("code"), response.getString("note"));
                return result;
            }

            String applStatus = resData.getString("status");

            mchApplyment.setChannelVar1(resData.toJSONString());

            // 审核成功
            if ("00".equals(applStatus)) {
                return signApply(mchApplyment);
            }
            // 审核拒绝
            else if ("90".equals(applStatus)) {
                result.setState(com.jeequan.jeepay.core.entity.MchApplyment.STATE_REJECT_WAIT_MODIFY);
                result.setApplyErrorInfo("[" + resData.getString("note") + "]");
                return result;

            } else {
                result.setApplyErrorInfo("[" + resData.getString("note") + "]");
                return result;
            }
        }

        if (mchApplyment.getState() == com.jeequan.jeepay.core.entity.MchApplyment.STATE_WAIT_SIGN) {
            return yspayApplymentApiService.signQuery(mchApplyment);
        }

        return mchApplyment;
    }

    @Override
    public com.jeequan.jeepay.core.entity.MchApplyment signApply(com.jeequan.jeepay.core.entity.MchApplyment mchApplyment) {
        String applyDetailInfo = mchApplyment.getApplyDetailInfo();

        return yspayApplymentApiService.signApply(JSON.parseObject(applyDetailInfo), mchApplyment);
    }

    /**
     * 获取签约地址
     */
    @Override
    public ApplymentSignInfo signInfo(com.jeequan.jeepay.core.entity.MchApplyment mchApplyment) {

        ApplymentSignInfo result = new ApplymentSignInfo();

        try {
            // 获取到 渠道商配置信息
            YspayIsvParams isvParams = (YspayIsvParams) configContextQueryService.queryIsvParams(mchApplyment);

            // 1、获取当前进件签约信息，未发起签约时为空
            String channelVar2 = mchApplyment.getChannelVar2();

            // 2、未发起签约
            if (StringUtils.isBlank(channelVar2)) {
                result.setState("01");
                return result;
            }

            // 3、查询数据库签约状态
            ApplymentSignInfo dbSignInfo = JSON.parseObject(channelVar2, ApplymentSignInfo.class);

            // 4、调渠道接口，查询签约状态
            JSONObject queryJSON = new JSONObject();
            JSONObject channelSignJSON = JSON.parseObject(dbSignInfo.getOriginData());
            queryJSON.put("authId", channelSignJSON.getString("authId"));

            // 发送请求
            String resultStr = YspayKit.applymentRequest("/openapi/smsc/saas/constract/queryAuthInfo", "smsc.saas.constract.queryAuthInfo", isvParams, queryJSON);
            JSONObject response = JSON.parseObject(resultStr);

            // 解密后数据
            JSONObject resData = response.getJSONObject("data");
            if (resData == null) {
                result.setState("04");
                result.setErrInfo(response.getString("code") + "[" + response.getString("msg") + "]");
                return result;
            }

            result.setState(resData.getString("status"));
            result.setErrInfo(resData.getString("note"));

            if ("00".equals(resData.getString("status"))) {
                result.setState("签约成功"); // 前端直接展示文字
            }
            return result;

        } catch (Exception e) {
            result.setSignUrl("签约信息解析异常" + e.getMessage());
            return result;
        }
    }

    /*@Override
    public ApplymentSignInfo signInfo(MchApplyment mchApplyment) {
        ApplymentSignInfo result = new ApplymentSignInfo();
        try {

            // 获取到 渠道商配置信息
            YspayIsvParams isvParams = (YspayIsvParams) configContextQueryService.queryIsvParams(mchApplyment.getIsvNo(), CS.IF_CODE.YSPAY);

            // 获取签约地址
            String channelVar2 = mchApplyment.getChannelVar2();
            if (StringUtils.isEmpty(channelVar2)) {
                result.setErrInfo("签约信息为空");
            }
            JSONObject signJson = JSON.parseObject(channelVar2);
            // 签约地址
            String signUrl = signJson.getString("signUrl");
            // 签约流水号
            String sysSignFlowId = signJson.getString("sysSignFlowId");
            if (StringUtils.isEmpty(signUrl) || StringUtils.isEmpty(sysSignFlowId)) {
                result.setErrInfo("签约地址或签约流水号不能为空");
            }
            result.setSignUrl(signUrl);
            // 查询签约状态
            JSONObject bizContent = new JSONObject();
            // 请求参数
            bizContent.put("sysSignFlowId", sysSignFlowId);
            // 发送请求
            String resultStr = YspayKit.applymentRequest("/saas/orgSign/querySignSts", "querySignSts", isvParams, bizContent);
            JSONObject response = JSON.parseObject(resultStr);
            JSONObject resData = response.getJSONObject("data");
            // 原参数
            result.setOriginData(resData.toJSONString());
            // 响应状态
            String code = resData.getString("code");
            if ("00".equals(code)) {
                String signState = resData.getString("signSts");
                if (StringUtils.isNotEmpty(signState)) {
                    if ("0".equals(signState)) {
                        result.setState("申请中");
                    } else if ("1".equals(signState)) {
                        result.setState("待签署");
                    } else if ("2".equals(signState)) {
                        result.setState("已签约");
                    } else if ("3".equals(signState)) {
                        result.setState("已作废");
                    } else if ("4".equals(signState)) {
                        result.setState("已过期");
                    } else if ("7".equals(signState)) {
                        result.setState("待签署");
                    } else if ("8".equals(signState)) {
                        result.setState("合同已生成");
                    }
                }
            } else {
                result.setState("|");
                result.setErrInfo(resData.getString("note"));
                log.error("请求失败：code={}, msg={}", code, resData.getString("note"));
                return result;
            }

        } catch (Exception e) {
            result.setSignUrl("签约信息解析异常" + e.getMessage());
        }
        return result;
    }*/
    public void bizContentApplyment(Map<String, String> picMap, YspayApplymentInfo info, JSONObject bizContent, YspayIsvParams isvParams, com.jeequan.jeepay.core.entity.MchApplyment mchApplyment) {
        // 费率校验
        YspayApplymentInfo.convertFeeJSON(info.getPaywayFeeList(), isvParams.getSettType());

        // 基本信息
        bizContent.put("custInfo", setCustInfo(picMap, info, isvParams, mchApplyment));
        // 法人信息
        bizContent.put("crpInfo", setCrpInfo(picMap, info));
        // 结算信息
        bizContent.put("stlAccInfo", setStlAccInfo(picMap, info));
        // 营业信息
        bizContent.put("busInfo", setBusInfo(picMap, info));
    }

    // 获取支付网关，用于进件回调
    protected String getApplySiteUrl() {
        return sysConfigService.getDBApplicationConfig().getPaySiteUrl();
    }

    /**
     * 基本信息
     **/
    private JSONObject setCustInfo(Map<String, String> picMap, YspayApplymentInfo info, YspayIsvParams isvParams, com.jeequan.jeepay.core.entity.MchApplyment mchApplyment) {
        JSONObject custInfoJson = new JSONObject();
        // 服务商编号
        custInfoJson.put("agtMercId", isvParams.getAgtMercId());
        // 商户名称

        custInfoJson.put("mercName", info.getMchFullName());
        if (ObjectUtils.isEmpty(info.getMchFullName())) {
            throw new BizException("商户全称不能为空");
        }
        // 商户简称
        if (StringUtils.isNotEmpty(info.getMchShortName())) {
            custInfoJson.put("mercShortName", info.getMchShortName());
        }
        // 商户类型,2 小微 3个体 4企业 5 社会组织 6 事业单位 7 政府机关
        custInfoJson.put("mercType", info.getYsMerchantType());
        // MCC码
        custInfoJson.put("mccCd", info.getMccCode());
        // 联系人电话
        custInfoJson.put("contactPhone", info.getContactPhone());
        // 联系人邮箱
        custInfoJson.put("contactMail", "18062761507@163.com");
        // 联系人姓名
        custInfoJson.put("contactMan", info.getContactName());
        // 客户经理姓名
        custInfoJson.put("cusMgrNm", isvParams.getCusMgrNm());
        // 是否开通营销,Y开通N不开通,默认不开通
        custInfoJson.put("isOpenMarket", "N");
        // 异步通知地址
        custInfoJson.put("notifyUrl", getApplySiteUrl() + "/api/mchApplyment/notify/" + mchApplyment.getIfCode() + "/" + mchApplyment.getApplyId());

        // 门头照
        picMap.put("A006", info.getStoreOuterImg());
        // 内景照
        picMap.put("A007", info.getStoreInnerImg());
        // 收银台照
        picMap.put("A008", info.getStoreCashierImg());
        return custInfoJson;
    }

    /**
     * 法人信息
     **/
    private JSONObject setCrpInfo(Map<String, String> picMap, YspayApplymentInfo info) {
        JSONObject crpInfoJson = new JSONObject();
        // 法人证件类型,00：身份证   06：国外护照 07：港澳通行证 08：台胞通行证
        crpInfoJson.put("crpCertType", "00");
        // 法人姓名
        crpInfoJson.put("crpNm", info.getIdcardName());
        // 法人身份证号
        crpInfoJson.put("crpCertNo", info.getIdcardNo());
        // 法人身份证开始日期
        crpInfoJson.put("certBgn", info.convertDate(info.getIdcardEffectBegin()));
        // 法人身份证结束日期
        crpInfoJson.put("certExpire", info.convertDate(info.getIdcardEffectEnd()));
        // 法人电话
        crpInfoJson.put("crpPhone", info.getLegalPersonPhone());
        // 法人地址
        crpInfoJson.put("crpAddr", info.getIdcardAddress());
        // 法人身份证正面
        picMap.put("A002", info.getIdcard1Img());
        // 法人身份证背面
        picMap.put("A003", info.getIdcard2Img());

        // 被授权人信息，非法人结算同开户人信息
        if ("Y".equals(info.getIsUncrpSett())) {
            JSONObject authInfo = new JSONObject();
            // 被授权人姓名
            authInfo.put("name", info.getSettAccountName());
            // 被授权人证件类型
            authInfo.put("certType", "00");
            // 被授权人证件号
            authInfo.put("certNo", info.getSettAccountIdcardNo());
            // 被授权人证件起始日期,格式：YYYYMMDD
            authInfo.put("certBgn", info.convertDate(info.getSettAccountIdcardEffectBegin()));
            // 被授权人证件有效期,格式：YYYYMMDD
            authInfo.put("certExpire", info.convertDate(info.getSettAccountIdcardEffectEnd()));
            // 被授权人证件地址
            authInfo.put("addr", info.getSettleAuthAddress());
            // 被授权人身份证正面
            picMap.put("A013", info.getSettAccountIdcard1Img());
            // 被授权人身份证背面
            picMap.put("A014", info.getSettAccountIdcard1Img());
            // 非法人结算授权函
            picMap.put("B005", info.getSettleAuthLetterPhoto());


            crpInfoJson.put("authInfo", authInfo);
        }

        return crpInfoJson;
    }

    /**
     * 结算信息
     **/
    private JSONObject setStlAccInfo(Map<String, String> picMap, YspayApplymentInfo info) {
        JSONObject stlAccJson = new JSONObject();
        // 是否平台内账户,Y是 N否，默认否
        stlAccJson.put("isSettInPlatAcc", "N");
        // 是否非法人结算,Y是 N否，默认否
        stlAccJson.put("isUncrpSett", info.getIsUncrpSett());
        // 结算户名，默认法人姓名
        stlAccJson.put("stlAccNm", StringUtils.defaultString(info.getDiySettAccountName(), info.getIdcardName()));
        // 开户证件号,默认法人证件号
        stlAccJson.put("openCertNo", info.getIdcardNo());
        // 结算账号
        stlAccJson.put("stlAccNo", info.getSettAccountNo());
        // 开户支行联行号
        stlAccJson.put("bankSubCode", info.getBankSubCode());
        // 结算账户类型,11 对私 21 对公 23 对公存折 24 单位结算卡
        stlAccJson.put("stlAccType", info.getYsSettAccountType(info.getSettAccountType()));
        if (com.jeequan.jeepay.core.entity.MchApplyment.SETT_ACCOUNT_TYPE_CORPORATE.equals(info.getSettAccountType())) {
            picMap.put("A011", info.getCompanyAccountLicenseImg());
        } else {
            picMap.put("A004", info.getSettAccountLicenseImg());
            picMap.put("A005", info.getSettAccountLicenseImg());
        }

        // 非法人结算
        if ("Y".equals(info.getIsUncrpSett())) {
            // 结算户名,默认法人姓名, 非法人结算必填
            stlAccJson.put("stlAccNm", info.getSettAccountName());
            // 银行预留手机号
            stlAccJson.put("bankMobile", info.getBankMobile());
            // 开户证件号
            stlAccJson.put("openCertNo", info.getSettAccountIdcardNo());
            if (info.getSettAccountBankBranchAreaCode().size() > 1) {
                // 开户行省
                stlAccJson.put("bankProince", info.getSettAccountBankBranchAreaCode().get(0) + "");
                // 开户行市
                stlAccJson.put("bankCity", info.getSettAccountBankBranchAreaCode().get(1) + "");
            }
        }

        // 备用结算信息
        if (StringUtils.isNotEmpty(info.getIsOtherAccountInfo()) && "1".equals(info.getIsOtherAccountInfo())) {
            // 结算账户类型,11 对私 21 对公 23 对公存折 24 单位结算卡
            stlAccJson.put("standByStlAccType", info.getYsSettAccountType(info.getStandByStlAccType()));
            // 银行预留手机号
            stlAccJson.put("standByStlAccNo", info.getStandByStlAccNo());
            // 备用账户户名
            stlAccJson.put("standByStlAccNm", info.getStandByStlAccNm());
            // 备用账户开户行支行编号
            stlAccJson.put("standByBankSubCode", info.getStandByBankSubCode());

            if (info.getStandByAccountBankBranchAreaCode().size() > 1) {
                // 备用账户开户行省
                stlAccJson.put("standByBankProvince", info.getStandByAccountBankBranchAreaCode().get(0) + "");
                // 备用账户开户行市
                stlAccJson.put("standByBankCity", info.getStandByAccountBankBranchAreaCode().get(1) + "");
            }
        }
        return stlAccJson;
    }

    /**
     * 营业信息
     **/
    private JSONObject setBusInfo(Map<String, String> picMap, YspayApplymentInfo info) {
        JSONObject busInfoJson = new JSONObject();
        /** 营业资质信息 【小微不传】**/
        if (!info.isPersonal()) {
            // 营业执照名称
            busInfoJson.put("busNm", info.getMchFullName());
            // 营业执照号码
            busInfoJson.put("busNo", info.getLicenseNo());
            // 营业执照开始日期
            busInfoJson.put("busCertBgn", info.convertDate(info.getLicenseEffectBegin()));
            // 营业执照结束日期
            busInfoJson.put("busCertExpire", info.convertDate(info.getLicenseEffectEnd()));
            // 营业执照证件类型 个体及企业商户：仅支持 19：社会统一信用代码
            busInfoJson.put("busCertType", "19");
        }
        // 营业详细地址,需包含省市区
        busInfoJson.put("busAddr", info.getAddress());

        Assert.notNull(info.getAreaCode(), "营业省市区信息不能为空");
        // 营业归属省代码
        busInfoJson.put("busProviceCode", info.getAreaCode().get(0) + "");
        // 营业归属市代码
        busInfoJson.put("busCityCode", info.getAreaCode().get(1) + "");
        // 营业归属区(县)代码
        if (info.getAreaCode().get(2) != null) {
            busInfoJson.put("busAreaCode", info.getAreaCode().get(2) + "");
        }

        picMap.put("A001", info.getLicenseImg());

        return busInfoJson;
    }

    @Override
    public void subMchColl(com.jeequan.jeepay.core.entity.MchApplyment mchApplyment) {
        if (mchApplyment.getState() != com.jeequan.jeepay.core.entity.MchApplyment.STATE_SUCCESS
                && mchApplyment.getState() != com.jeequan.jeepay.core.entity.MchApplyment.STATE_SUCCESS_NEED_SECOND_VERIFY) {
            return;
        }

        // 获取到 渠道商配置信息
        YspayIsvParams isvParams = (YspayIsvParams) configContextQueryService.queryIsvParams(mchApplyment);

        List<String> channelIdList = Arrays.asList("CUPS_WECHAT", "CUPS_ALIPAY", "NUCC_WECHAT", "NUCC_ALIPAY");

        for (String channelId : channelIdList) {
            JSONObject bizContent = new JSONObject();
            bizContent.put("mercId", mchApplyment.getChannelMchNo());
            bizContent.put("channelId", channelId);
            String bizResult = YspayKit.applymentRequest("/openapi/report/scan/union/repAndAppIdQry", "report.scan.union.repAndAppIdQry", isvParams, bizContent);
            JSONObject bizJSON = JSON.parseObject(bizResult).getJSONObject("data");

            String apprSts = bizJSON.getString("apprSts");

            String thirdMercId = bizJSON.getString("thirdMercId");

            MchSubInfoEntity subInfo = new MchSubInfoEntity();
            subInfo.setSubMchId(thirdMercId);
            subInfo.setMchApplyId(mchApplyment.getApplyId());
            subInfo.setSubMchWay(channelId);
            subInfo.setStatus(apprSts);

            if (channelId.endsWith("WECHAT")) {
                subInfo.setSubMchType("WX");
            } else if (channelId.endsWith("ALIPAY")) {
                subInfo.setSubMchType("ZFB");
            }

            if (channelId.startsWith("CUPS")) {
                subInfo.setMainUse(1);
            } else {
                subInfo.setMainUse(0);
            }

            try {
                mchSubInfoService.save(subInfo);
            } catch (DuplicateKeyException ignored) {
                // 主键冲突直接忽略
            }
        }
    }

    @Override
    public void subMchColl(com.jeequan.jeepay.core.entity.MchApplyment mchApplyment, Object callback) {
        ApplymentNotify.Report applymentNotify = (ApplymentNotify.Report) callback;
        String channelMchNo = applymentNotify.getMercId();

        List<MchSubInfoEntity> resultList = new ArrayList<>();
        for (ApplymentNotify.ThirdMerc thirdMerc : applymentNotify.getThridMercList()) {

            String apprSts = thirdMerc.getApprSts();
            String thridMercId = thirdMerc.getThridMercId();
            String remark = thirdMerc.getRemark();
            String reportChannel = thirdMerc.getReportChannel();

            if (reportChannel.contains("POS")) {
                continue;
            }

            MchSubInfoEntity subInfo = new MchSubInfoEntity();
            subInfo.setChannelMchNo(channelMchNo);
            subInfo.setSubMchId(Optional.ofNullable(thridMercId).orElse("报备失败"));
            subInfo.setStatus(apprSts);
            subInfo.setRemark(remark);
            subInfo.setMainUse(0);
            subInfo.setMchApplyId(mchApplyment.getApplyId());

            subInfo.setSubMchWay(reportChannel);
            if (reportChannel.contains("WECHAT")) {
                subInfo.setSubMchType("WX");
            }

            if (reportChannel.contains("ALIPAY")) {
                subInfo.setSubMchType("ZFB");
            }

            if (reportChannel.contains("CUPS")) {
                subInfo.setMainUse(1);
            } else {
                subInfo.setMainUse(0);
            }

            resultList.add(subInfo);
        }

        if (!resultList.isEmpty()) {
            mchSubInfoService.saveBatch(resultList);
        }
    }

    @Override
    public void subMchCert(com.jeequan.jeepay.core.entity.MchApplyment mchApplyment, com.jeequan.jeepay.core.entity.MchSubInfo mchSubInfo) {
        if ("WX".equals(mchSubInfo.getSubMchType())) {
            wxMchCert(mchApplyment, mchSubInfo);
        }

        if ("ZFB".equals(mchSubInfo.getSubMchType())) {
            zfbMchCert(mchApplyment, mchSubInfo);
        }
    }

    private void zfbMchCert(com.jeequan.jeepay.core.entity.MchApplyment mchApplyment, com.jeequan.jeepay.core.entity.MchSubInfo mchSubInfo) {
        JSONObject bizContent = new JSONObject();
        LambdaUpdateWrapper<MchSubInfoEntity> uWrapper = Wrappers.lambdaUpdate();
        bizContent.put("mercId", mchApplyment.getChannelMchNo());

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

        String bizResult = YspayKit.applymentRequest("/openapi/pregate/alipay/getAuthState", "trade.scan.wechat.auth.getAuthState", isvParams, bizContent);
        JSONObject bizJson = JSON.parseObject(bizResult);

        String state = bizJson.getString("state");

        if (!"00".equals(state)) {
            throw new BizException(state);
        }

        String authState = bizJson.getString("authState");
        if ("1".equals(authState)) {
            uWrapper.set(MchSubInfoEntity::getAuthStatus, com.jeequan.jeepay.core.entity.MchSubInfo.AUTH_STATUS_AUTHORIZED);
        }

        if ("0".equals(authState)) {
            uWrapper.set(MchSubInfoEntity::getAuthStatus, com.jeequan.jeepay.core.entity.MchSubInfo.AUTH_STATUS_UNAUTHORIZED);
        }

        uWrapper.eq(MchSubInfoEntity::getMainUse, 1);
        uWrapper.eq(MchSubInfoEntity::getMchApplyId, mchSubInfo.getMchApplyId());
        uWrapper.eq(MchSubInfoEntity::getSubMchType, mchSubInfo.getSubMchType());
        uWrapper.eq(!ObjectUtils.isEmpty(mchSubInfo.getSubMchWay()), MchSubInfoEntity::getSubMchWay, mchSubInfo.getSubMchWay());

        mchSubInfoService.update(null, uWrapper);
    }

    private void wxMchCert(com.jeequan.jeepay.core.entity.MchApplyment mchApplyment, com.jeequan.jeepay.core.entity.MchSubInfo mchSubInfo) {
        JSONObject bizContent = new JSONObject();
        bizContent.put("mercId", mchApplyment.getChannelMchNo());
        ConfigContextQueryService configContextQueryService = SpringBeansUtil.getBean(ConfigContextQueryService.class);
        YspayIsvParams isvParams = (YspayIsvParams) configContextQueryService.queryIsvParams(mchApplyment);

        String bizResult = YspayKit.applymentRequest("/openapi/trade/scan/wechat/auth/getAuthState", "trade.scan.wechat.auth.getAuthState", isvParams, bizContent);
        JSONObject bizJson = JSON.parseObject(bizResult);

        String state = bizJson.getString("state");

        LambdaUpdateWrapper<MchSubInfoEntity> uWrapper = Wrappers.lambdaUpdate();

        if (!"00".equals(state)) {
            throw new BizException(state);
        }

        String thirdMercIdX = bizJson.getString("thirdMercIdX");

        if (mchSubInfo.getSubMchId().equals(thirdMercIdX)) {
            String authStateX = bizJson.getString("authStateX");
            if ("AUTHORIZE_STATE_AUTHORIZED".equals(authStateX)) {
                uWrapper.set(MchSubInfoEntity::getAuthStatus, com.jeequan.jeepay.core.entity.MchSubInfo.AUTH_STATUS_AUTHORIZED);
            }

            if ("AUTHORIZE_STATE_UNAUTHORIZED".equals(authStateX)) {
                uWrapper.set(MchSubInfoEntity::getAuthStatus, com.jeequan.jeepay.core.entity.MchSubInfo.AUTH_STATUS_UNAUTHORIZED);
            }
        }

        String thirdMercIdY = bizJson.getString("thirdMercIdY");
        if (mchSubInfo.getSubMchId().equals(thirdMercIdY)) {
            String authStateY = bizJson.getString("authStateY");
            if ("AUTHORIZE_STATE_AUTHORIZED".equals(authStateY)) {
                uWrapper.set(MchSubInfoEntity::getAuthStatus, com.jeequan.jeepay.core.entity.MchSubInfo.AUTH_STATUS_AUTHORIZED);
            }

            if ("AUTHORIZE_STATE_UNAUTHORIZED".equals(authStateY)) {
                uWrapper.set(MchSubInfoEntity::getAuthStatus, com.jeequan.jeepay.core.entity.MchSubInfo.AUTH_STATUS_UNAUTHORIZED);
            }
        }

        uWrapper.eq(MchSubInfoEntity::getMainUse, 1);
        uWrapper.eq(MchSubInfoEntity::getMchApplyId, mchSubInfo.getMchApplyId());
        uWrapper.eq(MchSubInfoEntity::getSubMchType, mchSubInfo.getSubMchType());
        uWrapper.eq(!ObjectUtils.isEmpty(mchSubInfo.getSubMchWay()), MchSubInfoEntity::getSubMchWay, mchSubInfo.getSubMchWay());

        mchSubInfoService.update(null, uWrapper);
    }
}
