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

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.stream.StreamUtil;
import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.core.util.RandomUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.jeequan.jeepay.converter.MchInfoConverter;
import com.jeequan.jeepay.core.entity.MchApplyment;
import com.jeequan.jeepay.core.entity.MchSubInfo;
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.LklspayApplymentInfo;
import com.jeequan.jeepay.core.model.applyment.PaywayFee;
import com.jeequan.jeepay.core.model.params.lklspay.LklspayIsvParams;
import com.jeequan.jeepay.db.entity.BankBranchLkl;
import com.jeequan.jeepay.db.entity.MchSubInfoEntity;
import com.jeequan.jeepay.service.impl.LocationCacheService;
import com.jeequan.jeepay.service.impl.MchSubInfoService;
import com.jeequan.jeepay.service.mapper.BankBranchLklMapper;
import com.jeequan.jeepay.thirdparty.channel.lklpay.utils.LklpayConst;
import com.jeequan.jeepay.thirdparty.channel.lklspay.model.LklMercInfoConn;
import com.jeequan.jeepay.thirdparty.channel.lklspay.model.LklTkReqMethod;
import com.jeequan.jeepay.thirdparty.service.ConfigContextQueryService;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import lombok.extern.slf4j.Slf4j;
import net.coobird.thumbnailator.Thumbnails;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
public class LklspayMchApplymentService implements IIsvmchApplymentService<LklspayApplymentInfo> {

    @Autowired
    private LocationCacheService locationCacheService;

    @Autowired
    private ConfigContextQueryService configContextQueryService;

    @Autowired
    private BankBranchLklMapper bankBranchLklMapper;

    @Autowired
    private Configuration configuration;

    @Autowired
    private MchSubInfoService mchSubInfoService;

    @Autowired
    private MchInfoConverter mchInfoConverter;

    @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);

        LklspayApplymentInfo applymentInfo = JSON.parseObject(mchApplyment.getApplyDetailInfo(), LklspayApplymentInfo.class);
        applymentInfo.saveCheck();

        Assert.notNull(applymentInfo.getAreaName(), "经营地区名称[areaName]不能为空");
        Assert.isFalse(applymentInfo.getAreaName().isEmpty(), "经营地区名称[areaName]不能为空");

        result.setSettlementType(applymentInfo.getSettleType());

        return result;
    }

    private static LklMercInfoConn.Attachment getAttachment(LklspayIsvParams isvParams, File file, String imgType) {
        JSONObject imgUploadResult = LklspayKit.uploadRequest(isvParams, file, imgType);
        LklMercInfoConn.Attachment attachmentItem = new LklMercInfoConn.Attachment();
        attachmentItem.setId(imgUploadResult.getString("url"));
        attachmentItem.setType(imgType);
        return attachmentItem;
    }

    private static LklMercInfoConn.Attachment getAttachment(LklspayIsvParams isvParams, String fileUrl, String imgType) {
        JSONObject imgUploadResult = LklspayKit.uploadRequest(isvParams, fileUrl, imgType);
        LklMercInfoConn.Attachment attachmentItem = new LklMercInfoConn.Attachment();
        attachmentItem.setId(imgUploadResult.getString("url"));
        attachmentItem.setType(imgType);
        return attachmentItem;
    }

    private File writeHtml(Template template, Map<String, Object> data) throws IOException, TemplateException {
        String fileName = UUID.randomUUID().toString();
        File htmlFile = new File(FileUtil.getTmpDir(), fileName + ".html");
        FileWriter sw = new FileWriter(htmlFile);
        log.info("生成协议html, 地址:{}, 参数:{} ", htmlFile.getAbsolutePath(), data);
        template.process(data, sw);

        return htmlFile;
    }

    private static File createAgreementPicture(File htmlFile) throws IOException {
        File outputFile = new File(FileUtil.getTmpDir(), htmlFile.getName() + ".jpg");
        log.info("生成图片开始, HTML地址 {}, 图片地址:{}", htmlFile.getAbsolutePath(), outputFile.getAbsolutePath());
        String commandProcess = "wkhtmltoimage  --width  400  --quality  94  " + htmlFile.getPath() + "  " + outputFile.getPath();
        log.info("协议执行Process command:{}", commandProcess);
        long startTime = System.currentTimeMillis();   //获取开始时间
        Process process = Runtime.getRuntime().exec(commandProcess);
        try {
            int exitVal = process.waitFor();
            log.info("协议html转换png结果:{}", exitVal);
        } catch (InterruptedException e) {
            log.info("协议html转换png错误", e);
            Thread.currentThread().interrupt();
            throw new IOException(e);
        }
        long endTime = System.currentTimeMillis(); //获取结束时间
        log.info("程序运行时间： " + (endTime - startTime) + "ms");
        log.info("生成图片结束,地址: {}", outputFile.getPath());
        Thumbnails.of(outputFile).scale(1).outputQuality(0.9).toFile(outputFile);
        return outputFile;
    }

    private String getEndDate(String endDate) {
        if ("长期".equals(endDate)) {
            return "2099-12-31";
        }

        return endDate;
    }

    private LklMercInfoConn getLklData(LklspayApplymentInfo applymentInfo, LklspayIsvParams isvParams) {
        LklMercInfoConn mercInfo = new LklMercInfoConn();
        mercInfo.setUserNo(Long.parseLong(isvParams.getUserNo()));
        mercInfo.setEmail("18062761507@163.com");
        mercInfo.setBusiCode(LklpayConst.BIZ_CODE_SCAN);

        if (com.jeequan.jeepay.core.entity.MchApplyment.MERCHANT_TYPE_PERSONAL == applymentInfo.getMerchantType()) {
            mercInfo.setMerType("TP_PERSONAL");
            mercInfo.setMerRegName(applymentInfo.getMchFullName());
        } else {
            mercInfo.setMerType("TP_MERCHANT");
            String mchFullName = applymentInfo.getMchFullName();
            if (mchFullName.length() > 20) {
                // 字数过长，商户商户全称
                mercInfo.setMerRegName(applymentInfo.getMerRegName());
            } else {
                mercInfo.setMerRegName(mchFullName);
            }
        }

        mercInfo.setMerName(applymentInfo.getMchShortName());
        mercInfo.setMerAddr(applymentInfo.getAddress());

        mercInfo.setProvinceCode(applymentInfo.getMchAreaCode().getString(0));
        mercInfo.setCityCode(applymentInfo.getMchAreaCode().getString(1));
        mercInfo.setCountyCode(applymentInfo.getMchAreaCode().getString(2));

        if (1 != applymentInfo.getMerchantType()) {
            // 非小微商户提交营业执照信息
            mercInfo.setLicenseName(applymentInfo.getMchFullName());
            mercInfo.setLicenseNo(applymentInfo.getLicenseNo());
            mercInfo.setLicenseDtStart(applymentInfo.getLicenseEffectBegin());
            mercInfo.setLicenseDtEnd(getEndDate(applymentInfo.getLicenseEffectEnd()));
        }
        // 接口的经纬度字段是反的
        mercInfo.setLatitude(applymentInfo.getLatitude());
        mercInfo.setLongtude(applymentInfo.getLongtude());
        mercInfo.setSource("APP");

        Assert.notNull(applymentInfo.getMccCode(), "缺少mcc编码信息");
        String[] mccInfo = applymentInfo.getMccCode().split("_");
        if (mccInfo.length != 2) {
            throw new BizException("mcc数据异常");
        }
        mercInfo.setBusinessContent(mccInfo[0]);
        mercInfo.setLarName(applymentInfo.getIdcardName());
        mercInfo.setLarIdType("01");
        mercInfo.setLarIdCard(applymentInfo.getIdcardNo());
        mercInfo.setLarIdCardStart(applymentInfo.getIdcardEffectBegin());
        mercInfo.setLarIdCardEnd(getEndDate(applymentInfo.getIdcardEffectEnd()));
        mercInfo.setContactMobile(applymentInfo.getContactPhone());
        mercInfo.setContactName(applymentInfo.getContactName());

        BankBranchLkl bankCodeLkl = bankBranchLklMapper.selectByContactLine(applymentInfo.getOpenningBankCode());
        Assert.notNull(bankCodeLkl, "未获取到支行信息，请重新选择支行信息");

        mercInfo.setOpenningBankCode(bankCodeLkl.getContactLine());
        mercInfo.setOpenningBankName(bankCodeLkl.getBranchName());
        mercInfo.setClearingBankCode(bankCodeLkl.getClearNo());

        Assert.notNull(applymentInfo.getSettAccountBankBranchAreaCode(), "缺少支行地区编码信息");
        Assert.notNull(applymentInfo.getSettAccountBankBranchAreaName(), "缺少支行地区信息");
        mercInfo.setSettleProvinceCode(applymentInfo.getSettAccountBankBranchAreaCode().getString(0));
        mercInfo.setSettleProvinceName(applymentInfo.getSettAccountBankBranchAreaName().getString(0));
        mercInfo.setSettleCityCode(applymentInfo.getSettAccountBankBranchAreaCode().getString(1));
        mercInfo.setSettleCityName(applymentInfo.getSettAccountBankBranchAreaName().getString(1));
        mercInfo.setAccountNo(applymentInfo.getSettAccountNo());
        mercInfo.setAccountName(applymentInfo.getSettAccountName());
        mercInfo.setAccountType(applymentInfo.getSettAccType());
        mercInfo.setAccountIdType("01");
        mercInfo.setAccountIdCard(applymentInfo.getSettAccountIdcardNo());
        mercInfo.setAccountIdDtStart(applymentInfo.getSettAccountIdcardEffectBegin());
        mercInfo.setAccountIdDtEnd(getEndDate(applymentInfo.getSettAccountIdcardEffectEnd()));

        mercInfo.setBizContent(getFeeInfo(applymentInfo, isvParams));
        mercInfo.setSettleType(applymentInfo.getSettleType());
        mercInfo.setSettlementType("AUTOMATIC");

        return mercInfo;
    }

    public static String convertRate(BigDecimal rate) {
        return rate == null ? null : String.valueOf(rate.multiply(new BigDecimal(100)).setScale(2, RoundingMode.HALF_UP));
    }

    private LklMercInfoConn.BizContent getFeeInfo(LklspayApplymentInfo applymentInfo, LklspayIsvParams isvParams) {
        Map<String, LklMercInfoConn.Fee> map = new HashMap<>();

        List<PaywayFee> paywayFeeList = applymentInfo.getPaywayFeeList();

        for (PaywayFee paywayFee : paywayFeeList) {
            boolean isYsfLevelFee = (paywayFee.getWayCode().startsWith("YSF_") || paywayFee.getWayCode().startsWith("UP_"))
                    && PaywayFee.FEE_TYPE_LEVEL.equals(paywayFee.getFeeType())
                    && CollUtil.isNotEmpty(paywayFee.getLevelList());
            if (isYsfLevelFee) {
                // 借记卡费率
                PaywayFee paywayFeeDebitCard = paywayFee.getLevelList().get(0);
                double topFee1 = (double) paywayFeeDebitCard.getMaxFee() / 100L;
                map.put("YSF_DISCOUNT_DEBIT_FEE", new LklMercInfoConn.Fee("YSF_DISCOUNT_DEBIT_FEE", Double.parseDouble(convertRate(paywayFeeDebitCard.getFeeRate())), topFee1));

                PaywayFee paywayFee2DebitCard = paywayFee.getLevelList().get(1);
                double topFee2 = (double) paywayFee2DebitCard.getMaxFee() / 100L;
                map.put("DEBIT_CARD", new LklMercInfoConn.Fee("DEBIT_CARD", 0.5d, topFee2));
//                map.put("DEBIT_CARD", new LklMercInfoConn.Fee("DEBIT_CARD", Double.parseDouble(convertRate(paywayFeeDebitCard.getFeeRate())), topFee2));
            }

            PaywayFee creditCardPaywayFee = paywayFee.getCreditCardPaywayFee();
            if (creditCardPaywayFee != null && CollUtil.isNotEmpty(creditCardPaywayFee.getLevelList()) && (CollUtil.isNotEmpty(creditCardPaywayFee.getLevelList()))) {
                PaywayFee paywayFeeCrebitCard = creditCardPaywayFee.getLevelList().get(0);
                map.put("YSF_DISCOUNT_CREDIT_FEE", new LklMercInfoConn.Fee("YSF_DISCOUNT_CREDIT_FEE", Double.parseDouble(convertRate(paywayFeeCrebitCard.getFeeRate())), null));

                PaywayFee paywayFee2CrebitCard = creditCardPaywayFee.getLevelList().get(1);
                map.put("CREDIT_CARD", new LklMercInfoConn.Fee("CREDIT_CARD", Double.parseDouble(convertRate(paywayFee2CrebitCard.getFeeRate())), null));

            }

            if (paywayFee.getWayCode().startsWith("WX_")) {
                map.put("WECHAT", new LklMercInfoConn.Fee("WECHAT", Double.parseDouble(convertRate(paywayFee.getFeeRate())), null));
            }


            if (paywayFee.getWayCode().startsWith("ALI_")) {
                map.put("ALIPAY", new LklMercInfoConn.Fee("ALIPAY", Double.parseDouble(convertRate(paywayFee.getFeeRate())), null));
            }

            if ("D0".equals(paywayFee.getWayCode())) {
                double d0Rate = Double.parseDouble(convertRate(paywayFee.getFeeRate()));
                // 扫码d0费率
                map.put("SCAN_PAY_SECOND", new LklMercInfoConn.Fee("SCAN_PAY_SECOND", d0Rate, null));
                // 刷卡D0费率
                map.put("CARD_SECOND", new LklMercInfoConn.Fee("CARD_SECOND", d0Rate, null));
            }
        }

        // 扫码d0费率
        map.putIfAbsent("SCAN_PAY_SECOND", new LklMercInfoConn.Fee("SCAN_PAY_SECOND", 0.1d, null));
        // 刷卡D0费率
        map.putIfAbsent("CARD_SECOND", new LklMercInfoConn.Fee("CARD_SECOND", 0.1d, null));

        LklMercInfoConn.BizContent bizContent = new LklMercInfoConn.BizContent();

        String[] mccInfo = applymentInfo.getMccCode().split("_");
        bizContent.setMcc(mccInfo[1]);
        // 25为B2B收银台 13位专业扫码
        bizContent.setActivityId(13);
        bizContent.setTermNum("1");
        bizContent.setFees(new HashSet<>(map.values()));

        return bizContent;
    }

    @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) {
        LklspayIsvParams isvParams = ((LklspayIsvParams) configContextQueryService.queryIsvParams(mchApplyment));

        JSONObject param = new JSONObject();
        param.put("customerNo", mchApplyment.getChannelApplyNo());
        JSONObject respData = LklspayKit.applymentRequest(LklTkReqMethod.AUDIT_STATUS_GET, isvParams, param);
        JSONObject customer = respData.getJSONObject("customer");
        JSONArray terminalInfo = respData.getJSONArray("terminalInfo");

        String status = customer.getString("customerStatus");
        String externalCustomerNo = customer.getString("externalCustomerNo");

        if ("OPEN".equals(status)) {
            JSONArray customerFeeList = respData.getJSONArray("customerFee");
            String termId = null;
            // 将对应终端号下的终端id存下来
            for (int i = 0; i < customerFeeList.size(); i++) {
                JSONObject customerFee = customerFeeList.getJSONObject(i);
                String termNo = customerFee.getString("termNo");
                if (Objects.equals(termNo, customer.getString("termNo"))) {
                    termId = customerFee.getString("termId");
                    break;
                }
            }

            mchApplyment.setSuccResParameter(customer.toString());
            Optional.ofNullable(termId).ifPresent(t -> customer.put("termId", t));

            // 进件通过
            mchApplyment.setState(com.jeequan.jeepay.core.entity.MchApplyment.STATE_SUCCESS);
            mchApplyment.setChannelMchNo(externalCustomerNo);

            subMchColl(mchApplyment);
        }

        if ("REJECT".equals(status)) {
            // 入网驳回
            String auditRemark = customer.getString("auditRemark");
            mchApplyment.setSuccResParameter(customer.toJSONString());
            mchApplyment.setApplyErrorInfo("[" + auditRemark + "]");
            mchApplyment.setState(com.jeequan.jeepay.core.entity.MchApplyment.STATE_REJECT_WAIT_MODIFY);
        }

        return mchApplyment;
    }

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

    @Override
    public void subMchColl(com.jeequan.jeepay.core.entity.MchApplyment mchApplyment) {
        LklspayIsvParams isvParams = ((LklspayIsvParams) configContextQueryService.queryIsvParams(mchApplyment));

        JSONObject reqData = new JSONObject();
        String orderNo = DateUtil.format(new Date(), DateTimeFormatter.ofPattern("yyyyMMddHHmmss")) + RandomUtil.randomString(RandomUtil.BASE_NUMBER, 8);
        reqData.fluentPut("version", "1.0")
                .fluentPut("orderNo", orderNo)
                .fluentPut("orgCode", isvParams.getOrgCode())
                .fluentPut("merCupNo", mchApplyment.getChannelMchNo());

        JSONObject respData = LklspayKit.openRequest(LklTkReqMethod.QUERY_SUB_MERC, isvParams, reqData);

        JSONArray subMercList = respData.getJSONArray("list");

        if (subMercList == null) {
            return;
        }

        subMercList.forEach(item -> {
            if (item instanceof JSONObject) {
                JSONObject itemJson = (JSONObject) item;
                processItem(itemJson, mchApplyment);
            }
        });
    }

    private void processItem(JSONObject itemJson, com.jeequan.jeepay.core.entity.MchApplyment mchApplyment) {
        if ("UNIONPAY".equals(itemJson.getString("registerChannel"))) {
            // 收银呗
            saveSubMerch(mchApplyment.getApplyId(), mchApplyment.getChannelMchNo(), itemJson, 1);
        } else {
            // 扫码付不存拉卡拉的子商户号
            saveSubMerch(mchApplyment.getApplyId(), mchApplyment.getChannelMchNo(), itemJson, 0);
        }

//        if (!isLakalaSubMerchant(itemJson) && isWXZFRegisterType(itemJson)) {
//            saveSubMerch(mchApplyment.getApplyId(), mchApplyment.getChannelMchNo(), itemJson, 0);
//        } else {
//
//        }
    }

    /**
     * 是否是拉卡拉的商户号
     */
    private boolean isLakalaSubMerchant(JSONObject itemJson) {
        return "38630418".equals(itemJson.getString("channelId"));
    }

    /**
     * 是否是微信渠道
     */
    private boolean isWXZFRegisterType(JSONObject itemJson) {
        return "WXZF".equals(itemJson.getString("registerType"));
    }

    private void saveSubMerch(String mchApplyId, String channelMchNo, JSONObject itemJson, Integer isMainUse) {
        String resultCode = itemJson.getString("resultCode");

        MchSubInfoEntity subInfo = new MchSubInfoEntity();
        subInfo.setMchApplyId(mchApplyId);
        subInfo.setChannelId(itemJson.getString("channelId"));
        subInfo.setSubMchId(itemJson.getString("subMchId"));
        subInfo.setRemark(itemJson.getString("resultMessage"));
        subInfo.setChannelMchNo(channelMchNo);
        subInfo.setMainUse(isMainUse);
        subInfo.setSubMchWay(itemJson.getString("registerChannel"));
        if ("ZFBZF".equals(itemJson.getString("registerType"))) {
            subInfo.setSubMchType("ZFB");
        } else {
            subInfo.setSubMchType("WX");
        }

        subInfo.setStatus(resultCode);

        try {
            mchSubInfoService.save(subInfo);
        } catch (DuplicateKeyException e) {
            log.info("对应子商户信息已存在");
        }
    }

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

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

    public void wxAuthResult(com.jeequan.jeepay.core.entity.MchApplyment mchApplyment, MchSubInfo mchSubInfo) {
        LambdaUpdateWrapper<MchSubInfoEntity> uWrapper = Wrappers.lambdaUpdate();

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

        JSONObject reqData = new JSONObject();
        String orderNo = DateUtil.format(new Date(), DateTimeFormatter.ofPattern("yyyyMMddHHmmss")) + RandomUtil.randomString(RandomUtil.BASE_NUMBER, 8);
        reqData.fluentPut("version", "1.0")
                .fluentPut("orderNo", orderNo)
                .fluentPut("orgCode", isvParams.getOrgCode())
                .fluentPut("merCupNo", mchApplyment.getChannelMchNo());

        JSONObject req = LklspayKit.applymentRequest(LklTkReqMethod.QUERY_SUB_MERC, isvParams, reqData);

        JSONArray subMercList = req.getJSONArray("list");
        List<Object> filteredMercList = StreamUtil.of(subMercList)
                .filter(t -> ((JSONObject) t).getString("registerChannel").equals("UNIONPAY"))
                .filter(t -> ((JSONObject) t).getString("registerType").equals("WXZF"))
                .collect(Collectors.toList());

        // 拉卡拉开放平台商户号
        subMercList.getJSONObject(0);
        String subMchId = ((JSONObject) filteredMercList.get(0)).getString("subMchId");

        if (CharSequenceUtil.isEmpty(subMchId)) {
            return;
        }

        // 获取实名认证结果
        JSONObject reqData2 = new JSONObject();
        reqData2.fluentPut("merchantNo", mchApplyment.getChannelMchNo())
                .fluentPut("tradeMode", "WECHAT")
                .fluentPut("subMerchantId", subMchId);

        JSONObject respData = LklspayKit.openRequest(LklTkReqMethod.MCH_AUTH_STATUS, isvParams, reqData2);

        // 认证状态
        String authorizeState = respData.getString("checkResult");
        if ("AUTHORIZE_STATE_UNAUTHORIZED".equals(authorizeState)) {
            uWrapper.set(MchSubInfoEntity::getAuthStatus, MchSubInfo.AUTH_STATUS_UNAUTHORIZED);
        }

        if ("AUTHORIZE_STATE_AUTHORIZED".equals(authorizeState)) {
            uWrapper.set(MchSubInfoEntity::getAuthStatus, MchSubInfo.AUTH_STATUS_AUTHORIZED);
        }

        String rejectReason = respData.getString("rejectReason");

        uWrapper.set(MchSubInfoEntity::getRemark, rejectReason);
        uWrapper.set(MchSubInfoEntity::getSubMchId, subMchId);

        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);
    }

    public void zfbAuthResult(com.jeequan.jeepay.core.entity.MchApplyment mchApplyment, MchSubInfo mchSubInfo) {
        LambdaUpdateWrapper<MchSubInfoEntity> uWrapper = Wrappers.lambdaUpdate();

        LklspayIsvParams isvParams = ((LklspayIsvParams) configContextQueryService.queryIsvParams(mchApplyment));
        JSONObject reqData = new JSONObject();
        String orderNo = DateUtil.format(new Date(), DateTimeFormatter.ofPattern("yyyyMMddHHmmss")) + RandomUtil.randomString(RandomUtil.BASE_NUMBER, 8);
        reqData.fluentPut("version", "1.0")
                .fluentPut("orderNo", orderNo)
                .fluentPut("orgCode", isvParams.getOrgCode())
                .fluentPut("merCupNo", mchApplyment.getChannelMchNo());

        JSONObject req = LklspayKit.applymentRequest(LklTkReqMethod.QUERY_SUB_MERC, isvParams, reqData);

        JSONArray subMercList = req.getJSONArray("list");
        List<Object> filteredMercList = subMercList.stream()
                .filter(t -> ((JSONObject) t).getString("registerChannel").equals("UNIONPAY"))
                .filter(t -> ((JSONObject) t).getString("registerType").equals("ZFBZF"))
                .collect(Collectors.toList());

        // 拉卡拉开放平台商户号
        subMercList.getJSONObject(0);
        String subMchId = ((JSONObject) filteredMercList.get(0)).getString("subMchId");

        if (CharSequenceUtil.isEmpty(subMchId)) {
            return;
        }

        // 获取实名认证结果
        JSONObject reqData2 = new JSONObject();
        reqData2.fluentPut("merchantNo", mchApplyment.getChannelMchNo())
                .fluentPut("tradeMode", "ALIPAY")
                .fluentPut("subMerchantId", subMchId);

        JSONObject respData = LklspayKit.openRequest(LklTkReqMethod.MCH_AUTH_STATUS, isvParams, reqData2);

        // 认证状态
        String authorizeState = respData.getString("checkResult");
        if ("UNAUTHORIZED".equals(authorizeState)) {
            uWrapper.set(MchSubInfoEntity::getAuthStatus, MchSubInfo.AUTH_STATUS_UNAUTHORIZED);
        }

        if ("AUTHORIZED".equals(authorizeState)) {
            uWrapper.set(MchSubInfoEntity::getAuthStatus, MchSubInfo.AUTH_STATUS_AUTHORIZED);
        }

//        if ("CLOSED".equals(authorizeState)) {
//            ums.setAliCertStatus("-1");
//        }

        String rejectReason = respData.getString("rejectReason");

        uWrapper.set(MchSubInfoEntity::getRemark, rejectReason);
        uWrapper.set(MchSubInfoEntity::getSubMchId, subMchId);

        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);
    }
}
