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

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jeequan.jeepay.converter.BaseConverter;
import com.jeequan.jeepay.converter.MchInfoConverter;
import com.jeequan.jeepay.core.constants.ApiCodeEnum;
import com.jeequan.jeepay.core.entity.MchApplyment;
import com.jeequan.jeepay.core.entity.MchModifyApplyment;
import com.jeequan.jeepay.core.exception.BizException;
import com.jeequan.jeepay.core.interfaces.paychannel.IYsApplymentApiService;
import com.jeequan.jeepay.core.model.applyment.ApplymentSignInfo;
import com.jeequan.jeepay.core.model.applyment.PaywayFee;
import com.jeequan.jeepay.core.model.applyment.YspayApplymentInfo;
import com.jeequan.jeepay.core.model.params.yspay.YspayIsvParams;
import com.jeequan.jeepay.core.model.params.yspay.YspayIsvsubMchParams;
import com.jeequan.jeepay.core.model.rqrs.msg.ChannelRetMsg;
import com.jeequan.jeepay.core.utils.JsonKit;
import com.jeequan.jeepay.core.utils.SeqKit;
import com.jeequan.jeepay.core.utils.SpringBeansUtil;
import com.jeequan.jeepay.db.entity.MchModifyApplymentEntity;
import com.jeequan.jeepay.service.impl.MchApplymentService;
import com.jeequan.jeepay.service.impl.MchModifyApplymentService;
import com.jeequan.jeepay.service.impl.SysConfigService;
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.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * 银盛进件
 *
 *
 * @date 2022/7/18 14:30
 */
@Service
@Slf4j
public class YspayApplymentApiService implements IYsApplymentApiService {

    @Autowired
    protected SysConfigService sysConfigService;

    @Autowired
    private ConfigContextQueryService configContextQueryService;

    @Autowired
    private BaseConverter baseConverter;

    @Autowired
    private MchApplymentService mchApplymentService;

    @Autowired
    private MchModifyApplymentService mchModifyApplymentService;

    @Autowired
    private MchInfoConverter mchInfoConverter;

    /**
     * @author: xiaoyu
     * @date: 2022/7/20 11:02
     * @describe: 图片上传接口
     */
    @Override
    public MchApplyment uploadImg(MchApplyment mchApplyment) {

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

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

        try {
            JSONArray uploadArr = new JSONArray();
            // 进件渠道号
            String applyNo = mchApplyment.getChannelApplyNo();

            // 非小微商户必填
            if (applymentInfo.getMerchantType() != MchApplyment.MERCHANT_TYPE_PERSONAL) {
                // 营业执照
                setArrImgResult(uploadArr, YspayKit.uploadRequest(applyNo, isvParams, applymentInfo.getLicenseImg(), "A001"));
            }
            // 法人身份证人像面
            setArrImgResult(uploadArr, YspayKit.uploadRequest(applyNo, isvParams, applymentInfo.getIdcard1Img(), "A002"));
            // 法人身份证国徽面
            setArrImgResult(uploadArr, YspayKit.uploadRequest(applyNo, isvParams, applymentInfo.getIdcard2Img(), "A003"));
            // 手持身份证照
//            setArrImgResult(uploadArr, YspayKit.uploadRequest(applyNo, isvParams, applymentInfo.getIdcardInHandImg(), "A009"));

            // 非小微或企业非对私
            if (MchApplyment.MERCHANT_TYPE_PERSONAL != applymentInfo.getMerchantType() && !"C".equals(applymentInfo.getSettAccountType())) {
                // 开户许可证
                setArrImgResult(uploadArr, YspayKit.uploadRequest(applyNo, isvParams, applymentInfo.getCompanyAccountLicenseImg(), "A011"));
            } else {
                // 结算账户正面
                setArrImgResult(uploadArr, YspayKit.uploadRequest(applyNo, isvParams, applymentInfo.getSettAccountLicenseImg(), "A004"));
                // 结算账户反面
                setArrImgResult(uploadArr, YspayKit.uploadRequest(applyNo, isvParams, applymentInfo.getSettAccountLicenseImg(), "A005"));
            }

            if ("Y".equals(applymentInfo.getIsUncrpSett())) {
                // 非法人身份证人像面
                setArrImgResult(uploadArr, YspayKit.uploadRequest(applyNo, isvParams, applymentInfo.getSettAccountIdcard1Img(), "A013"));
                // 非法人身份证国徽面
                setArrImgResult(uploadArr, YspayKit.uploadRequest(applyNo, isvParams, applymentInfo.getSettAccountIdcard2Img(), "A014"));
                // 结算授权书
                setArrImgResult(uploadArr, YspayKit.uploadRequest(applyNo, isvParams, applymentInfo.getSettleAuthLetterPhoto(), "B005"));
                // 法人手持结算授权书
//                setArrImgResult(uploadArr, YspayKit.uploadRequest(applyNo, isvParams, applymentInfo.getSettleAuthLetterHandlePhoto(), "B004"));
            } else {
                // 法人身份证人像面
                setArrImgResult(uploadArr, YspayKit.uploadRequest(applyNo, isvParams, applymentInfo.getIdcard1Img(), "A013"));
                // 法人身份证国徽面
                setArrImgResult(uploadArr, YspayKit.uploadRequest(applyNo, isvParams, applymentInfo.getIdcard2Img(), "A014"));
            }

            // 门头照
            setArrImgResult(uploadArr, YspayKit.uploadRequest(applyNo, isvParams, applymentInfo.getStoreOuterImg(), "A006"));
            // 内景照
            setArrImgResult(uploadArr, YspayKit.uploadRequest(applyNo, isvParams, applymentInfo.getStoreInnerImg(), "A007"));
            // 收银台照
            setArrImgResult(uploadArr, YspayKit.uploadRequest(applyNo, isvParams, applymentInfo.getStoreCashierImg(), "A008"));
            // 收单协议照
            setArrImgResult(uploadArr, YspayKit.uploadRequest(applyNo, isvParams, applymentInfo.getAcquiringAgreementPhoto(), "A010"));
            // 其他1
            setArrImgResult(uploadArr, YspayKit.uploadRequest(applyNo, isvParams, applymentInfo.getOther1(), "B008"));

            // 上传图片结果
//            result.setChannelVar1(uploadArr.toJSONString());
            result.setApplyDetailInfo(mchApplyment.getApplyDetailInfo());
            return result;
        } catch (Exception e) {
            log.error("银盛进件失败：", e);
            throw new BizException(e.getMessage());
        }
    }

    /**
     * @date: 2022/7/19 16:27
     * @describe: 图片存放
     */
    private static void setArrImgResult(JSONArray arrayImg, JSONObject params) {
        if (params != null) {
            arrayImg.add(params);
        }
    }

    /**
     * @date: 2022/7/20 11:02
     * @describe: 提交初审
     */
    @Override
    public MchApplyment attachConfirm(MchApplyment mchApplyment) {

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

        MchApplyment result = new MchApplyment();
        result.setState(mchApplyment.getState());

        try {
            JSONObject bizContent = new JSONObject();
            // 请求参数
            bizContent.put("sysFlowId", mchApplyment.getChannelApplyNo());
            bizContent.put("auditFlag", "Y");
            // 发送请求
            String resultStr = YspayKit.applymentRequest("/openapi/t1/smsc/auditCustInfoApply", "t1.smsc.auditCustInfoApply", isvParams, bizContent);
            JSONObject response = JSON.parseObject(resultStr);

            // 解密后数据
            JSONObject resData = response.getJSONObject("data");
            if (resData == null) {
                result.setState(MchApplyment.STATE_REJECT_WAIT_MODIFY);
                result.setApplyErrorInfo(response.getString("code") + "[" + response.getString("note") + "]");
                log.error("【银盛进件】提交审核请求失败：code={}, msg={}", response.getString("code"), response.getString("note"));
                return result;
            }

            // 入网状态,00:入网成功 01:待上传图片 02:待审核 90:审核拒绝 10:转人工审核
            String status = resData.getString("status");
            if ("00".equals(status)) {
                // 留给异步处理
                return mchApplyment;
            } else if ("01".equals(status)) {
                JSONObject sucJSON = JsonKit.newJson("custId", resData.getString("custId"));
                sucJSON.put("sysFlowId", resData.getString("sysFlowId"));
                result.setSuccResParameter(sucJSON.toJSONString());
                result.setRemainStep(((byte) 2));
                result.setState(MchApplyment.STATE_WAIT_VERIFY);
                return result;
            } else if ("10".equals(status)) {
                // 转人工审核
                result.setState(MchApplyment.STATE_UPSTREAM_MANUAL_REVIEW);
                result.setApplyErrorInfo("[" + resData.getString("note") + "]");
                result.setRemainStep((byte) 0);
                return result;
            } else if ("90".equals(status)) {
                // 审核拒绝
                result.setState(MchApplyment.STATE_REJECT_WAIT_MODIFY);
                result.setApplyErrorInfo("[" + resData.getString("note") + "]");
                result.setRemainStep((byte) 0);
                return result;
            } else {
                result.setApplyErrorInfo("[" + resData.getString("note") + "]");
                return result;
            }

        } catch (BizException e) {
            if (e.getApiRes().getCode().equals(ApiCodeEnum.YS_ARTIFICIAL_AUDIT_CODE.getCode())) {
                // 转人工审核
                result.setState(MchApplyment.STATE_UPSTREAM_MANUAL_REVIEW);
                result.setApplyErrorInfo("[" + e.getMessage() + "]");
                result.setRemainStep((byte) 0);
                return result;
            } else {
                throw e;
            }
        } catch (Exception e) {
            log.error("银盛进件失败：", e);
            throw new BizException(e.getMessage());
        }
    }


    /**
     * @date: 2022/7/21 10:23
     * @describe: 费率配置
     */
    @Override
    public MchApplyment signApply(JSONObject reqParamJSON, MchApplyment record) {

        MchApplyment result = new MchApplyment();
        ApplymentSignInfo signInfo = new ApplymentSignInfo();

        try {
            // 费率信息
            List<PaywayFee> paywayFeeList = JSON.parseArray(reqParamJSON.getString("paywayFeeList"), PaywayFee.class);

            // 获取到 渠道商配置信息
            ConfigContextQueryService configContextQueryService = SpringBeansUtil.getBean(ConfigContextQueryService.class);
            YspayIsvParams isvParams = (YspayIsvParams) configContextQueryService.queryIsvParams(record);

            JSONObject channelVar1 = JSON.parseObject(record.getChannelVar1());

            // 请求参数
            JSONObject bizContent = new JSONObject();
            bizContent.put("custId", channelVar1.getString("custId"));
            bizContent.put("contractType", "2"); // 合同类型,1-纸质合同、2-电子合同
            bizContent.put("isSendConMsg", "1"); // 是否自动发送签约通知, contractType=2时必填 0(短信+邮件) 1(短信) 2(邮件) 3(不通知)
            // 异步通知地址，这里将channelApplyNo传进去，方便签约回调时好找到商户信息
            bizContent.put("notifyUrl", sysConfigService.getDBApplicationConfig().getPaySiteUrl() + "/api/mchApplyment/notify/" + record.getIfCode() + "/" + record.getApplyId());

//            bizContent.put("busOpenType", "00"); // 到账方式,00-扫码工作日到账
            bizContent.put("codeScanT1Fee", YspayApplymentInfo.convertFeeJSON(paywayFeeList, "1"));
            // 结算方式 1- T1    2-D1   3-D0
//            bizContent.put("d1Fee", YspayApplymentInfo.convertFeeJSON(paywayFeeList, "2"));
            // 开通D0, 支付时可通过接口传参来选择D1、D0支付方式
            // 00-（T1）扫码工作日到账，01-（D0）扫码实时到账，20-天天到账，D1到账
            bizContent.put("busOpenType", "00|01"); // 到账方式,01-扫码实时到账
            bizContent.put("codeScanD0Fee", YspayApplymentInfo.convertFeeJSON(paywayFeeList, "3"));

            // 发送请求
            String resStr = YspayKit.applymentRequest("/openapi/t1/smsc/sign", "t1.smsc.sign", isvParams, bizContent);
            JSONObject response = JSON.parseObject(resStr);

            // 解密后数据
            JSONObject resData = response.getJSONObject("data");
            if (resData == null) {
                signInfo.setErrInfo(response.getString("code") + "[" + response.getString("note") + "]");
                log.error("【银盛进件】提交审核请求失败：code={}, msg={}", response.getString("code"), response.getString("note"));
                result.setChannelVar2(JSON.toJSONString(signInfo));
                result.setState(MchApplyment.STATE_REJECT_WAIT_MODIFY);
                return result;
            }

            signInfo.setSignUrl(resData.getString("signUrl"));
            signInfo.setState("签约中");
            signInfo.setOriginData(resData.toJSONString());

            result.setChannelVar2(JSON.toJSONString(signInfo));

            // 费率信息
            JSONObject applyDetailJSON = JSON.parseObject(record.getApplyDetailInfo());
            applyDetailJSON.put("paywayFeeList", paywayFeeList);
            result.setApplyDetailInfo(applyDetailJSON.toJSONString());
            result.setState(MchApplyment.STATE_WAIT_SIGN);

            return result;

        } catch (Exception e) {
            log.info("签约异常", e);
            throw new BizException("签约异常[" + e.getMessage() + "]");
        }
    }

    @Override
    public MchApplyment signSendAgain(JSONObject reqParamJSON, MchApplyment mchApplyment) {

        MchApplyment result = new MchApplyment();
        ApplymentSignInfo signInfo = new ApplymentSignInfo();

        try {

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

            if (StringUtils.isEmpty(mchApplyment.getChannelVar2())) {
                log.error("【银盛进件】签约重发失败，签约参数缺失：{}", mchApplyment.getChannelVar2());
                signInfo.setErrInfo("签约重发失败，签约参数缺失");
                result.setChannelVar2(JSON.toJSONString(signInfo));
                return result;
            }
            JSONObject channelV2Json = JSON.parseObject(mchApplyment.getChannelVar2());
            JSONObject originData = channelV2Json.getJSONObject("originData");
            if (originData == null) {
                log.error("【银盛进件】签约重发失败，签约参数缺失");
                signInfo.setErrInfo("签约重发失败，签约参数缺失");
                result.setChannelVar2(JSON.toJSONString(signInfo));
                return result;
            }

            // 请求参数
            JSONObject bizContent = new JSONObject();
            bizContent.put("signId", originData.getString("signId"));
            bizContent.put("isSendConMsg", "0");

            // 发送请求
            String resStr = YspayKit.applymentRequest("/openapi/smsc/sign/sendSmsOrEmailMsg", "smsc.sign.sendSmsOrEmailMsg", isvParams, bizContent);
            JSONObject response = JSON.parseObject(resStr);

            // 解密后数据
            JSONObject resData = response.getJSONObject("data");
            if (resData == null) {
                signInfo.setErrInfo(response.getString("code") + "[" + response.getString("note") + "]");
                log.error("【银盛进件】签约重发失败：code={}, msg={}", response.getString("code"), response.getString("note"));
                result.setChannelVar2(JSON.toJSONString(signInfo));
                return result;
            }
            signInfo.setSignUrl(resData.getString("signUrl"));
            signInfo.setState("签约中");
            signInfo.setOriginData(resData.toJSONString());

            result.setChannelVar2(JSON.toJSONString(signInfo));
            return result;

        } catch (Exception e) {
            log.info("签约重发异常", e);
            throw new BizException("签约重发异常" + e.getMessage());
        }
    }

    /**
     * 获取签约地址
     */
    @Override
    public MchApplyment signQuery(MchApplyment mchApplyment) {

        MchApplyment result = new MchApplyment();
        ApplymentSignInfo signInfo = new ApplymentSignInfo();
        result.setState(mchApplyment.getState());
        try {
            // 获取到 渠道商配置信息
            YspayIsvParams isvParams = (YspayIsvParams) configContextQueryService.queryIsvParams(mchApplyment);

            // 查询数据库签约信息
            ApplymentSignInfo channelVar2Data = JSON.parseObject(mchApplyment.getChannelVar2(), ApplymentSignInfo.class);

            // 合并数据
            baseConverter.cp(channelVar2Data, signInfo);

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

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

            // 解密后数据
            JSONObject resData = response.getJSONObject("data");
            if (resData == null) {
                signInfo.setState("签约失败");
                signInfo.setErrInfo(response.getString("code") + "[" + response.getString("msg") + "]");
                result.setChannelVar2(JSON.toJSONString(signInfo));
                result.setState(MchApplyment.STATE_REJECT_WAIT_MODIFY);
                return result;
            }

            // 审核状态
            if ("00".equals(resData.getString("status"))) {
                signInfo.setState("签约成功");
                // 签约完成，返回商户号
                JSONObject sucJSON = JSON.parseObject(mchApplyment.getSuccResParameter());
                if (sucJSON == null) {
                    sucJSON = new JSONObject();
                }
                sucJSON.put("mercId", resData.getString("mercId"));
                result.setSuccResParameter(sucJSON.toJSONString());
                result.setChannelMchNo(resData.getString("mercId"));
                result.setState(MchApplyment.STATE_SUCCESS);

                // TODO 银盛入网签约完成 业务大厅添加变更数据将T1变为D1并待审核
                if ("yspay".equals(mchApplyment.getIfCode())) {
                    MchModifyApplymentEntity modifyApplyment = new MchModifyApplymentEntity();
                    modifyApplyment.setModifyApplyId(SeqKit.genMchNotifyApplyNo());
                    modifyApplyment.setApplyId(mchApplyment.getApplyId());
                    //modifyApplyment.setChannelApplyNo(mchApplyment.getChannelApplyNo());
                    modifyApplyment.setChannelMchNo(mchApplyment.getChannelMchNo());
                    modifyApplyment.setMchNo(mchApplyment.getMchNo());
                    modifyApplyment.setIfCode(mchApplyment.getIfCode());
                    modifyApplyment.setIfName(mchApplyment.getIfName());
                    //商户本次变更前数据
                    com.jeequan.jeepay.db.entity.MchApplyment applyment = mchApplymentService.getById(mchApplyment.getApplyId());
                    String jsonString = JSONObject.toJSONString(applyment);
                    modifyApplyment.setOriginDetailInfo(jsonString);
                    //商户本次变更信息
                    modifyApplyment.setApplyDetailInfo("{\"settlementType\":\"D1\"}");
                    modifyApplyment.setApplyPageType(applyment.getApplyPageType());
                    //变更类型为6 结算类型变更
                    modifyApplyment.setModifyApplyType((byte) 6);
                    //状态默认为审核中
                    modifyApplyment.setState((byte) 1);
                    modifyApplyment.setCreatedAt(new Date());
                    mchModifyApplymentService.save(modifyApplyment);
                }
            } else if ("04".equals(resData.getString("status"))) {
                signInfo.setState("签约失败");
                signInfo.setErrInfo(resData.getString("note"));
                result.setState(MchApplyment.STATE_REJECT_WAIT_MODIFY);
            } else if ("03".equals(resData.getString("status"))) {
                signInfo.setState("待审核");
            } else {
                signInfo.setState("签约中");
            }
            result.setChannelVar2(JSON.toJSONString(signInfo));
            return result;

        } catch (Exception e) {
            signInfo.setState("签约中");
            signInfo.setErrInfo("异常信息" + e.getMessage());
            result.setChannelVar2(JSON.toJSONString(signInfo));
            return result;
        }
    }


    @Override
    public MchModifyApplyment signSendAgain(JSONObject reqParamJSON, MchModifyApplyment modifyApplyment) {

        MchModifyApplyment result = new MchModifyApplyment();
        ApplymentSignInfo signInfo = new ApplymentSignInfo();

        MchApplyment mchApplyment = mchInfoConverter.toModel(mchApplymentService.getById(modifyApplyment.getApplyId()));

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

            if (StringUtils.isEmpty(modifyApplyment.getChannelVar1())) {
                log.error("【银盛进件】签约重发失败，签约参数缺失：{}", mchApplyment.getChannelVar2());
                signInfo.setErrInfo("签约重发失败，签约参数缺失");
                result.setChannelVar1(JSON.toJSONString(signInfo));
                return result;
            }
            JSONObject channelV1Json = JSON.parseObject(modifyApplyment.getChannelVar1());
            if (channelV1Json == null) {
                log.error("【银盛进件】签约重发失败，签约参数缺失");
                signInfo.setErrInfo("签约重发失败，签约参数缺失");
                result.setChannelVar1(JSON.toJSONString(signInfo));
                return result;
            }

            // 请求参数
            JSONObject bizContent = new JSONObject();
            bizContent.put("signId", channelV1Json.getString("signId"));
            bizContent.put("isSendConMsg", "0");

            // 发送请求
            String resStr = YspayKit.applymentRequest("/openapi/smsc/sign/sendSmsOrEmailMsg", "smsc.sign.sendSmsOrEmailMsg", isvParams, bizContent);
            JSONObject response = JSON.parseObject(resStr);

            // 解密后数据
            JSONObject resData = response.getJSONObject("data");
            if (resData == null) {
                signInfo.setErrInfo(response.getString("code") + "[" + response.getString("note") + "]");
                log.error("【银盛进件】签约重发失败：code={}, msg={}", response.getString("code"), response.getString("note"));
                result.setChannelVar1(JSON.toJSONString(signInfo));
                return result;
            }
            signInfo.setSignUrl(resData.getString("signUrl"));
            signInfo.setState("签约中");
            signInfo.setOriginData(resData.toJSONString());

            result.setChannelVar1(JSON.toJSONString(signInfo));
            return result;

        } catch (Exception e) {
            log.info("签约重发异常", e);
            throw new BizException("签约重发异常" + e.getMessage());
        }
    }

    /**
     * @date: 2022/7/21 10:23
     * @describe: 费率配置
     */
    @Override
    public MchApplyment payRateConfig(JSONObject reqParamJSON, MchApplyment mchApplyment) {
//      云商服2.0接口不接入
        // 获取到 渠道商配置信息
//        ConfigContextQueryService configContextQueryService = SpringBeansUtil.getBean(ConfigContextQueryService.class);
//        YspayIsvParams isvParams = (YspayIsvParams)configContextQueryService.queryIsvParams(mchApplyment);
//        MchApplyment result = new MchApplyment();
//        try {
//            List<PaywayFee> paywayFeeList = JSON.parseArray(reqParamJSON.getString("paywayFeeList"), PaywayFee.class);
//            // 获取商户信息
//            if (StringUtils.isEmpty(mchApplyment.getSuccResParameter())) {
//                result.setChannelVar1("商户信息不能为空");
//                result.setState(MchApplyment.STATE_REJECT_WAIT_MODIFY);
//                return result;
//            }
//            JSONObject mchParasmJson = JSONObject.parseObject(mchApplyment.getSuccResParameter());
//            if (mchParasmJson == null || StringUtils.isEmpty(mchParasmJson.getString("mercId"))) {
//                result.setChannelVar1("商户信息不能为空");
//                result.setState(MchApplyment.STATE_REJECT_WAIT_MODIFY);
//                return result;
//            }
//            // 费率参数修改
//            YspayApplymentInfo applymentInfo = JSONObject.parseObject(mchApplyment.getApplyDetailInfo(), YspayApplymentInfo.class);
//            applymentInfo.setPaywayFeeList(paywayFeeList);
//            JSONObject infoJson = (JSONObject) JSONObject.toJSON(applymentInfo);
//            result.setApplyDetailInfo(infoJson.toJSONString());
//
//            // 商户号
//            String mercId = mchParasmJson.getString("mercId");
//            JSONObject bizContent = new JSONObject();
//            // 商户号
//            bizContent.put("mercId", mercId);
//            // 机构号
//            bizContent.put("accOrgNo", isvParams.getSrc());
//
//            JSONObject jsonObject = YspayApplymentInfo.convertPayConfig(paywayFeeList);
//            // 交易权限
//            bizContent.put("scanServiceOpen", jsonObject.getString("scanServiceOpen"));
//            // 费率信息
//            bizContent.put("easyFeeBean", jsonObject.getJSONObject("easyFeeBean"));
//            log.info("[银盛费率配置] bizContent:{}", bizContent);
//            // 发送请求
//            String resultStr = YspayKit.applymentRequest("/saas/orgScan/onlineTrading", "onlineTrading", isvParams, bizContent);
//            JSONObject response = JSONObject.parseObject(resultStr);
//            JSONObject resData = response.getJSONObject("data");
//            String code = resData.getString("code");
//            if ("00".equals(code)) {
//                result.setState(MchApplyment.STATE_SUCCESS);
//                result.setChannelVar1("【银盛费率配置】配置成功" + resData.toJSONString());
//            }else {
//                result.setState(MchApplyment.STATE_REJECT_WAIT_MODIFY);
//                result.setChannelVar1("【银盛费率配置】配置失败"  + resData.toJSONString());
//                log.error("请求失败：code={}, msg={}", code, resData.getString("note"));
//            }
//
//            // 开通D0到账
//            JSONObject bizContentOpen = new JSONObject();
//            // 商户号
//            bizContentOpen.put("mercId", mercId);
//            // 1-开通 0-关闭
//            bizContentOpen.put("opType", "1");
//            // 垫资费率
//            bizContentOpen.put("feeRate", "0.02");
//            // 垫资最低金额（分）
//            bizContentOpen.put("feeMin", "1");
//            log.info("[银盛开通D0到账] bizContentOpen：{}", bizContentOpen);
//            String resultOpenStr = YspayKit.applymentRequest("/saas/orgScan/optOnlineD0", "optOnlineD0", isvParams, bizContentOpen);
//            JSONObject responseOpen = JSONObject.parseObject(resultOpenStr);
//            JSONObject resDataOpen = responseOpen.getJSONObject("data");
//            String codeOpen = resDataOpen.getString("code");
//            if ("00".equals(codeOpen)) {
//                result.setState(MchApplyment.STATE_SUCCESS);
//                result.setChannelVar1(result.getChannelVar1() + "  【银盛开通D0到账】配置成功" + resDataOpen.toJSONString());
//            }else {
//                result.setState(MchApplyment.STATE_REJECT_WAIT_MODIFY);
//                result.setChannelVar1(result.getChannelVar1() + "  【银盛开通D0到账】配置失败"+ resDataOpen.toJSONString());
//                log.error("请求失败：code={}, msg={}", code, resDataOpen.getString("note"));
//            }
//
//        } catch (Exception e) {
//            log.error("银盛进件[配置费率]失败：", e);
//            throw new BizException(e.getMessage());
//        }

        return mchApplyment;
    }

    @Override
    public ChannelRetMsg configBindAppId(String configVal, String mchAppId, MchApplyment mchApplyment) {
        JSONObject bizContent = new JSONObject();
        JSONObject params = JSON.parseObject(configVal);
        String mchType = getWxMchType(params.getString("mchType"));
        bizContent.put("mchType", mchType);
        bizContent.put("appletAppid", params.getString("configWxBindLiteAppId"));
        return commonReq(mchApplyment, mchAppId, bizContent);
    }

    @Override
    public ChannelRetMsg configSubscribeAppId(String configVal, String mchAppId, MchApplyment mchApplyment) {
        JSONObject bizContent = new JSONObject();
        JSONObject params = JSON.parseObject(configVal);
        String mchType = getWxMchType(params.getString("mchType"));
        bizContent.put("mchType", mchType);
        bizContent.put("appid", params.getString("configWxBindAppId"));
        return commonReq(mchApplyment, mchAppId, bizContent);
    }

    @Override
    public ChannelRetMsg configPayBaseUrl(String configVal, String mchAppId, MchApplyment mchApplyment) {
        JSONObject bizContent = new JSONObject();
        JSONObject params = JSON.parseObject(configVal);
        String mchType = getWxMchType(params.getString("mchType"));
        bizContent.put("mchType", mchType);
        bizContent.put("jsapiPath1", params.getString("configWxPayBaseUrl"));
        return commonReq(mchApplyment, mchAppId, bizContent);
    }

    private ChannelRetMsg commonReq(MchApplyment mchApplyment, String mchAppId, JSONObject bizContent) {

        // 获取到 渠道商配置信息
        ConfigContextQueryService configContextQueryService = SpringBeansUtil.getBean(ConfigContextQueryService.class);
        YspayIsvParams isvParams = (YspayIsvParams) configContextQueryService.queryIsvParams(mchApplyment);
        YspayIsvsubMchParams isvsubMchParams = (YspayIsvsubMchParams) configContextQueryService.queryIsvsubMchParams(mchApplyment.getMchNo(), mchAppId, mchApplyment.getIfCode());

        // 商户进件参数
        YspayApplymentInfo applymentInfo = JSON.parseObject(mchApplyment.getApplyDetailInfo(), YspayApplymentInfo.class);

        if (isvsubMchParams == null || StringUtils.isEmpty(isvsubMchParams.getMercId())) {
            return ChannelRetMsg.confirmFail(null, "", "商户应用参数未配置，请先配置参数到应用");
        }
        // 商户号
        bizContent.put("mercId", isvsubMchParams.getMercId());
        // 渠道编号 微信支付（网联）
        bizContent.put("reportChannel", "NUCC_WECHAT");
        // 商户归属省
        bizContent.put("mercProv", applymentInfo.getMercProv());
        // 商户归属市
        bizContent.put("mercCity", applymentInfo.getMercCity());
        // 商户归属区
        bizContent.put("mercArea", applymentInfo.getMercArea());
        // 商户联系人姓名
        bizContent.put("contactsName", applymentInfo.getContactName());
        // 商户联系人手机
        bizContent.put("contactsTel", applymentInfo.getContactPhone());

        // 发送请求
        String resultStr = YspayKit.wxQueryRequest("https://multiapi.ysepay.com:2443/busi-gate-api/mercScanReport",
                "https://multiapi.ysepay.com", "ysepay.merchant.scan.report", isvParams, bizContent);
        JSONObject response = JSON.parseObject(resultStr);
        JSONObject resData = response.getJSONObject("ysepay_merchant_scan_report_response");
        String respCode = resData.getString("respCode");
        // 请求异常
        if (!"00".equals(respCode)) {
            return ChannelRetMsg.confirmFail(null, respCode, resData.getString("respMsg"));
        }
        String apprSts = resData.getString("apprSts");
        // 业务异常
        if (!"00".equals(apprSts)) {
            return ChannelRetMsg.confirmFail(null, apprSts, resData.getString("remark"));
        }

        return ChannelRetMsg.confirmSuccess(null);
    }

    private static String getWxMchType(String mchType) {
        if (StringUtils.isNotEmpty(mchType)) {
            String[] split = mchType.split("_");
            return split[1];
        }
        return null;
    }
}
