package cn.pluss.platform.klk.service.impl;

import cn.hutool.core.io.resource.UrlResource;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONUtil;
import cn.pluss.platform.BankCardService;
import cn.pluss.platform.IdCardService;
import cn.pluss.platform.MerchantAuditRecordService;
import cn.pluss.platform.channel.ys.impl.YSAuditServiceV3;
import cn.pluss.platform.dto.AccountDTO;
import cn.pluss.platform.entity.*;
import cn.pluss.platform.exception.MsgException;
import cn.pluss.platform.klk.LaKaLaUtility;
import cn.pluss.platform.klk.LakalaConfig;
import cn.pluss.platform.klk.service.*;
import cn.pluss.platform.klk.util.HtmlUtil;
import cn.pluss.platform.klk.util.RSAUtil;
import cn.pluss.platform.klk.vo.*;

import cn.pluss.platform.mapper.MerchantBackLklMapper;
import cn.pluss.platform.mapper.MerchantChannelFeeMapper;
import cn.pluss.platform.mapper.MerchantChannelStatusMapper;
import cn.pluss.platform.mapper.MerchantImageMapper;
import cn.pluss.platform.mcc.MccReflectService;
import cn.pluss.platform.merchant.AccountService;
import cn.pluss.platform.merchant.MerchantBaseInfoService;
import cn.pluss.platform.merchantChannelStatus.MerchantChannelStatusService;
import cn.pluss.platform.userApp.UserAppService;
import cn.pluss.platform.util.DateUtils;
import cn.pluss.platform.util.StringUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import freemarker.template.TemplateException;
import lombok.Data;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.codec.binary.Base64;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.http.*;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.util.ObjectUtils;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.*;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

@Service
@Slf4j
public class LaKalaInterfaceImpl {
    @Resource
    LklPayService lklPayService;
    @Resource
    TbLklRegionBankInfoServiceImpl tbLklRegionBankInfoServiceImpl;
    @Resource
    TbPlussBankBranchLklService tbPlussBankBranchLklService;

    @Resource
    UserAppService uaService;
    @Resource
    private MerchantBaseInfoService mbiService;
    @Resource
    BankCardService bankCardService;
    @Resource
    private TbPlussRegionLklService tbPlussRegionLklService;

    @Resource
    private IdCardService idCardService;
    @Resource
    private TbPlussBankRegionLklService regionLklService;

    @Resource
    AccountService accountService;


    @Autowired
    protected MerchantAuditRecordService merchAuditRecService;

    @Resource
    private MerchantChannelStatusMapper merchantChannelStatusMapper;

    @Lazy
    @Resource
    private MerchantChannelStatusService mcsService;
    @Resource
    MerchantBaseInfoService baseInfoService;

    @Resource
    TbPlussBusinessSmallLklService businessSmallLklService;
    @Resource
    MccReflectService service;
    @Resource
    PlussMerchantLklService merchantLklService;

    @Lazy
    @Autowired
    LakalaConfig lakalaConfig;


    @Lazy
    @Autowired
    MerchantImageMapper merchantImageMapper;
    @Autowired
    MerchantBackLklService merchantBackLklService;
    private static final String client_id = "chaozhanggui";
    private static final String client_secret = "Y54Gqy6aLpxld3dp";
    private static final String grant_type = "client_credentials";
    public static final String userNo = "22265868";
    /**
     * 商户进件
     */
    private static final String tuoKeMerchat = "https://htkactvi.lakala.com/registration/merchant";
    /**
     * 获取地区信息
     */
    private static final String organparentCode = "https://htkactvi.lakala.com/registration/organization/";
    /**
     * 获取银行地区信息
     */
    private static final String organizationBank = "https://htkactvi.lakala.com/registration/organization/bank/";
    /**
     * 文件上传
     */
    private static final String fileUpload = "https://htkactvi.lakala.com/registration/file/upload";
    private static final String tuoKeToken = "https://tkapi.lakala.com/auth/oauth/token";

    /************************************************测试信息***************************************************/
//    private static final String client_id = "testsit";
//    private static final String client_secret = "EguwEckByf2I6u6z";
//    private static final String grant_type = "client_credentials";
//    private static final String userNo = "20000101";
//    /**
//     * 商户进件
//     */
//    private static final String tuoKeMerchat = "https://test.wsmsd.cn/sit/htkregistration/merchant";
//    /**
//     * 获取地区信息
//     */
//    private static final String organparentCode = "https://test.wsmsd.cn/sit/htkregistration/organization/";
//    /**
//     * 获取银行地区信息
//     */
//    private static final String organizationBank = "https://test.wsmsd.cn/sit/htkregistration/organization/bank/";
//    /**
//     * 文件上传
//     */
//    private static final String fileUpload = "https://test.wsmsd.cn/sit//htkregistration/file/upload";
//
//
//    private static final String tuoKeToken = "https://test.wsmsd.cn/sit/htkauth/oauth/token";


    /**
     * 拉卡拉模式进件
     */

    /**
     * 拉卡拉拓客进件
     */
    public void createTuoKeInfo(String userId) {

//      UserApp  userapp=userAppService.getById(userId);
//      MsgException.checkNull(userapp,"商户基础信息不完整");
//
//      MsgException.checkBlank(userapp.getEmail(),"商户邮箱不允许为空");

        MerchantBaseInfo merchantBaseInfo = mbiService.getMerchantBaseInfoByUserId(userId);

        IdCard idCard = idCardService.getCertIdCard(userId);  //获取法人身份证信息
        MsgException.checkNull(idCard, "商户基本信息不完整");

        MerchantChannelStatus mcs = mcsService.getByMerchantCodeNoChannel(merchantBaseInfo.getMerchantCode());

        if (ObjectUtil.isEmpty(mcs)) {
            log.info("审核失败，重新审核数据:{}", merchantBaseInfo.getMerchantCode());
            QueryWrapper<MerchantChannelStatus> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("merchantCode", merchantBaseInfo.getMerchantCode());
            queryWrapper.eq("channel", "5");
            List<String> list = new ArrayList<>();
            list.add("1");
            list.add("2");
            queryWrapper.in("status", list);
            mcs = merchantChannelStatusMapper.selectOne(queryWrapper);
        }
        String status = mcs.getStatus();
        String thirdStatus = mcs.getThirdStatus();
        MsgException.checkNull(mcs, "商户未提交审核");
        if (status.equals(MerchantChannelStatus.AUDIT_STATUS_EXAMINING) && !thirdStatus.equals(MerchantChannelStatus.AUDIT_THIRD_STATUS_WAITING)) {
            MsgException.throwException("进件审核中，请等待审核结果");
        }

        if (MerchantChannelStatus.isAudited(mcs)) {
            MsgException.throwException("商户已进件成功，请勿重复进件");
        }


        JSONObject object1 = new JSONObject();
        JSONObject object2 = new JSONObject();
        object1.put("userNo", userNo); //合作机构信息 由拓客SAAS提供
        object1.put("email", "chaozhanggui2023@163.com"); //商户邮箱
        object1.put("busiCode", "WECHAT_PAY");//业务类型 BPOS:传统POS, ZPOS:电签,ZPOS4G：4G电签,SUPER_POS:智能pos,B_WIZARD:蓝精灵,PAPER_CODE:码牌,WECHAT_PAY:专业化扫码,KLYX:云音箱,QRCODE:收款王,MONEY_BOX:收钱宝盒根据业务开放取值
        object1.put("merRegName", merchantBaseInfo.getAlias()); //商户注册名称 不能少于七个中文
        object1.put("merType", (merchantBaseInfo.getMerchantType().equals(1) || merchantBaseInfo.getMerchantType().equals("2")) ? "TP_PERSONAL" : "TP_MERCHANT");  //商户注册类型 TP_MERCHANT:企业 TP_PERSONAL:⼩微个⼈
        object1.put("merName", merchantBaseInfo.getAlias()); //商户名称(经营名称)  不能少于七个中文
        object1.put("merAddr", merchantBaseInfo.getAddress()); //去掉省，市区后的详细地址
        object1.put("provinceCode", tbPlussRegionLklService.getOne(new QueryWrapper<TbPlussRegionLklEntity>().likeRight("name", merchantBaseInfo.getProvince()).last("limit 1")).getCode()); //省代码 通过【地区信息→获取地区查询】接口获取 对应 code字段
        object1.put("cityCode", tbPlussRegionLklService.getOne(new QueryWrapper<TbPlussRegionLklEntity>().likeRight("name", merchantBaseInfo.getCity()).last("limit 1")).getCode()); // 市代码 通过【地区信息→获取地区查询】接口获取 对应 code字段
        object1.put("countyCode", tbPlussRegionLklService.getOne(new QueryWrapper<TbPlussRegionLklEntity>().likeRight("name", merchantBaseInfo.getDistrict()).last("limit 1")).getCode()); // 区县代码 通过【地区信息→获取地区查询】接口获取 对应 code字段
        Set<Object> attchmentsVoSet = new HashSet<>();
        QueryWrapper<Account> accountQueryWrapper1 = new QueryWrapper<>();
        accountQueryWrapper1.eq("userId", userId);
        accountQueryWrapper1.eq("channelType", "D1");
        Account accountServiceOne1 = accountService.getOne(accountQueryWrapper1);
        MsgException.checkNull(accountServiceOne1, "结算信息未提交");


        QueryWrapper<BankCard> bankCardWrapper = new QueryWrapper<>();
        bankCardWrapper.eq("id", accountServiceOne1.getBankCardId());
        BankCard userBrakCard = bankCardService.getOne(bankCardWrapper);

        MsgException.checkNull(userBrakCard, "结算卡信息未提交");


        QueryWrapper<MccReflect> userAppQueryWrapper = new QueryWrapper();
        userAppQueryWrapper.eq("standard_mcc_code", merchantBaseInfo.getMcc()).eq("channel_id", "5").last("limit 1");
        MccReflect mccReflect = service.getOne(userAppQueryWrapper);


        if (merchantBaseInfo.getMerchantType().equals("3")) {
            object1.put("merRegName", merchantBaseInfo.getMerchantName());
            object1.put("merName", merchantBaseInfo.getMerchantName());
            object1.put("licenseName", merchantBaseInfo.getBussAuthName()); //营业执照名称
            object1.put("licenseNo", merchantBaseInfo.getBussAuthNum()); //营业执照号码 ⼩微商户可不传， 其他必传
            StringBuffer startSb = new StringBuffer();
            StringBuffer endSb = new StringBuffer();

            if (merchantBaseInfo.getBussAuthStartTime().contains("年")) {
                startSb.append(merchantBaseInfo.getBussAuthStartTime().substring(0, 4));
                startSb.append("-");
                startSb.append(merchantBaseInfo.getBussAuthStartTime().substring(5, 7));
                startSb.append("-");
                startSb.append(merchantBaseInfo.getBussAuthStartTime().substring(8, 10));
            } else {
                startSb.append(merchantBaseInfo.getBussAuthStartTime());
            }

            if (ObjectUtil.isEmpty(merchantBaseInfo.getBussAuthEndTime()) || "长期".equals(merchantBaseInfo.getBuslicType())) {
                endSb.append("2099-12-31");
            } else {
                if (merchantBaseInfo.getBussAuthEndTime().contains("年")) {
                    endSb.append(merchantBaseInfo.getBussAuthEndTime().substring(0, 4));
                    endSb.append("-");
                    endSb.append(merchantBaseInfo.getBussAuthEndTime().substring(5, 7));
                    endSb.append("-");
                    endSb.append(merchantBaseInfo.getBussAuthEndTime().substring(8, 10));
                } else {
                    endSb.append(merchantBaseInfo.getBussAuthEndTime());
                }

            }


            object1.put("licenseDtStart", startSb); //营业执照开始时间⼩微商户可不传， 其他必传，格式yyyy-MM-dd
            object1.put("licenseDtEnd", endSb); //⼩微商户可不传， 其他必传，格式yyyy-MM-dd

            QueryWrapper<MerchantImage> imageQueryWrapper = new QueryWrapper<>();
            imageQueryWrapper.eq("merchantCode", merchantBaseInfo.getMerchantCode());
            imageQueryWrapper.eq("photoType", "03");
            MerchantImage image = merchantImageMapper.selectOne(imageQueryWrapper);
            MsgException.checkNull(image, "营业执照不存在");
            //营业执照
            AttchmentsVo business_licence = new AttchmentsVo(); //图片set

            business_licence.setId(laKaLaFileUpload(image.getPicUrl(), "BUSINESS_LICENCE"));//营业执照
            business_licence.setType("BUSINESS_LICENCE");//营业执照
            attchmentsVoSet.add(business_licence);


            //开户许可证
            AttchmentsVo opening_permit = new AttchmentsVo(); //图片set

            opening_permit.setId(laKaLaFileUpload(userBrakCard.getLicenseUrl(), "OPENING_PERMIT"));//开户许可证
            opening_permit.setType("OPENING_PERMIT");//开户许可证
            attchmentsVoSet.add(opening_permit);


            Map<String, Object> data = new HashMap<>();
            data.put("customerName", merchantBaseInfo.getMerchantName());
            data.put("licenseNo", merchantBaseInfo.getBussAuthNum());
            data.put("legalName", idCard.getCertName());
            data.put("licenseName", merchantBaseInfo.getMerchantName());
            data.put("identityNo", idCard.getCertNo());
            data.put("address", merchantBaseInfo.getProvince().concat(merchantBaseInfo.getCity()).concat(merchantBaseInfo.getDistrict()));
            data.put("receiveDetail", merchantBaseInfo.getProvince().concat(merchantBaseInfo.getCity()).concat(merchantBaseInfo.getDistrict()).concat(merchantBaseInfo.getAddress()));
            data.put("identityNoExpire", endSb);
            data.put("accountName", userBrakCard.getBankHolder());
            data.put("accountIdCard", idCard.getCertNo());
            data.put("accountNo", userBrakCard.getBankCardNo());

            data.put("accountIdDtEnd", idCard.getCertEndTime().equals("长期") ? "2099-12-31" : DateUtils.convertString(idCard.getCertEndTime()));
            data.put("bankName", userBrakCard.getBankName());
            data.put("mail", "chaozhanggui2023@163.com");
            data.put("contactManName", userBrakCard.getPhone());
            data.put("channelType", ObjectUtils.isEmpty(mccReflect) ? "7399" : mccReflect.getMccCode());
            data.put("phone", userBrakCard.getPhone());
            data.put("agencyName", merchantBaseInfo.getMerchantName());

//            //协议
            AttchmentsVo agree_ment = new AttchmentsVo(); //图片set
            try {
                agree_ment.setId(laKaLaFileUpload(HtmlUtil.createAgreementPicture(HtmlUtil.writeHtml(data)),"AGREE_MENT"));//协议
                agree_ment.setType("AGREE_MENT");//协议
                attchmentsVoSet.add(agree_ment);
            } catch (IOException e) {
                throw new RuntimeException(e);
            } catch (TemplateException e) {
                throw new RuntimeException(e);
            }


        }

        object1.put("latitude", "108.94647"); //经度 进件所在地址经度error
        object1.put("longtude", "34.34727"); //纬度 进件所在地址纬度 error
        object1.put("source", "APP");  //进件来源 APP: app H5: h5
        object1.put("businessContent", merchantBaseInfo.getMccName()); //商户经营内容
        object1.put("larName", idCard.getCertName()); //法⼈姓名
        object1.put("larIdType", "01"); //法⼈证件类型 01 身份证 暂时只支持身份证
        object1.put("larIdCard", idCard.getCertNo()); //法⼈证件号码
        object1.put("larIdCardStart", birthdayDate(idCard.getCertStartTime())); //法⼈证件开始⽇期 格式yyyy-MM-dd
        object1.put("larIdCardEnd", birthdayDate(idCard.getCertEndTime())); //法⼈证件过期时间 格式yyyy-MM-dd

        object1.put("contactMobile", merchantBaseInfo.getContactMobile()); //商户联系⼈⼿机号码
        object1.put("contactName", merchantBaseInfo.getContactName()); //商户联系⼈姓名


        QueryWrapper<TbPlussBankBranchLklEntity> lklEntityQueryWrapper = new QueryWrapper<>();
        lklEntityQueryWrapper.eq("branch_bank_no", userBrakCard.getContactLine());
        TbPlussBankBranchLklEntity lakalaBranchInfo = tbPlussBankBranchLklService.getOne(lklEntityQueryWrapper);
        MsgException.checkNull(lakalaBranchInfo, "结算卡对应的分行支行信息不存在");

        object1.put("openningBankCode", lakalaBranchInfo.getBranchBankNo()); //结算账户开户⾏号 通过【银行列表查询】接口获取 对应 branchBankNo字段
        object1.put("openningBankName", lakalaBranchInfo.getBranchBankName()); //结算账户开户⾏名称 通过【银行列表查询】接口获取 对应 branchBankName字段
        object1.put("clearingBankCode", lakalaBranchInfo.getClearNo()); //结算账户清算⾏号 通过【银行列表查询】接口获取 对应 clearNo字段


        QueryWrapper<TbPlussBankRegionLklEntity> regionLklEntityQueryWrapper = new QueryWrapper<>();
        regionLklEntityQueryWrapper.eq("code", lakalaBranchInfo.getAreaCode());
        TbPlussBankRegionLklEntity bankParentCode = regionLklService.getOne(regionLklEntityQueryWrapper); //市code 和 name
        MsgException.checkNull(bankParentCode, "结算卡对应的省份信息不存在");
        regionLklEntityQueryWrapper.clear();
        regionLklEntityQueryWrapper.eq("code", bankParentCode.getParentCode());
        TbPlussBankRegionLklEntity parentCode = regionLklService.getOne(regionLklEntityQueryWrapper); //省code 和 名称
        MsgException.checkNull(bankParentCode, "结算卡对应的城市信息不存在");

        object1.put("settleProvinceCode", parentCode.getCode()); //结算信息省份名称 通过【地区信息→获取银行地区查询】接口获取 对应 code字段
        object1.put("settleProvinceName", parentCode.getName()); //结算信息省份代码 通过【地区信息→获取银行地区查询】接口获取 对应 name字段
        object1.put("settleCityCode", bankParentCode.getCode()); //结算信息城市名称 通过【地区信息→获取银行地区查询】接口获取 对应 code字段
        object1.put("settleCityName", bankParentCode.getName()); //结算信息城市代码 通过【地区信息→获取银行地区查询】接口获取 对应 name字段

        AccountDTO accountV4 = getAccountV4(userId, "D1");  //结算人
        MsgException.checkNull(accountV4, "结算信息不存在");

        if("02".equals(accountV4.getSettleType())){
            AttchmentsVo opening_permit = new AttchmentsVo(); //图片set
            opening_permit.setId(laKaLaFileUpload(accountV4.getCertificateUrl(), "LETTER_OF_AUTHORIZATION"));//对私非法人授权函
            opening_permit.setType("LETTER_OF_AUTHORIZATION");//对私非法人授权函
            attchmentsVoSet.add(opening_permit);
        }

        object1.put("accountNo", accountV4.getBankCard().getBankCardNo()); //结算人银行卡号
        object1.put("accountName", accountV4.getBankCard().getBankHolder()); //结算人账户名称
        object1.put("accountType", accountV4.getBankCard().getAccountType().equals("01") ? "58" : "57"); //结算账户类型 57 对公 58 对私
//        object1.put("accountIdType",tuoKeVo.getUserNo()); //结算⼈证件类型 为空同法⼈
        object1.put("accountIdCard", accountV4.getIdcard().getCertNo()); //结算⼈证件号码

        if (accountV4.getBankCard().getAccountType().equals("2")) {
            QueryWrapper<MerchantImage> imageQueryWrapper = new QueryWrapper<>();
            imageQueryWrapper.eq("merchantCode", merchantBaseInfo.getMerchantCode());
            imageQueryWrapper.eq("photoType", "08");
            MerchantImage image = merchantImageMapper.selectOne(imageQueryWrapper);
            MsgException.checkNull(image, "收银台照片不存在");

            //对公收银台照片
            AttchmentsVo checkstand_img = new AttchmentsVo();
            checkstand_img.setId(laKaLaFileUpload(accountV4.getIdcard().getImgNegative(), "CHECKSTAND_IMG")); //收银台照片
            checkstand_img.setType("CHECKSTAND_IMG");//收银台照片
            attchmentsVoSet.add(checkstand_img);


            imageQueryWrapper.clear();
            imageQueryWrapper.eq("merchantCode", merchantBaseInfo.getMerchantCode());
            imageQueryWrapper.eq("photoType", "06");
            image = merchantImageMapper.selectOne(imageQueryWrapper);
            MsgException.checkNull(image, "门头照片不存在");
            //门头照片
            AttchmentsVo shop_outside_img = new AttchmentsVo();

            shop_outside_img.setId(laKaLaFileUpload(image.getPicUrl(), "SHOP_OUTSIDE_IMG"));//门头照片
            shop_outside_img.setType("SHOP_OUTSIDE_IMG");
            attchmentsVoSet.add(shop_outside_img);

            imageQueryWrapper.clear();
            imageQueryWrapper.eq("merchantCode", merchantBaseInfo.getMerchantCode());
            imageQueryWrapper.eq("photoType", "09");
            image = merchantImageMapper.selectOne(imageQueryWrapper);
            MsgException.checkNull(image, "商铺内部照片不存在");
            //商铺内部照片
            AttchmentsVo shop_inside_img = new AttchmentsVo();

            shop_inside_img.setId(laKaLaFileUpload(image.getPicUrl(), "SHOP_INSIDE_IMG"));//商铺内部照片
            shop_inside_img.setType("SHOP_INSIDE_IMG");
            attchmentsVoSet.add(shop_inside_img);
        }


        JSONArray array = new JSONArray();

        Set<FeesSetVo> feesSet = new HashSet<>();
        FeesSetVo w = new FeesSetVo();
        w.setFeeCode("WECHAT");
        w.setFeeValue(0.38d);
        array.add(w);

        FeesSetVo a = new FeesSetVo();
        a.setFeeCode("ALIPAY");
        a.setFeeValue(0.38d);
        array.add(a);

        FeesSetVo u = new FeesSetVo();
        u.setFeeCode("SCAN_PAY_SECOND");
        u.setFeeValue(0.38d);
        array.add(u);
        feesSet.add(w);
        feesSet.add(a);
        feesSet.add(u);

        object2.put("termNum", "1"); //终端数量 1-5 最⼤ 5个终端
        object2.put("fees", feesSet); //费率集合

//        object2.put("mcc","12007");
        object2.put("mcc", ObjectUtils.isEmpty(mccReflect) ? "7399" : mccReflect.getMccCode());  //商户MCC编号 通过 【商户类别查询→查询小类】接口获取 对应 code字段
        object2.put("activityId", "13"); //归属活动信息 由拓客SAAS分配 云音响 14 专业化扫码 13 B2B收银台 25 码牌 12 智能pos 10 智能posPro 21
        object1.put("bizContent", object2); //业务扩展信息 参⻅ 业务扩展信息


        AttchmentsVo frontLegalPerson = new AttchmentsVo(); //图片set
        frontLegalPerson.setId(laKaLaFileUpload(accountV4.getIdcard().getImgPositive(), "ID_CARD_FRONT"));//法人身份证图片地址
        frontLegalPerson.setType("ID_CARD_FRONT");//身份证正⾯
        attchmentsVoSet.add(frontLegalPerson);

        AttchmentsVo reverseLegalPerson = new AttchmentsVo();
        reverseLegalPerson.setId(laKaLaFileUpload(accountV4.getIdcard().getImgNegative(), "ID_CARD_BEHIND")); //法人身份证图片地址
        reverseLegalPerson.setType("ID_CARD_BEHIND");//身份证反⾯
        attchmentsVoSet.add(reverseLegalPerson);


        object1.put("attchments", attchmentsVoSet); //附件信息集合 参⻅ 附件信息
        object1.put("settleType", "D1"); //结算类型 D0秒到 D1次日结算

        System.out.println("请求报文: " + object1);
        /**获取拓客accessToken**/
        Map map = getToken();
        String result = "";
        try {
            result = cn.hutool.http.HttpRequest.post(tuoKeMerchat)
                    .header("Authorization", "bearer " + map.get("access_token")).header("content-type", "application/json")
                    .body(object1.toString()).execute().body();
            System.out.println("返回结果:" + result);
            Map arry = (Map) JSONArray.parse(result);
            if (String.valueOf(arry.get("status")).equals("WAIT_AUDI")) {
                log.info("进件成功，等待三方审核");

                PlussMerchantLklEntity plussMerchantLklEntity = new PlussMerchantLklEntity();
                plussMerchantLklEntity.setMerchantId(merchantBaseInfo.getMerchantCode());
                plussMerchantLklEntity.setMerchantlkl(String.valueOf(arry.get("merchantNo")));
                plussMerchantLklEntity.setType("0");
                merchantLklService.save(plussMerchantLklEntity);


                QueryWrapper<MerchantChannelFee> feeQueryWrapper = new QueryWrapper<>();
                feeQueryWrapper.eq("channel", "5");
                feeQueryWrapper.eq("merchant_code", mcs.getMerchantCode());
                MerchantChannelFee merchantChannelFee = merchantChannelFeeMapper.selectOne(feeQueryWrapper);
                if (ObjectUtil.isEmpty(merchantChannelFee)) {
                    merchantChannelFee = new MerchantChannelFee();
                    merchantChannelFee.setChannel(5);
                    merchantChannelFee.setMerchantCode(merchantBaseInfo.getMerchantCode());
                    JSONObject object=new JSONObject();
                    object.put("D0",array);
                    object.put("D1",array);

                    merchantChannelFee.setFeeStr(new JSONObject(object).toJSONString());
                    merchantChannelFee.setCreateTime(new Date());
                    merchantChannelFeeMapper.insert(merchantChannelFee);
                }


                mcs.setChannel(5);
                mcs.setUpdateTime(new Date());
                mcs.setMerchantCode(merchantBaseInfo.getMerchantCode());
                mcs.setStatus("1");
                mcs.setThirdStatus("");
                mcs.setCallbackStatus("0");
                mcs.setRemark("拉卡拉审核中");
                mcs.setMerchantId(String.valueOf(arry.get("merchantNo")));

                MerchantAuditRecord merchantAuditRecord = new MerchantAuditRecord();
                merchantAuditRecord.setStatus("1");
                merchantAuditRecord.setMerchantCode(merchantBaseInfo.getMerchantCode());
                merchantAuditRecord.setChannel(5);
                merchantAuditRecord.setThirdStatus("");
                merchantAuditRecord.setMerchantId(String.valueOf(arry.get("merchantNo")));
                merchAuditRecService.save(merchantAuditRecord);

                if (StringUtil.isNotEmpty(mcs.getId())) {
                    merchantChannelStatusMapper.updateById(mcs);
                } else {
                    // 保存进件信息
                    merchantChannelStatusMapper.insert(mcs);
                }

            } else {


                JSONObject object = JSONObject.parseObject(result);
                log.error("进件失败{}",object.getString("message"));
                mcs.setChannel(5);
                mcs.setUpdateTime(new Date());
                mcs.setMerchantCode(merchantBaseInfo.getMerchantCode());
                mcs.setStatus("1");
                mcs.setThirdStatus("-100");
                mcs.setCallbackStatus("0");
                mcs.setRemark(object.getString("message"));
                mcs.setMerchantId(object.getString("customerNo"));

                MerchantAuditRecord merchantAuditRecord = new MerchantAuditRecord();
                merchantAuditRecord.setStatus("1");
                merchantAuditRecord.setMerchantCode(merchantBaseInfo.getMerchantCode());
                merchantAuditRecord.setChannel(5);
                merchantAuditRecord.setThirdStatus("");
                merchantAuditRecord.setMerchantId(object.getString("customerNo"));
                merchAuditRecService.save(merchantAuditRecord);

                if (StringUtil.isNotEmpty(mcs.getId())) {
                    merchantChannelStatusMapper.updateById(mcs);
                } else {
                    // 保存进件信息
                    merchantChannelStatusMapper.insert(mcs);
                }

                MsgException.throwException(object.getString("message"));
            }
        } catch (Exception e) {
            e.printStackTrace();
            Map arry = (Map) JSONArray.parse(result);
            new MsgException(String.valueOf(arry.get("message")));
        }
    }


    public void merchantAudit(String userId,Account account,BankCard bankCard,IdCard accountIdCard) {


        MerchantBaseInfo merchantBaseInfo = mbiService.getMerchantBaseInfoByUserId(userId);
        MsgException.checkNull(merchantBaseInfo, "商户进件信息不存在");

        QueryWrapper<MerchantChannelStatus> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("channel", "5");
        List<Integer> list = new ArrayList<>();
        list.add(1);
        list.add(6);
        queryWrapper.in("status", list);
        queryWrapper.eq("merchantCode", merchantBaseInfo.getMerchantCode());
        MerchantChannelStatus mcs = merchantChannelStatusMapper.selectOne(queryWrapper);
        MsgException.checkNull(mcs, "对应的商户信息不存在");


        AccountDTO accountV4 = getAccountV4(userId, "D1");  //结算人

        MsgException.checkNull(accountV4, "结算信息不存在");

        JSONObject object = new JSONObject();
        object.put("accountKind", accountV4.getBankCard().getAccountType().equals("01") ? "58" : "57");
        object.put("accountNo", bankCard.getBankCardNo()); //结算人银行卡号
        object.put("accountName", bankCard.getBankHolder()); //结算人账户名称


        Set<ConcurrentMap<String, String>> attchmentsVoSet = new HashSet<>();
        ConcurrentMap<String, String> frontLegalPersonMap = new ConcurrentHashMap<>();
        frontLegalPersonMap.put("imgPath", laKaLaFileUpload(accountIdCard.getImgPositive(), "ID_CARD_FRONT"));
        frontLegalPersonMap.put("imgType", "ID_CARD_FRONT");
        attchmentsVoSet.add(frontLegalPersonMap);

        ConcurrentMap<String, String> reverseLegalPersonMap = new ConcurrentHashMap<>();
        reverseLegalPersonMap.put("imgPath", laKaLaFileUpload(accountIdCard.getImgNegative(), "ID_CARD_BEHIND"));
        reverseLegalPersonMap.put("imgType", "ID_CARD_BEHIND");
        attchmentsVoSet.add(reverseLegalPersonMap);
        object.put("attachments", attchmentsVoSet);

//        QueryWrapper<Account> accountQueryWrapper1 = new QueryWrapper<>();
//        accountQueryWrapper1.eq("userId", userId);
//        accountQueryWrapper1.eq("channelType", "D1");
//        Account accountServiceOne1 = accountService.getOne(accountQueryWrapper1);
//        MsgException.checkNull(accountServiceOne1, "结算信息未提交");
//
//
//        QueryWrapper<BankCard> bankCardWrapper = new QueryWrapper<>();
//        bankCardWrapper.eq("id", accountServiceOne1.getBankCardId());
//        BankCard userBrakCard = bankCardService.getOne(bankCardWrapper);


        QueryWrapper<TbPlussBankBranchLklEntity> lklEntityQueryWrapper = new QueryWrapper<>();
        lklEntityQueryWrapper.eq("branch_bank_no", bankCard.getContactLine());
        TbPlussBankBranchLklEntity lakalaBranchInfo = tbPlussBankBranchLklService.getOne(lklEntityQueryWrapper);
        MsgException.checkNull(lakalaBranchInfo, "结算卡对应的分行支行信息不存在");

        object.put("bankNo", lakalaBranchInfo.getBranchBankNo()); //结算账户开户⾏号 通过【银行列表查询】接口获取 对应 branchBankNo字段
        object.put("bankName", lakalaBranchInfo.getBranchBankName()); //结算账户开户⾏名称 通过【银行列表查询】接口获取 对应 branchBankName字段
        object.put("clearingBankNo", lakalaBranchInfo.getClearNo()); //结算账户清算⾏号 通过【银行列表查询】接口获取 对应 clearNo字段
//        JSONObject req = new JSONObject();
//        req.put("dto", object);
//        req.put("customerNo", Integer.valueOf(mcs.getMerchantId()));
        object.put("customerNo",Integer.valueOf(mcs.getMerchantId()));

        Map map = getModifyToken("19191703856", "klb1qaz");
        String result = "";
        try {
            log.info("修改信息:{}",object.toString());
            String url = "https://tkapi.lakala.com/htkmerchants/channel/customer/update/settle/";
            result = cn.hutool.http.HttpRequest.post(url.concat(mcs.getMerchantId()))
                    .header("Authorization", "bearer " + map.get("access_token")).header("content-type", "application/json")
                    .body(object.toString()).execute().body();
            System.out.println("返回结果:" + result);
            Map arry = (Map) JSONArray.parse(result);

            if (arry.containsKey("message") && "SUCCESS".equals(arry.get("message") + "")) {
                // 保存商户进件修改记录
                MerchantAuditRecord updateRecord = new MerchantAuditRecord();
                updateRecord.setMerchantId(mcs.getMerchantId());
                updateRecord.setApplicationId(arry.get("reviewRelatedId") + "");
                updateRecord.setChannel(5);
                updateRecord.setStatus("1");
                updateRecord.setMerchantCode(merchantBaseInfo.getMerchantCode());
                // 文档上没有返回状态码
                merchAuditRecService.save(updateRecord);
                // 修改商户状态
                mcs.setStatus(MerchantChannelStatus.AUDIT_STATUS_DATA_EDIT);
                mcs.setApplicationId(arry.get("reviewRelatedId") + "");
                mcsService.updateById(mcs);
            } else {
                MsgException.throwException("修改进件信息失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }


    }

    @Autowired
    @Lazy
    MerchantChannelFeeMapper merchantChannelFeeMapper;

    public void merchAuditFee(String userId) {

        MerchantBaseInfo merchantBaseInfo = mbiService.getMerchantBaseInfoByUserId(userId);
        MsgException.checkNull(merchantBaseInfo, "商户进件信息不存在");

        QueryWrapper<MerchantChannelStatus> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("channel", "5");
        List<Integer> list = new ArrayList<>();
        list.add(1);
        list.add(6);
        queryWrapper.in("status", list);
        queryWrapper.eq("merchantCode", merchantBaseInfo.getMerchantCode());
        MerchantChannelStatus mcs = merchantChannelStatusMapper.selectOne(queryWrapper);
        MsgException.checkNull(mcs, "对应的商户信息不存在");

        QueryWrapper<MerchantChannelFee> feeQueryWrapper = new QueryWrapper<>();
        feeQueryWrapper.eq("channel", "5");
        feeQueryWrapper.eq("merchant_code", merchantBaseInfo.getMerchantCode());

        MerchantChannelFee fee = merchantChannelFeeMapper.selectOne(feeQueryWrapper);
        MsgException.checkNull(fee, "费率值为空");
        JSONArray array = JSONArray.parseArray(fee.getFeeStr());
        JSONArray feeAarray = new JSONArray();
        for (int i = 0; i < array.size(); i++) {
            JSONObject req = array.getJSONObject(i);
            JSONObject object = new JSONObject();
            object.put("fee", req.getDoubleValue("feeValue"));
            object.put("feeType", req.getString("feeCode"));
            feeAarray.add(object);
        }

        JSONObject request = new JSONObject();

//        JSONObject o=new JSONObject();
//        o.put("fees",feeAarray);
        request.put("settleType", mcs.getVirChannelFlag());
        request.put("fees", feeAarray);
        request.put("customerNo", Integer.valueOf(mcs.getMerchantId()));

        Map map = getModifyToken("19191703856", "klb1qaz");
        String result = "";
        try {
            String url = "https://tkapi.lakala.com/htkmerchants/channel/customer/update/fee/";
            result = cn.hutool.http.HttpRequest.post(url.concat(mcs.getMerchantId()))
                    .header("Authorization", "bearer " + map.get("access_token")).header("content-type", "application/json")
                    .body(request.toString()).execute().body();
            System.out.println("返回结果:" + result);
            Map arry = (Map) JSONArray.parse(result);

            if (arry.containsKey("message") && "SUCCESS".equals(arry.get("message") + "")) {
                // 保存商户进件修改记录
                MerchantAuditRecord updateRecord = new MerchantAuditRecord();
                updateRecord.setMerchantId(mcs.getMerchantId());
                updateRecord.setApplicationId(arry.get("reviewRelatedId") + "");
                updateRecord.setChannel(5);
                updateRecord.setStatus("1");
                updateRecord.setMerchantCode(merchantBaseInfo.getMerchantCode());
                // 文档上没有返回状态码
                merchAuditRecService.save(updateRecord);
                // 修改商户状态
                mcs.setApplicationId(arry.get("reviewRelatedId") + "");
                mcsService.updateById(mcs);
            } else {
                MsgException.throwException("修改进件信息失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }



    public boolean htkmerchants(MerchantBaseInfo merchantBaseInfo){

        QueryWrapper<MerchantBackLkl> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("merchant_code",merchantBaseInfo.getMerchantCode());
        MerchantBackLkl backLkl= merchantBackLklService.getOne(queryWrapper);
        MsgException.checkNull(backLkl,"进件信息为空");

        QueryWrapper<MerchantChannelFee> feeQueryWrapper = new QueryWrapper<>();
        feeQueryWrapper.eq("channel", "5");
        feeQueryWrapper.eq("merchant_code", merchantBaseInfo.getMerchantCode());

        MerchantChannelFee fee = merchantChannelFeeMapper.selectOne(feeQueryWrapper);
        MsgException.checkNull(fee, "费率值为空");
        JSONArray array = JSONArray.parseArray(fee.getFeeStr());
        JSONArray feeAarray = new JSONArray();
        for (int i = 0; i < array.size(); i++) {
            JSONObject req = array.getJSONObject(i);
            JSONObject object = new JSONObject();
            object.put("fee", req.getDoubleValue("feeValue"));
            object.put("feeType", req.getString("feeCode"));
            feeAarray.add(object);
        }

        JSONObject object=new JSONObject();
        object.put("externalCustomerNo",backLkl.getExternalCustomerNo());
        object.put("bzPos","KLYX");
        object.put("termNum",5);
        object.put("fees",feeAarray);

        Map map=getToken();
        try {
            String  result = cn.hutool.http.HttpRequest.post("https://tkapi.lakala.com/htkmerchants")
                    .header("Authorization", "bearer " + map.get("access_token")).header("content-type", "application/json")
                    .body(object.toString()).execute().body();
            System.out.println("返回结果:" + result);
            if(ObjectUtil.isNotEmpty(result)){
                JSONObject resp= JSONObject.parseObject(result);
                if(resp.containsKey("code")&&"00000".equals(resp.getString("code"))){
                    return true;
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }

        return false;

    }


    public static void queryReview(String reviewRelatedId){
        Map map=getToken();
        try {
            RestTemplate client = new RestTemplate();
            HttpHeaders headers = new HttpHeaders();
            // 表单提交
            headers.setContentType(MediaType.APPLICATION_JSON);
            headers.set("Authorization", "bearer " + map.get("access_token"));
            //  封装参数
            MultiValueMap<String, String> params = new LinkedMultiValueMap<String, String>();
            params.add("reviewRelatedId", reviewRelatedId);
            HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<MultiValueMap<String, String>>(params, headers);
            //  执行HTTP请求
            String url = "https://htkapi.lakala.com/api/customer/update/review";
            ResponseEntity<String> response = client.exchange(url, HttpMethod.GET, requestEntity, String.class);

            System.out.println(response);

        }catch (Exception e){
            e.printStackTrace();
        }
    }


    /**
     * 获取拓客accessToken
     */
    public static Map getToken() {
        RestTemplate client = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        // 表单提交
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        headers.set("Authorization", "Basic " + getBase64());
        //  封装参数
        MultiValueMap<String, String> params = new LinkedMultiValueMap<String, String>();
        params.add("grant_type", grant_type);
        params.add("client_id", client_id);
        params.add("client_secret", client_secret);
        HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<MultiValueMap<String, String>>(params, headers);
        //  执行HTTP请求
        ResponseEntity<String> response = client.exchange(tuoKeToken, HttpMethod.POST, requestEntity, String.class);

        Map map = (Map) JSONArray.parse(response.getBody());
        return map;
    }


    public static Map getModifyToken(String userName, String password) {
        RestTemplate client = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        // 表单提交
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        headers.set("Authorization", "Basic " + getBase64());
        //  封装参数
        MultiValueMap<String, String> params = new LinkedMultiValueMap<String, String>();
        params.add("grant_type", "password");
        params.add("username", userName);
        params.add("password", password);
        HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<MultiValueMap<String, String>>(params, headers);
        //  执行HTTP请求
        String url = "https://htkapi.lakala.com/auth/oauth/token";
        ResponseEntity<String> response = client.exchange(url, HttpMethod.POST, requestEntity, String.class);

        Map map = (Map) JSONArray.parse(response.getBody());
        return map;
    }


    public Map queryMerchat(String customerNo, String externalCustomerNo) {
        Map map = getToken();
        try {
            JSONObject object = new JSONObject();
            if (ObjectUtil.isNotEmpty(customerNo)) {
                object.put("customerNo", customerNo);
            }

            if (ObjectUtil.isNotEmpty(externalCustomerNo)) {
                object.put("externalCustomerNo", externalCustomerNo);
            }

            JSONObject req = new JSONObject();
            byte[] privateKey = Base64.decodeBase64(lakalaConfig.getPrivateKey());
            byte[] bytes = RSAUtil.encryptByPrivateKey(object.toString().getBytes(), privateKey);

            req.put("data", Base64.encodeBase64String(bytes));

            log.info("请求参数:加密前：{}，加密后:{}", object.toString(), req.toString());
            String result = cn.hutool.http.HttpRequest.post("https://tkapi.lakala.com/htkmerchants/open/merchant/info")
                    .header("Authorization", "bearer " + map.get("access_token")).header("content-type", "application/json")
                    .body(req.toJSONString()).execute().body();
            Map arry = (Map) JSONArray.parse(result);
            log.info("返回参数:", JSONUtil.toJsonStr(arry));
            return arry;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }


    // 加密
    public static String getBase64() {

        String encodeBase64String = org.apache.commons.codec.binary.Base64.encodeBase64String((client_id + ":" + client_secret).getBytes());

        return encodeBase64String;
    }

    // 解密
    public static String getFromBase64(String s) {
        byte[] decodeBase64 = org.apache.commons.codec.binary.Base64.decodeBase64(s);
        s = new String(decodeBase64);
        return s;
    }


    /**
     * 拼接身份证过期时间
     */
    public String birthdayDate(String date) {
        String str = new String(date);
        String s1 = "";

        s1 = str.substring(0, 4) + "-" + str.substring(4, 6) + "-" + str.substring(6, str.length());
        return s1;
    }

    @Autowired
    private UserAppService userAppService;

    /**
     * 获取结算人信息
     */
    public AccountDTO getAccountV4(String userId, String type) {

        UserApp userApp = userAppService.getById(userId);
        if (type == null) {

            MerchantChannelStatus mcs = mcsService.getValidData(userApp.getMerchantCode());
            if (mcs == null || !Objects.equals(mcs.getChannel(), 4)) {
                type = Account.CHANNEL_TYPE_D1;
            } else {
                type = Account.CHANNEL_TYPE_D0;
            }
        }
        AccountDTO accountDTO = accountService.getRealAccount(userId);
        if (accountDTO == null) {
            accountDTO = new AccountDTO();
        }
        if (accountDTO.getIdcard() == null && accountDTO.getBankCard() == null) {
            accountDTO.setIdcard(new IdCard());
            accountDTO.setBankCard(new BankCard());
        }
        return accountDTO;
    }

    /**
     * 获取地区信息
     */
    public List<OrganVo> getOrganCode(String code) {
        /**获取拓客accessToken**/
        RestTemplate client = new RestTemplate();


        Map parse = getToken();
        HttpHeaders header = new HttpHeaders();
        header.set("Authorization", "bearer " + parse.get("access_token"));
        //  封装参数
        MultiValueMap<String, String> par = new LinkedMultiValueMap<String, String>();

        HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<MultiValueMap<String, String>>(par, header);
        //  执行HTTP请求
        ResponseEntity<String> re = client.exchange(organparentCode + code, HttpMethod.GET, request, String.class);
        List<OrganVo> jsonArrayList = null;
        try {
            String seqResult = new String(re.getBody().getBytes("ISO8859-1"), "utf-8");
            jsonArrayList = JSONArray.parseArray(seqResult, OrganVo.class);
//            jsonArrayList = (List<OrganVo>) JSONArray.parse(seqResult);
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
        return jsonArrayList;
    }


    /**
     * 获取银行地区信息
     */
    public String bankOrgen(String code) {
        RestTemplate client = new RestTemplate();
        Map parse = getToken();
        HttpHeaders header = new HttpHeaders();
        header.set("Authorization", "bearer " + parse.get("access_token"));
        MultiValueMap<String, String> par = new LinkedMultiValueMap<String, String>();
        HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<MultiValueMap<String, String>>(par, header);
        //  执行HTTP请求
        ResponseEntity<String> re = client.exchange(organizationBank + code, HttpMethod.GET, request, String.class);
        try {
            String seqResult = new String(re.getBody().getBytes("ISO8859-1"), "utf-8");
            return seqResult;
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 银行列表查询
     */
    public String banList(String areaCode) {
        Map parse = getToken();


        //请求头
        HttpHeaders header = new HttpHeaders();
        header.add("Authorization", "bearer " + parse.get("access_token"));
        MultiValueMap<String, Object> param = new LinkedMultiValueMap<String, Object>();
        //封装请求头
        HttpEntity<MultiValueMap<String, Object>> formEntity = new HttpEntity<MultiValueMap<String, Object>>(param, header);
        RestTemplate restTemplate = new RestTemplate();
        try {
            //访问地址
            ResponseEntity<String> result4 = restTemplate.exchange("https://htkactvi.lakala.com/registration/bank?areaCode=" + areaCode, HttpMethod.GET, formEntity, String.class);
            String seqResult = new String(result4.getBody().getBytes("ISO8859-1"), "utf-8");

            return seqResult;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    /**
     * 商户类别查询
     * 一般商户传1 小微系统商户传2 （拓客现在只传2）
     */
    public String htkRegistration() {
        /**获取拓客accessToken**/
        RestTemplate client = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        // 表单提交
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

        Map parse = getToken();
        HttpHeaders header = new HttpHeaders();
        header.set("Authorization", "bearer " + parse.get("access_token"));
        //  封装参数
        MultiValueMap<String, String> par = new LinkedMultiValueMap<String, String>();
        par.add("businessScene", "2");
        HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<MultiValueMap<String, String>>(par, header);
        //  执行HTTP请求
        ResponseEntity<String> re = client.exchange("https://htkactvi.lakala.com/registration/customer/category", HttpMethod.GET, request, String.class);

        try {
            String seqResult = new String(re.getBody().getBytes("ISO8859-1"), "utf-8");
            return seqResult;
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 获取大类和小类
     */
    public String getRegistrationChid() {
        /**获取拓客accessToken**/
        RestTemplate client = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        // 表单提交
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

        Map parse = getToken();
        HttpHeaders header = new HttpHeaders();
        header.set("Authorization", "bearer " + parse.get("access_token"));
        //  封装参数
        MultiValueMap<String, String> par = new LinkedMultiValueMap<String, String>();

        HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<MultiValueMap<String, String>>(par, header);
        //  执行HTTP请求
        ResponseEntity<String> re = client.exchange("https://htkactvi.lakala.com/registration/customer/category", HttpMethod.GET, request, String.class);

        try {
            String seqResult = new String(re.getBody().getBytes("ISO8859-1"), "utf-8");
            return seqResult;
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 拓客文件上传接口
     */
    @SneakyThrows
    public static String laKaLaFileUpload(String url1, String type) {
        String url = fileUpload;
        Map<String, Object> params = new HashMap<>();

//        String url1 = "https://czg-oss.oss-cn-hangzhou.aliyuncs.com/images/9b42a8f68e2b4682bdb72490abe131fe.png?Expires=1994642722&OSSAccessKeyId=LTAI5tPdEfYSZcqHbjCrtPRD&Signature=cTcS0ey%2F6NYWQnyvVCMQsO6rZMU%3D";
        URI uri = null;
        try {
            uri = new URI(url1);
        } catch (URISyntaxException e) {
            throw new RuntimeException(e);
        }
        RestTemplate restTemplate1 = new RestTemplate();
        ResponseEntity<byte[]> exchange = restTemplate1.exchange(uri, HttpMethod.GET, null, byte[].class);
        MultipartFile file1 = new MockMultipartFile("file", exchange.getBody());
        File file = convert(file1);

        params.put("file", file);
        params.put("imgType", type);
        params.put("sourcechnl", "0");
        params.put("isOcr", "false");

        Map token = getToken();
        String result = HttpRequest.post(url)
                .header("Authorization", "bearer " + token.get("access_token"))
                .form(params).execute().body();
        Map parse = (Map) JSONArray.parse(result);
        log.info("拉卡拉图片上传返回信息:{}", result);
        return parse.get("url").toString();
    }


    @SneakyThrows
    public static String laKaLaFileUpload(File file, String type) {
        RestTemplate restTemplate = new RestTemplate();
        String url = fileUpload;
        Map<String, Object> params = new HashMap<>();

        params.put("file", file);
        params.put("imgType", type);
        params.put("sourcechnl", "0");
        params.put("isOcr", "false");

        Map token = getToken();
        String result = HttpRequest.post(url)
                .header("Authorization", "bearer " + token.get("access_token"))
                .form(params).execute().body();
        Map parse = (Map) JSONArray.parse(result);
        log.info("拉卡拉图片上传返回信息:{}", result);
        return parse.get("url").toString();
    }

    public static File convert(MultipartFile multipartFile) throws IOException {
        InputStream inputStream = multipartFile.getInputStream();
        File file = File.createTempFile(ObjectUtil.isEmpty(multipartFile.getOriginalFilename()) ? System.currentTimeMillis() + "" : multipartFile.getOriginalFilename(), ".png");
        FileOutputStream outputStream = new FileOutputStream(file);
        byte[] buffer = new byte[1024];
        int bytesRead = 0;
        while ((bytesRead = inputStream.read(buffer)) != -1) {
            outputStream.write(buffer, 0, bytesRead);
        }
        outputStream.close();
        file.deleteOnExit();
        return file;
    }


    /**
     * 银行地区对象
     */
    @Data
    static class BankInfo {
        private String clearNo;
        private String branchBankNo;
        private String branchBankName;
        private String bankNo;
        private String areaCode;
    }

    /**
     * 银行对象
     */
    @Data
    static class Region {
        private String code;
        private String name;
    }


    public void ff() {
        LaKalaInterfaceImpl laKalaInterface = new LaKalaInterfaceImpl();

        String s = laKalaInterface.bankOrgen("1");
        List<Region> lists = JSONArray.parseArray(s, Region.class);
        for (Region list : lists) {
            String s1 = laKalaInterface.bankOrgen(list.getCode());
            List<Region> lists1 = JSONArray.parseArray(s1, Region.class);
            for (Region bank : lists1) {
                String s2 = laKalaInterface.banList(bank.getCode());
                List<BankInfo> bankInfos = JSONArray.parseArray(s2, BankInfo.class);
                for (BankInfo bankInfo : bankInfos) {
                    TbLklRegionBankInfoEntity entity = new TbLklRegionBankInfoEntity();
                    entity.setSCode(list.getCode());
                    entity.setSName(list.getName());
                    entity.setRCode(bank.getCode());
                    entity.setRName(bank.getName());
                    entity.setAreaCode(bankInfo.getAreaCode());
                    entity.setBankNo(bankInfo.getBankNo());
                    entity.setBranchBankName(bankInfo.getBranchBankName());
                    entity.setBranchBankNo(bankInfo.getBranchBankNo());
                    entity.setClearNo(bankInfo.getClearNo());
                    tbLklRegionBankInfoServiceImpl.aa(entity);
                }
            }
        }
    }

    static  class FeeInfoDto{
        private Double fee;

        private Double topFee;

        private String feeType;

        public Double getFee() {
            return fee;
        }

        public void setFee(Double fee) {
            this.fee = fee;
        }

        public Double getTopFee() {
            return topFee;
        }

        public void setTopFee(Double topFee) {
            this.topFee = topFee;
        }

        public String getFeeType() {
            return feeType;
        }

        public void setFeeType(String feeType) {
            this.feeType = feeType;
        }
    }

    public static void main(String[] args) {




        queryReview("7834754512434053005");

//        System.out.println(getToken());


//        System.out.println(LaKaLaUtility.decrypt("MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCHB7j7gG3ioLnnr7bsuEXTAh/8YSxSp4lQIYGW9gX0Ikgz9JqARdg4iEnU6tgNirxA6Jdg0AWgLJQxQBEZMkwyK2ZfYgesYhlJkv6WVC8v5OkOrhA9NSQ3iS6JsYegsZO0GJSTtLQaTOF8WobPYe5NI+eWU1fRz2ZyxlWlKshBeQIDAQAB","VLFMfe4RbgEAZ5+eXhr+VAhxomLii3D/LbZawImg3lMqv9FjCUPLm5FG31pYljIMy/nkjpLifyuqRv3SdJo9RvPqN/1g5X3/QSRZPnaNER47peybLfCqUJCgJJmRSOS+auiZNECXkuYgvR6rVlR/ikOyJ1+zBw+CIAdb8wJu0V8="));


        List<FeeInfoDto> feeInfoDtos=new ArrayList<>();

        FeeInfoDto feeInfoDto1=new FeeInfoDto();
        feeInfoDto1.setFeeType("WECHAT");
        feeInfoDto1.setFee(0.38d);
        feeInfoDtos.add(feeInfoDto1);

        FeeInfoDto feeInfoDto2=new FeeInfoDto();
        feeInfoDto2.setFeeType("ALIPAY");
        feeInfoDto2.setFee(0.38d);
        feeInfoDtos.add(feeInfoDto2);

        FeeInfoDto feeInfoDto3=new FeeInfoDto();
        feeInfoDto3.setFeeType("SCAN_PAY_SECOND");
        feeInfoDto3.setFee(0.38d);
        feeInfoDtos.add(feeInfoDto3);

        JSONObject object=new JSONObject();




        Map map=getToken();
        try {



            JSONObject req=new JSONObject();
            object.put("externalCustomerNo","8221100572200L4");
            byte[] privateKey = Base64.decodeBase64("MIICdQIBADANBgkqhkiG9w0BAQEFAASCAl8wggJbAgEAAoGBAIcHuPuAbeKgueevtuy4RdMCH/xhLFKniVAhgZb2BfQiSDP0moBF2DiISdTq2A2KvEDol2DQBaAslDFAERkyTDIrZl9iB6xiGUmS/pZULy/k6Q6uED01JDeJLomxh6Cxk7QYlJO0tBpM4Xxahs9h7k0j55ZTV9HPZnLGVaUqyEF5AgMBAAECgYAmugRHvXHGiapH1JF2GvOLrRRXYddAbWRoYvOzxCO4/QwQOpsFJwL4U745HpGQcLXFN/ASiBbU9XQbG/DLdS182qAjvdZVJOA2e3H3LhpY3D8ec3webO+0nGk6e4oWGG1efJLM88Nb0FtQiQ0E6z17Paw5AGvxMVBPbL5SoQfq8QJBANHQmvFkAWlBL2XTLPUXaj+NAJzolE90ctAquxfDcTtfEXv0JitC5bwTg87uNl7n4PUTmtMDIkse+D5vQ2CIF78CQQCkwOIMzedKtWhOEbdGxiz1Y/jkuA8yF7HREeC7X2Av0z2Gi3yltoJd0s6zLn+6zowQp1O/5U6ifrYCIObWlTTHAkA0WOZ/eWL8vr2zmvdpgtkIWAaiH0j5deU7WJ3rNODoXjS/h0+KlZs5zGijVT2Nei7fFnAXW33P3j8zXJEj4XCDAkAcrG0rKVLNz9C9dZveN3NvqdyRge8zGqiZ6HCia7ED4dHdbr1c4ezCg4Px72/PhU8fPt/2j+Qlp8PpjuxeAE3VAkBqUiVV9XZptFEXa/77rgHP3SWrC3TcrrS5jtNTGfA4VISV95YXnZzWjYfpgs2WoxdAXjsrM5TB7L3V4um4o6Dp");
            byte[] bytes = RSAUtil.encryptByPrivateKey(object.toString().getBytes(), privateKey);

            req.put("data",Base64.encodeBase64String(bytes));

            System.out.println("请求参数:"+object.toString());
            String  result = cn.hutool.http.HttpRequest.post("https://tkapi.lakala.com/htkmerchants/open/merchant/info")
                    .header("Authorization", "bearer " + map.get("access_token")).header("content-type", "application/json")
                    .body(req.toString()).execute().body();
            System.out.println("返回结果:" + result);
            if(ObjectUtil.isNotEmpty(result)){

                JSONObject resp=JSONObject.parseObject(result);
                if(resp.containsKey("code")&&"000000".equals(resp.getString("code"))){
                    String data=resp.getString("data");
                    data = LaKaLaUtility.decrypt("MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCHB7j7gG3ioLnnr7bsuEXTAh/8YSxSp4lQIYGW9gX0Ikgz9JqARdg4iEnU6tgNirxA6Jdg0AWgLJQxQBEZMkwyK2ZfYgesYhlJkv6WVC8v5OkOrhA9NSQ3iS6JsYegsZO0GJSTtLQaTOF8WobPYe5NI+eWU1fRz2ZyxlWlKshBeQIDAQAB",data);

                    System.out.println("解密后的数据:"+data);
//
//                    Long shopId=JSONObject.parseObject(data).getJSONArray("shopInfoList").getJSONObject(0).getLong("shopId");
//                    object=new JSONObject();
//                    object.put("externalCustomerNo","8221100572200L4");
//                    object.put("bzPos","KLYX");
//                    object.put("termNum",1);
//                    object.put("fees",feeInfoDtos);
//                    object.put("shopId",shopId);
//                    object.put("attachments",null);
//                    privateKey = Base64.decodeBase64("MIICdQIBADANBgkqhkiG9w0BAQEFAASCAl8wggJbAgEAAoGBAIcHuPuAbeKgueevtuy4RdMCH/xhLFKniVAhgZb2BfQiSDP0moBF2DiISdTq2A2KvEDol2DQBaAslDFAERkyTDIrZl9iB6xiGUmS/pZULy/k6Q6uED01JDeJLomxh6Cxk7QYlJO0tBpM4Xxahs9h7k0j55ZTV9HPZnLGVaUqyEF5AgMBAAECgYAmugRHvXHGiapH1JF2GvOLrRRXYddAbWRoYvOzxCO4/QwQOpsFJwL4U745HpGQcLXFN/ASiBbU9XQbG/DLdS182qAjvdZVJOA2e3H3LhpY3D8ec3webO+0nGk6e4oWGG1efJLM88Nb0FtQiQ0E6z17Paw5AGvxMVBPbL5SoQfq8QJBANHQmvFkAWlBL2XTLPUXaj+NAJzolE90ctAquxfDcTtfEXv0JitC5bwTg87uNl7n4PUTmtMDIkse+D5vQ2CIF78CQQCkwOIMzedKtWhOEbdGxiz1Y/jkuA8yF7HREeC7X2Av0z2Gi3yltoJd0s6zLn+6zowQp1O/5U6ifrYCIObWlTTHAkA0WOZ/eWL8vr2zmvdpgtkIWAaiH0j5deU7WJ3rNODoXjS/h0+KlZs5zGijVT2Nei7fFnAXW33P3j8zXJEj4XCDAkAcrG0rKVLNz9C9dZveN3NvqdyRge8zGqiZ6HCia7ED4dHdbr1c4ezCg4Px72/PhU8fPt/2j+Qlp8PpjuxeAE3VAkBqUiVV9XZptFEXa/77rgHP3SWrC3TcrrS5jtNTGfA4VISV95YXnZzWjYfpgs2WoxdAXjsrM5TB7L3V4um4o6Dp");
//                    bytes = RSAUtil.encryptByPrivateKey(object.toString().getBytes(), privateKey);
//                    req=new JSONObject();
//                    req.put("data",Base64.encodeBase64String(bytes));
//                    System.out.println("请求参数:"+object.toString());
//                    result = cn.hutool.http.HttpRequest.post("https://tkapi.lakala.com/htkmerchants/open/merchant/addTerm")
//                            .header("Authorization", "bearer " + map.get("access_token")).header("content-type", "application/json")
//                            .body(req.toString()).execute().body();
//                    System.out.println("返回结果:" + result);
//
//                    System.out.println("解密后结果:"+LaKaLaUtility.decrypt("MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCHB7j7gG3ioLnnr7bsuEXTAh/8YSxSp4lQIYGW9gX0Ikgz9JqARdg4iEnU6tgNirxA6Jdg0AWgLJQxQBEZMkwyK2ZfYgesYhlJkv6WVC8v5OkOrhA9NSQ3iS6JsYegsZO0GJSTtLQaTOF8WobPYe5NI+eWU1fRz2ZyxlWlKshBeQIDAQAB",result));
                }
            }






        }catch (Exception e){
            e.printStackTrace();
        }

//        Map map = getToken();
//        System.out.println(JSONUtil.toJsonStr(map));

//        System.out.println(laKaLaFileUpload("https://czg-oss.oss-cn-hangzhou.aliyuncs.com/images/819abf620cfe4e6f9e2c432a998090ab.png?Expires=2002093384&OSSAccessKeyId=LTAI5tPdEfYSZcqHbjCrtPRD&Signature=8%2FQMRnkTQmQF8jp93XxayPZbPuU%3D", "BUSINESS_LICENCE"));

//        System.out.println(new LaKalaInterfaceImpl().getRegistrationChid());
//        String result="";
//        try{
//            JSONObject object=new JSONObject();
//            object.put("customerNo","123627687");
//
//            result = cn.hutool.http.HttpRequest.post("https://tkapi.lakala.com/htkmerchants/open/merchant/info")
//                    .header("Authorization", "bearer " + map.get("access_token")).header("content-type", "application/json")
//                    .body(object.toString()).execute().body();
//            Map arry = (Map) JSONArray.parse(result);
//            System.out.println(JSONUtil.toJsonStr(arry));
//        }catch (Exception e){
//            e.printStackTrace();
//        }


//        LaKalaInterfaceImpl laKalaInterface = new LaKalaInterfaceImpl();
//        laKalaInterface.getOrganCode("1");
//        try {
//            laKalaInterface.laKaLaFileUpload1();
//        } catch (IOException e) {
//            throw new RuntimeException(e);
//        }

//        System.out.println(getBase64("testsit:EguwEckByf2I6u6z"));

//        String str = new String("20180301");
//        String s1 = "";
//
//        s1 = str.substring(0, 4) + "-" + str.substring(4, 6) + "-" + str.substring(6, str.length());
//
//        System.out.println(s1);
    }

}
