package com.hfkj.channel.lakala;

import com.alibaba.fastjson.JSONObject;
import com.hfkj.channel.lakala.config.LaKaLaConfig;
import com.hfkj.channel.saas.utils.SaasCommon;
import com.hfkj.common.exception.ErrorCode;
import com.hfkj.common.exception.ErrorHelp;
import com.hfkj.common.exception.SysCode;
import com.hfkj.common.utils.DateUtil;
import com.hfkj.common.utils.HttpsUtils;
import com.hfkj.common.utils.ImageUtils;
import com.hfkj.common.utils.UnionUtils;
import com.hfkj.config.CommonSysConst;
import com.hfkj.entity.*;
import com.hfkj.model.MerBasisModel;
import com.hfkj.service.*;
import com.hfkj.sysenum.*;
import com.hfkj.sysenum.lakala.UploadFileTypeEnum;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.File;
import java.math.BigDecimal;
import java.util.*;

/**
 * 拉卡拉分账
 * @author hurui
 */
@Service
public class LaKaLaLedgerService {

    @Resource
    private BsMerLedgerService merLedgerService;
    @Resource
    private BsMerLedgerApplyService merLedgerApplyService;
    @Resource
    private BsMerLedgerReceiverService merLedgerReceiverService;
    @Resource
    private BsMerLedgerReceiverApplyService merLedgerReceiverApplyService;
    @Resource
    private BsMerService merService;
    @Resource
    private BsMerAttachService merAttachService;
    @Resource
    private BsMerPlatformNoService merPlatformNoService;
    @Resource
    private CommonService commonService;

    /**
     * 商户分账业务开通申请
     * @param merLedgerId
     * @return
     */
    public JSONObject applyLedger(Long merLedgerId) {
        //
        BsMerLedger merLedger = merLedgerService.getMerLedgerById(merLedgerId);
        if (merLedger == null || !merLedger.getPlatformType().equals(PlatformTypeEnum.type1.getNumber())) {
            throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
        }
        // 商户
        BsMer mer = merService.getMer(merLedger.getMerId());
        if (mer == null) {
            throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未找到商户");
        }
        SecDictionary org = commonService.mappingSysCode("ORG_NO", mer.getOrgNo());
        if (org == null) {
            throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未知的机构");
        }
        Map<String, Object> commonParam = new HashMap<>();
        commonParam.put("reqTime", DateUtil.format(new Date(), "yyyyMMddHHmmss"));
        commonParam.put("version", "1.0.0");
        commonParam.put("reqId", UnionUtils.createNonceStr());

        String orderNo = System.currentTimeMillis()+"";
        Map<String, Object> map = new HashMap<>();
        map.put("version", "1.0");
        map.put("orderNo", orderNo);
        map.put("orgCode", org.getExt1());
        map.put("merCupNo", merLedger.getCupNo());
        map.put("contactMobile", mer.getRegPhone());
        map.put("splitLowestRatio", merLedger.getSplitLowestRatio());
        map.put("splitEntrustFileName", merLedger.getSplitEntrustFileName());
        // 转换成bas64
        String base64ImgUrl = ImageUtils.getBase64ByImgUrl(CommonSysConst.getSysConfig().getObs_url()+merLedger.getSplitEntrustFilePath());
        String fileType = merLedger.getSplitEntrustFilePath().substring(merLedger.getSplitEntrustFilePath().lastIndexOf(".") + 1);
        map.put("splitEntrustFilePath", LaKaLaConfig.uploadFile("COOPERATION_QUALIFICATION_PROOF", fileType, base64ImgUrl).getString("attFileId"));
        map.put("splitRange", "MARK");
        map.put("retUrl", CommonSysConst.getSysConfig().getDomainName() + "/crest/laKaLaNotify/applyLedgerMer");
        commonParam.put("reqData", map);

        Map<String, Object> reqParam = LaKaLaConfig.generateSignParamsV2(JSONObject.parseObject(JSONObject.toJSONString(commonParam)));
        // 头部参数
        Map<String, Object> heard = new HashMap<>();
        heard.put("Authorization", reqParam.get("Authorization"));

        // 请求记录
        Map<String, Object> requestMap = new HashMap<>();
        requestMap.put("Authorization", reqParam.get("Authorization"));
        requestMap.put("req_data", JSONObject.toJSONString(commonParam));

        BsMerLedgerApply merLedgerApply = new BsMerLedgerApply();
        merLedgerApply.setMerLedgerId(merLedger.getId());
        merLedgerApply.setMerId(merLedger.getMerId());
        merLedgerApply.setOrderNo(orderNo);
        merLedgerApply.setRequestBody(JSONObject.toJSONString(requestMap));

        JSONObject responseBody = HttpsUtils.doPost(CommonSysConst.getSysConfig().getLkl_request_url() + "/api/v2/mms/openApi/ledger/applyLedgerMer", commonParam, heard);
        if (!responseBody.getString("retCode").equals("000000")) {
            throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, responseBody.getString("retMsg"));

        }

        merLedger.setStatus(MerLedgerStatusEnum.status2.getNumber());
        merLedgerService.editMerLedger(merLedger);

        System.out.println("body：" + JSONObject.toJSONString(commonParam));
        System.out.println("response：" + responseBody.toJSONString());
        merLedgerApply.setApplyId(responseBody.getJSONObject("respData").getString("applyId"));
        merLedgerApply.setResponseBody(responseBody.toJSONString());
        merLedgerApplyService.editMerLedgerApply(merLedgerApply);
        return responseBody;
    }

    public JSONObject updateLedger(Long merLedgerId) {
        BsMerLedger merLedger = merLedgerService.getMerLedgerById(merLedgerId);
        if (merLedger == null || !merLedger.getPlatformType().equals(PlatformTypeEnum.type1.getNumber())) {
            throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
        }
        // 商户
        BsMer mer = merService.getMer(merLedger.getMerId());
        if (mer == null) {
            throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未找到商户");
        }
        SecDictionary org = commonService.mappingSysCode("ORG_NO", mer.getOrgNo());
        if (org == null) {
            throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未知的机构");
        }

        Map<String, Object> commonParam = new HashMap<>();
        commonParam.put("reqTime", DateUtil.format(new Date(), "yyyyMMddHHmmss"));
        commonParam.put("version", "1.0.0");
        commonParam.put("reqId", UnionUtils.createNonceStr());

        String orderNo = System.currentTimeMillis()+"";
        Map<String, Object> map = new HashMap<>();
        map.put("version", "1.0");
        map.put("orderNo", orderNo);
        map.put("orgCode", org.getExt1());
        map.put("receiverNo", merLedger.getReceiverNo());
        map.put("merCupNo", merLedger.getCupNo());
        map.put("contactMobile", mer.getRegPhone());
        map.put("splitLowestRatio", merLedger.getSplitLowestRatio());
        map.put("splitEntrustFileName", merLedger.getSplitEntrustFileName());
        // 转换成bas64
        String base64ImgUrl = ImageUtils.getBase64ByImgUrl(CommonSysConst.getSysConfig().getObs_url()+merLedger.getSplitEntrustFilePath());
        String fileType = merLedger.getSplitEntrustFilePath().substring(merLedger.getSplitEntrustFilePath().lastIndexOf(".") + 1);
        map.put("splitEntrustFilePath", LaKaLaConfig.uploadFile("COOPERATION_QUALIFICATION_PROOF", fileType, base64ImgUrl).getString("attFileId"));
        map.put("splitRange", "MARK");
        map.put("retUrl", CommonSysConst.getSysConfig().getDomainName() + "/crest/laKaLaNotify/applyLedgerMer");
        commonParam.put("reqData", map);

        Map<String, Object> reqParam = LaKaLaConfig.generateSignParamsV2(JSONObject.parseObject(JSONObject.toJSONString(commonParam)));
        // 头部参数
        Map<String, Object> heard = new HashMap<>();
        heard.put("Authorization", reqParam.get("Authorization"));

        // 请求记录
        Map<String, Object> requestMap = new HashMap<>();
        requestMap.put("Authorization", reqParam.get("Authorization"));
        requestMap.put("req_data", JSONObject.toJSONString(commonParam));

        BsMerLedgerApply merLedgerApply = new BsMerLedgerApply();
        merLedgerApply.setMerLedgerId(merLedger.getId());
        merLedgerApply.setMerId(merLedger.getId());
        merLedgerApply.setOrderNo(orderNo);
        merLedgerApply.setRequestBody(JSONObject.toJSONString(requestMap));

        JSONObject responseBody = HttpsUtils.doPost(CommonSysConst.getSysConfig().getLkl_request_url() + "/api/v2/mms/openApi/ledger/modifyLedgerReceiver", commonParam, heard);
        System.out.println("body：" + JSONObject.toJSONString(commonParam));
        System.out.println("response：" + responseBody.toJSONString());
        if (!responseBody.getString("retCode").equals("000000")) {
            throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, responseBody.getString("retMsg"));
        }
        return responseBody;
    }

    /**
     * 商户分账信息变更申请
     * @param merLedgerId
     * @return
     */
    public JSONObject applyLedgerModify(Long merLedgerId) {
        //
        BsMerLedger merLedger = merLedgerService.getMerLedgerById(merLedgerId);
        if (merLedger == null || merLedger.getPlatformType().equals(PlatformTypeEnum.type1.getNumber())) {
            throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
        }
        // 商户
        BsMer mer = merService.getMer(merLedger.getId());
        if (mer == null) {
            throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未找到商户");
        }
        SecDictionary org = commonService.mappingSysCode("ORG_NO", mer.getOrgNo());
        if (org == null) {
            throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未知的机构");
        }
        Map<String, Object> commonParam = new HashMap<>();
        commonParam.put("reqTime", DateUtil.format(new Date(), "yyyyMMddHHmmss"));
        commonParam.put("version", "1.0.0");
        commonParam.put("reqId", UnionUtils.createNonceStr());

        String orderNo = System.currentTimeMillis()+"";
        Map<String, Object> map = new HashMap<>();
        map.put("version", "1.0");
        map.put("orderNo", orderNo);
        map.put("orgCode", org.getExt1());
        map.put("merCupNo", merLedger.getCupNo());
        map.put("contactMobile", mer.getRegPhone());
        map.put("splitLowestRatio", merLedger.getSplitLowestRatio());
        map.put("splitEntrustFileName", merLedger.getSplitEntrustFileName());
        // map.put("splitEntrustFilePath", saasCommon.fileUpload(new File(CommonSysConst.getSysConfig().getFile_url() +"/"+ merLedger.getSplitEntrustFilePath()), "SPLIT_ENTRUST_FILE", "0").getString("url"));
        map.put("splitRange", "MARK");
        map.put("retUrl", CommonSysConst.getSysConfig() + "/crest/laKaLaNotify/applyLedgerMer");
        commonParam.put("reqData", map);

        Map<String, Object> reqParam = LaKaLaConfig.generateSignParamsV2(JSONObject.parseObject(JSONObject.toJSONString(commonParam)));
        // 头部参数
        Map<String, Object> heard = new HashMap<>();
        heard.put("Authorization", reqParam.get("Authorization"));

        // 请求记录
        Map<String, Object> requestMap = new HashMap<>();
        requestMap.put("Authorization", reqParam.get("Authorization"));
        requestMap.put("req_data", JSONObject.toJSONString(commonParam));

        BsMerLedgerApply merLedgerApply = new BsMerLedgerApply();
        merLedgerApply.setMerLedgerId(merLedger.getId());
        merLedgerApply.setMerId(merLedger.getId());
        merLedgerApply.setOrderNo(orderNo);
        merLedgerApply.setRequestBody(JSONObject.toJSONString(requestMap));
        merLedgerApplyService.editMerLedgerApply(merLedgerApply);

        JSONObject responseBody = HttpsUtils.doPost(CommonSysConst.getSysConfig().getLkl_request_url() + "/api/v2/mms/openApi/ledger/applyLedgerMer", commonParam, heard);
        System.out.println("body：" + JSONObject.toJSONString(commonParam));
        System.out.println("response：" + responseBody.toJSONString());
        merLedgerApply.setApplyId(responseBody.getJSONObject("respData").getString("applyId"));
        merLedgerApply.setResponseBody(responseBody.toJSONString());
        merLedgerApplyService.editMerLedgerApply(merLedgerApply);

        if (!responseBody.getString("retCode").equals("000000")) {
            throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, responseBody.getString("retMsg"));
        }

        return responseBody;
    }

    /**
     * 分账商户信息查询
     * @param merCupNo 银联商户号
     * @return
     */
    public JSONObject queryLedgerMer(String merCupNo) {
        BsMerPlatformNo merPlatform = merPlatformNoService.getPlatformNoByCupNo(merCupNo);
        if (merPlatform == null) {
            throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未知的商户号");
        }
        // 商户
        BsMer mer = merService.getMer(merPlatform.getMerId());
        if (mer == null) {
            throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未找到商户");
        }
        SecDictionary org = commonService.mappingSysCode("ORG_NO", mer.getOrgNo());
        if (org == null) {
            throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未知的机构");
        }
        Map<String, Object> commonParam = new HashMap<>();
        commonParam.put("reqTime", DateUtil.format(new Date(), "yyyyMMddHHmmss"));
        commonParam.put("version", "1.0.0");
        commonParam.put("reqId", UnionUtils.createNonceStr());

        String orderNo = System.currentTimeMillis()+"";
        Map<String, Object> map = new HashMap<>();
        map.put("version", "1.0");
        map.put("orderNo", orderNo);
        map.put("orgCode", org.getExt1());
        map.put("merCupNo", merCupNo);
        commonParam.put("reqData", map);

        Map<String, Object> reqParam = LaKaLaConfig.generateSignParamsV2(JSONObject.parseObject(JSONObject.toJSONString(commonParam)));
        // 头部参数
        Map<String, Object> heard = new HashMap<>();
        heard.put("Authorization", reqParam.get("Authorization"));

        JSONObject responseBody = HttpsUtils.doPost(CommonSysConst.getSysConfig().getLkl_request_url() + "/api/v2/mms/openApi/ledger/queryLedgerMer", commonParam, heard);
        System.out.println("body：" + JSONObject.toJSONString(commonParam));
        System.out.println("response：" + responseBody.toJSONString());

        if (!responseBody.getString("retCode").equals("000000")) {
            throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, responseBody.getString("retMsg"));
        }

        return responseBody;
    }

    /**
     * 创建分账接收方
     */
    public void applyLedgerReceiver(Long merId) {
        // 商户
        MerBasisModel merDetail = merService.getMerDetail(merId);
        if (merDetail == null) {
            throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未找到商户");
        }
        SecDictionary org = commonService.mappingSysCode("ORG_NO", merDetail.getOrgNo());
        if (org == null) {
            throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未知的机构");
        }
        Map<String, Object> commonParam = new HashMap<>();
        commonParam.put("reqTime", DateUtil.format(new Date(), "yyyyMMddHHmmss"));
        commonParam.put("version", "1.0.0");
        commonParam.put("reqId", UnionUtils.createNonceStr());

        Map<String, Object> map = new HashMap<>();
        map.put("version", "1.0");
        map.put("orderNo", System.currentTimeMillis()+"");
        map.put("orgCode", org.getExt1());
        map.put("receiverName", merDetail.getMerName());
        map.put("contactMobile", merDetail.getRegPhone());
        map.put("acctTypeCode", merDetail.getMerSettleAcct().getSettleType().equals(MerSettleType.status1.getNumber())?57:58);// 57：对公 58：对私
        map.put("acctNo", merDetail.getMerSettleAcct().getBankCardNo());
        map.put("acctName", merDetail.getMerSettleAcct().getSettleType().equals(MerSettleType.status1.getNumber())?merDetail.getBlisName():merDetail.getMerSettleAcct().getBankCardHolder());
        map.put("acctCertificateType", "17");
        map.put("acctCertificateNo", merDetail.getMerSettleAcct().getSettleIdCardNo());
        map.put("acctOpenBankCode", merDetail.getMerSettleAcct().getOpenningBankCode());
        map.put("acctOpenBankName", merDetail.getMerSettleAcct().getOpenningBankName());
        map.put("acctClearBankCode", merDetail.getMerSettleAcct().getClearingBankCode());

        if (merDetail.getMerSettleAcct().getSettleType().equals(MerSettleType.status1.getNumber()) == true) {
            map.put("licenseNo", merDetail.getBlisNo());
            map.put("licenseName", merDetail.getBlisName());
            map.put("legalPersonName", merDetail.getLarName());
            map.put("legalPersonCertificateType", "17");
            map.put("legalPersonCertificateNo", merDetail.getLarIdCard());
        }

        List<Map<String, Object>> attachMapList = new ArrayList<>();
        Map<String, Object> attachMap;

        List<BsMerAttach> attachList = merAttachService.getAttachListByMer(merId, PlatformTypeEnum.type0, null);
        for (BsMerAttach attach : attachList) {
            if (StringUtils.isNotBlank(attach.getFileUrl())) {
                MerAttachType attachType = MerAttachType.getDataByNumber(attach.getType());
                if (attachType != null && StringUtils.isNotBlank(attachType.getLklCode())) {
                    attachMap = new HashMap<>();

                    // 转换成bas64
                    String base64ImgUrl = ImageUtils.getBase64ByImgUrl(CommonSysConst.getSysConfig().getObs_url()+"/"+attach.getFileUrl());
                    String fileType = attach.getFileUrl().substring(attach.getFileUrl().lastIndexOf(".") + 1);
                    attachMap.put("attachType", attachType.getLklCode());
                    attachMap.put("attachName", attachType.getName());
                    attachMap.put("attachStorePath", LaKaLaConfig.uploadFile(attachType.getLklSaasCode(), fileType, base64ImgUrl).getString("attFileId"));
                    attachMapList.add(attachMap);
                }
            }
        }
        map.put("attachList", attachMapList);
        commonParam.put("reqData", map);

        Map<String, Object> reqParam = LaKaLaConfig.generateSignParamsV2(JSONObject.parseObject(JSONObject.toJSONString(commonParam)));
        // 头部参数
        Map<String, Object> heard = new HashMap<>();
        heard.put("Authorization", reqParam.get("Authorization"));

        JSONObject responseBody = HttpsUtils.doPost(CommonSysConst.getSysConfig().getLkl_request_url() + "/api/v2/mms/openApi/ledger/applyLedgerReceiver", commonParam, heard);
        System.out.println("body：" + JSONObject.toJSONString(commonParam));
        System.out.println("response：" + responseBody.toJSONString());
        if (!responseBody.getString("retCode").equals("000000")) {
            throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, responseBody.getString("retMsg"));
        }

        // 查询分账信息
        BsMerLedger merLedger = merLedgerService.getMerLedger(merId, PlatformTypeEnum.type1);
        if (merLedger != null) {
            merLedger.setReceiverStatus(true);
            merLedger.setReceiverNo(responseBody.getJSONObject("respData").getString("receiverNo"));
            merLedgerService.editMerLedger(merLedger);
        }
    }

    /**
     * 修改分账接收方
     */
    public void updateLedgerReceiver(Long merId) {
        // 商户
        MerBasisModel merDetail = merService.getMerDetail(merId);
        if (merDetail == null) {
            throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未找到商户");
        }
        SecDictionary org = commonService.mappingSysCode("ORG_NO", merDetail.getOrgNo());
        if (org == null) {
            throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未知的机构");
        }
        Map<String, Object> commonParam = new HashMap<>();
        commonParam.put("reqTime", DateUtil.format(new Date(), "yyyyMMddHHmmss"));
        commonParam.put("version", "1.0.0");
        commonParam.put("reqId", UnionUtils.createNonceStr());

        Map<String, Object> map = new HashMap<>();
        map.put("version", "1.0");
        map.put("orderNo", System.currentTimeMillis()+"");
        map.put("orgCode", org.getExt1());
        map.put("receiverNo", "1");
        map.put("receiverName", merDetail.getMerName());
        map.put("contactMobile", merDetail.getRegPhone());
        map.put("acctNo", merDetail.getMerSettleAcct().getBankCardNo());
        map.put("acctTypeCode", merDetail.getMerSettleAcct().getSettleType().equals(MerSettleType.status1.getNumber())?57:58);// 57：对公 58：对私
        map.put("acctOpenBankCode", merDetail.getMerSettleAcct().getOpenningBankCode());
        map.put("acctOpenBankName", merDetail.getMerSettleAcct().getOpenningBankName());
        map.put("acctClearBankCode", merDetail.getMerSettleAcct().getClearingBankCode());

        List<Map<String, Object>> attachMapList = new ArrayList<>();
        Map<String, Object> attachMap;

        List<BsMerAttach> attachList = merAttachService.getAttachListByMer(merId, PlatformTypeEnum.type0, null);
        for (BsMerAttach attach : attachList) {
            if (StringUtils.isNotBlank(attach.getFileUrl())) {
                MerAttachType attachType = MerAttachType.getDataByNumber(attach.getType());
                if (attachType != null && StringUtils.isNotBlank(attachType.getLklCode())) {
                    attachMap = new HashMap<>();

                    // 转换成bas64
                    String base64ImgUrl = ImageUtils.getBase64ByImgUrl(CommonSysConst.getSysConfig().getObs_url()+"/"+attach.getFileUrl());
                    String fileType = attach.getFileUrl().substring(attach.getFileUrl().lastIndexOf(".") + 1);
                    attachMap.put("attachType", attachType.getLklCode());
                    attachMap.put("attachName", attachType.getName());
                    attachMap.put("attachStorePath", LaKaLaConfig.uploadFile(attachType.getLklSaasCode(), fileType, base64ImgUrl).getString("attFileId"));
                    attachMapList.add(attachMap);
                }
            }
        }
        map.put("attachList", attachMapList);
        commonParam.put("reqData", map);

        Map<String, Object> reqParam = LaKaLaConfig.generateSignParamsV2(JSONObject.parseObject(JSONObject.toJSONString(commonParam)));
        // 头部参数
        Map<String, Object> heard = new HashMap<>();
        heard.put("Authorization", reqParam.get("Authorization"));

        JSONObject responseBody = HttpsUtils.doPost(CommonSysConst.getSysConfig().getLkl_request_url() + "/api/v2/mms/openApi/ledger/modifyLedgerReceiver", commonParam, heard);
        System.out.println("body：" + JSONObject.toJSONString(commonParam));
        System.out.println("response：" + responseBody.toJSONString());
        if (!responseBody.getString("retCode").equals("000000")) {
            throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, responseBody.getString("retMsg"));
        }

        // 查询分账信息
        BsMerLedger merLedger = merLedgerService.getMerLedger(merId, PlatformTypeEnum.type1);
        if (merLedger != null) {
            merLedger.setReceiverNo(responseBody.getJSONObject("respData").getString("receiverNo"));
            merLedgerService.editMerLedger(merLedger);
        }
    }

    /**
     * 绑定分账关系
     */
    public void applyBind(BsMerLedgerReceiver merLedgerReceiver) {
        // 查询
        if (merLedgerReceiver == null) {
            throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未找到分账关系");
        }
        // 商户
        BsMer mer = merService.getMer(merLedgerReceiver.getMerId());
        if (mer == null) {
            throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未找到商户");
        }
        SecDictionary org = commonService.mappingSysCode("ORG_NO", mer.getOrgNo());
        if (org == null) {
            throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未知的机构");
        }
        Map<String, Object> commonParam = new HashMap<>();
        commonParam.put("reqTime", DateUtil.format(new Date(), "yyyyMMddHHmmss"));
        commonParam.put("version", "1.0.0");
        commonParam.put("reqId", UnionUtils.createNonceStr());

        Map<String, Object> map = new HashMap<>();
        map.put("version", "1.0");
        map.put("orderNo", System.currentTimeMillis()+"");
        map.put("orgCode", org.getExt1());
        map.put("merCupNo", merLedgerReceiver.getCupNo());
        map.put("receiverNo", merLedgerReceiver.getReceiverNo());

        String base64ImgUrl = ImageUtils.getBase64ByImgUrl(CommonSysConst.getSysConfig().getObs_url()+merLedgerReceiver.getEntrustFilePath());
        String fileType = merLedgerReceiver.getEntrustFilePath().substring(merLedgerReceiver.getEntrustFilePath().lastIndexOf(".") + 1);
        map.put("entrustFileName", merLedgerReceiver.getEntrustFileName());
        map.put("entrustFilePath", LaKaLaConfig.uploadFile("COOPERATION_QUALIFICATION_PROOF", fileType, base64ImgUrl).getString("attFileId"));
        map.put("retUrl", CommonSysConst.getSysConfig().getDomainName()+"/crest/laKaLaNotify/applyBindReceiver");
        commonParam.put("reqData", map);

        Map<String, Object> reqParam = LaKaLaConfig.generateSignParamsV2(JSONObject.parseObject(JSONObject.toJSONString(commonParam)));
        // 头部参数
        Map<String, Object> heard = new HashMap<>();
        heard.put("Authorization", reqParam.get("Authorization"));

        JSONObject responseBody = HttpsUtils.doPost(CommonSysConst.getSysConfig().getLkl_request_url() + "/api/v2/mms/openApi/ledger/applyBind", commonParam, heard);
        System.out.println("body：" + JSONObject.toJSONString(commonParam));
        System.out.println("response：" + responseBody.toJSONString());
        if (!responseBody.getString("retCode").equals("000000")) {
            throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, responseBody.getString("retMsg"));
        }
        merLedgerReceiver.setStatus(MerLedgerReceiverStatusEnum.status2.getNumber());
        merLedgerReceiver.setAuditStatus(MerLedgerReceiverAuditStatusEnum.status1.getNumber());
        merLedgerReceiverService.editMerLedgerReceiver(merLedgerReceiver);

        BsMerLedgerReceiverApply ledgerReceiverApply = new BsMerLedgerReceiverApply();
        ledgerReceiverApply.setMerId(merLedgerReceiver.getMerId());
        ledgerReceiverApply.setMerLedgerId(merLedgerReceiver.getMerLedgerId());
        ledgerReceiverApply.setMerLedgerReceiverId(merLedgerReceiver.getId());
        ledgerReceiverApply.setReceiverNo(merLedgerReceiver.getReceiverNo());
        ledgerReceiverApply.setOrderNo(MapUtils.getString(map,"orderNo"));
        ledgerReceiverApply.setApplyId(responseBody.getJSONObject("respData").getString("applyId"));
        ledgerReceiverApply.setRequestBody(JSONObject.toJSONString(commonParam));
        ledgerReceiverApply.setResponseBody(responseBody.toJSONString());
        ledgerReceiverApply.setStatus(MerLedgerReceiverApplyStatusEnum.status1.getNumber());
        merLedgerReceiverApplyService.editReceiverApply(ledgerReceiverApply);
    }

    /**
     * 分账关系解绑申请
     */
    public void applyUnBind(Long merId,String receiverNo) {
        // 查询
        BsMerLedgerReceiver merLedgerReceiver = merLedgerReceiverService.getMerLedgerReceiver(merId, receiverNo);
        if (merLedgerReceiver == null) {
            throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未找到分账关系");
        }
        // 商户
        BsMer mer = merService.getMer(merLedgerReceiver.getMerId());
        if (mer == null) {
            throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未找到商户");
        }
        SecDictionary org = commonService.mappingSysCode("ORG_NO", mer.getOrgNo());
        if (org == null) {
            throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未知的机构");
        }
        Map<String, Object> commonParam = new HashMap<>();
        commonParam.put("reqTime", DateUtil.format(new Date(), "yyyyMMddHHmmss"));
        commonParam.put("version", "1.0.0");
        commonParam.put("reqId", UnionUtils.createNonceStr());

        Map<String, Object> map = new HashMap<>();
        map.put("version", "1.0");
        map.put("orderNo", System.currentTimeMillis()+"");
        map.put("orgCode", org.getExt1());
        map.put("merCupNo", merLedgerReceiver.getCupNo());
        map.put("receiverNo", merLedgerReceiver.getReceiverNo());
        String base64ImgUrl = ImageUtils.getBase64ByImgUrl(CommonSysConst.getSysConfig().getObs_url() + merLedgerReceiver.getRelieveEntrustFilePath());
        String fileType = merLedgerReceiver.getRelieveEntrustFilePath().substring(merLedgerReceiver.getRelieveEntrustFilePath().lastIndexOf(".") + 1);
        map.put("entrustFileName", merLedgerReceiver.getRelieveEntrustFileName());
        map.put("entrustFilePath", LaKaLaConfig.uploadFile("COOPERATION_QUALIFICATION_PROOF", fileType, base64ImgUrl).getString("attFileId"));
        map.put("retUrl", CommonSysConst.getSysConfig().getDomainName()+"/crest/laKaLaNotify/applyBindUnReceiver");
        commonParam.put("reqData", map);

        Map<String, Object> reqParam = LaKaLaConfig.generateSignParamsV2(JSONObject.parseObject(JSONObject.toJSONString(commonParam)));
        // 头部参数
        Map<String, Object> heard = new HashMap<>();
        heard.put("Authorization", reqParam.get("Authorization"));

        JSONObject responseBody = HttpsUtils.doPost(CommonSysConst.getSysConfig().getLkl_request_url() + "/api/v2/mms/openApi/ledger/applyUnBind", commonParam, heard);
        System.out.println("body：" + JSONObject.toJSONString(commonParam));
        System.out.println("response：" + responseBody.toJSONString());
        if (!responseBody.getString("retCode").equals("000000")) {
            throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, responseBody.getString("retMsg"));
        }
        merLedgerReceiver.setAuditStatus(MerLedgerReceiverAuditStatusEnum.status4.getNumber());
        merLedgerReceiverService.editMerLedgerReceiver(merLedgerReceiver);

        BsMerLedgerReceiverApply ledgerReceiverApply = new BsMerLedgerReceiverApply();
        ledgerReceiverApply.setMerId(merLedgerReceiver.getMerId());
        ledgerReceiverApply.setMerLedgerId(merLedgerReceiver.getMerLedgerId());
        ledgerReceiverApply.setMerLedgerReceiverId(merLedgerReceiver.getId());
        ledgerReceiverApply.setReceiverNo(merLedgerReceiver.getReceiverNo());
        ledgerReceiverApply.setOrderNo(MapUtils.getString(map,"orderNo"));
        ledgerReceiverApply.setApplyId(responseBody.getJSONObject("respData").getString("applyId"));
        ledgerReceiverApply.setRequestBody(JSONObject.toJSONString(commonParam));
        ledgerReceiverApply.setResponseBody(responseBody.toJSONString());
        ledgerReceiverApply.setStatus(MerLedgerReceiverApplyStatusEnum.status1.getNumber());
        merLedgerReceiverApplyService.editReceiverApply(ledgerReceiverApply);
    }

}
