package com.hfkj.channel.lakala;

import com.alibaba.fastjson.JSONObject;
import com.ccb.wlpt.config.SysConfig;
import com.hfkj.channel.saas.saasenum.FileImgType;
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.config.CommonSysConst;
import com.hfkj.entity.*;
import com.hfkj.channel.lakala.config.LaKaLaConfig;
import com.hfkj.model.MerBasisModel;
import com.hfkj.service.*;
import com.hfkj.sysenum.MerAttachType;
import com.hfkj.sysenum.PlatformTypeEnum;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

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

/**
 * 拉卡拉商户 服务
 * @author hurui
 */
@Service("lklMerContractService")
public class LaKaLaMerService {

    @Resource
    private BsMerContractRecordService merContractRecordService;

    @Resource
    private BsMerContractRecordMsgService merContractRecordMsgService;

    @Resource
    private BsMerService merService;

    @Resource
    private BsIndustryService industryService;

    @Resource
    private SecRegionService regionService;

    @Resource
    private BsMerRateService merRateService;

    @Resource
    private BsMerPlatformNoService merPlatformNoService;

    @Resource
    private BsMerPlatformNoRateService merPlatformNoRateService;

    @Resource
    private BsMerAttachService merAttachService;

    @Resource
    private SaasCommon saasCommon;

    /**
     * 商户进件
     * @param merId
     */
    public void addMer(Long merId) {
        MerBasisModel basisModel = merService.getMerDetail(merId);

        // 经营内容
        BsIndustry industry = industryService.getDetailById(basisModel.getMerIndustry().getChildId());
        if (industry == null) {
            throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未找到经营范围");
        }

        String orderNo = ""+System.currentTimeMillis();

        Map<String, Object> map = new HashMap<>();
        map.put("version", "1.0");
        map.put("orderNo", orderNo);
        map.put("posType", "WECHAT_PAY");
        map.put("orgCode", CommonSysConst.getSysConfig().getLkl_org_code());
        map.put("merRegName", basisModel.getMerName());
        map.put("merRegDistCode", regionService.getRegionById(basisModel.getMerRegion().getAreaCode()).getLakala());
        map.put("merRegAddr", LaKaLaMerService.dislodge(basisModel.getMerRegion().getAddress()));
        map.put("mccCode", basisModel.getMerMccCode());
        map.put("merBlisName", basisModel.getMerName());
        map.put("merBlis", basisModel.getBlisNo());
        map.put("merBlisStDt", DateUtil.format(DateUtil.format(basisModel.getBlisPeriodStart(), "yyyy年MM月dd日"), "yyyy-MM-dd"));

        Date blisPeriodEnd = DateUtil.format(basisModel.getBlisPeriodEnd(), "yyyy月MM日dd");
        if (blisPeriodEnd == null) {
            Calendar c = Calendar.getInstance();
            c.set(9999,11,31);
            map.put("merBlisExpDt", DateUtil.format(c.getTime(), "yyyy-MM-dd"));
        } else {
            map.put("merBlisExpDt", DateUtil.format(blisPeriodEnd, "yyyy-MM-dd"));
        }

        map.put("merBusiContent", industry.getExt1());
        map.put("larName", basisModel.getLarName());
        map.put("larIdType", "01");
        map.put("larIdcard", basisModel.getLarIdCard());
        map.put("larIdcardStDt", DateUtil.format(DateUtil.format(basisModel.getLarIdCardPeriodStart(), "yyyy.MM.dd"), "yyyy-MM-dd"));

        Date larIdCardPeriodEnd = DateUtil.format(basisModel.getLarIdCardPeriodEnd(), "yyyy.MM.dd");
        if (larIdCardPeriodEnd == null) {
            Calendar c = Calendar.getInstance();
            c.set(9999,11,31);
            map.put("larIdcardExpDt", DateUtil.format(c.getTime(), "yyyy-MM-dd"));
        } else {
            map.put("larIdcardExpDt", DateUtil.format(larIdCardPeriodEnd, "yyyy-MM-dd"));
        }
        map.put("merContactMobile", basisModel.getRegPhone());
        map.put("merContactName", basisModel.getRegName());
        map.put("openningBankCode", basisModel.getMerSettleAcct().getOpenningBankCode());
        map.put("openningBankName", basisModel.getMerSettleAcct().getOpenningBankName());
        map.put("clearingBankCode", basisModel.getMerSettleAcct().getClearingBankCode());
        map.put("acctNo", basisModel.getMerSettleAcct().getBankCardNo());

        // 对公传公司名, 对私传法人名
        if (basisModel.getMerSettleAcct().getSettleType().equals(1)) {
            map.put("acctName", basisModel.getMerName());
        } else {
            map.put("acctName", basisModel.getMerSettleAcct().getSettleIdCardName());
        }
        map.put("acctTypeCode", basisModel.getMerSettleAcct().getSettleType() == 1?57:58);
        map.put("settlePeriod", "T+1");
        map.put("retUrl", CommonSysConst.getSysConfig().getLkl_mer_contract_ret_url());

        // 平台商户记录
        BsMerPlatformNo merPlatformNo = new BsMerPlatformNo();
        merPlatformNo.setMerId(merId);
        merPlatformNo.setMerNo(basisModel.getMerNo());
        merPlatformNo.setPlatformType(PlatformTypeEnum.type1.getNumber());
        merPlatformNoService.editMerPlatformNo(merPlatformNo);

        List<Map<String, Object>> feeDataMap = new ArrayList<>();
        // 查询商户费率列表
        List<BsMerRate> rateList = merRateService.getRateListByMerId(merId);
        Map<String, Object> feeData;
        for (BsMerRate merRate : rateList) {
            feeData = new HashMap<>();
            feeData.put("feeRateTypeCode", merRate.getRateTypeCode());
            feeData.put("feeRateTypeName", merRate.getRateTypeName());
            feeData.put("feeRatePct", merRate.getRatePct());
            feeDataMap.add(feeData);

            // 平台费率记录
            BsMerPlatformNoRate platformNoRate = new BsMerPlatformNoRate();
            platformNoRate.setMerPlatformNoId(merPlatformNo.getId());
            platformNoRate.setMerId(basisModel.getId());
            platformNoRate.setMerNo(basisModel.getMerNo());
            platformNoRate.setPlatformType(PlatformTypeEnum.type1.getNumber());
            platformNoRate.setRateTypeCode(merRate.getRateTypeCode());
            platformNoRate.setRateTypeName(merRate.getRateTypeName());
            platformNoRate.setRatePct(merRate.getRatePct());
            merPlatformNoRateService.editRate(platformNoRate);
        }
        map.put("feeData", feeDataMap);

        List<Map<String, Object>> attachListMap = new ArrayList<>();
        Map<String, Object> attachMap;
        // 查询商户附件列表
        List<BsMerAttach> attachList = merAttachService.getAttachListByMer(merId, PlatformTypeEnum.type0, null);
        for (BsMerAttach attach : attachList) {
            attachMap = new HashMap<>();
            MerAttachType attachType = MerAttachType.getDataByNumber(attach.getType());
            if (attachType == null || StringUtils.isBlank(attachType.getLklCode())) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未知的附件类型");
            }
            attachMap.put("attType", attachType.getLklCode());
            attachMap.put("attFileId", saasCommon.fileUpload(new File(CommonSysConst.getSysConfig().getFile_url() +"/"+ attach.getFileUrl()), attachType.getLklCode(), "0").getString("url"));
            attachListMap.add(attachMap);
        }
        map.put("fileData", attachListMap);

        // 请求参数
        Map<String, Object> param = new HashMap<>();
        param.put("reqData", map);

        // 生成签名
        Map<String, Object> reqParam = LaKaLaConfig.generateSignParamsV2(JSONObject.parseObject(JSONObject.toJSONString(param)));

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


        System.out.println("Authorization" + JSONObject.toJSONString(reqParam.get("Authorization")));
        System.out.println("param" + JSONObject.toJSONString(param));

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

        JSONObject respData = responseBody.getJSONObject("respData");

        // 增加进件记录
        BsMerContractRecord record = new BsMerContractRecord();
        record.setMerId(merId);
        record.setPlatformType(PlatformTypeEnum.type1.getNumber());
        record.setOrderNo(orderNo);
        record.setContractId(respData.getString("contractId"));
        merContractRecordService.insertRecord(record);

        // 增加进件记录消息
        BsMerContractRecordMsg recordMsg = new BsMerContractRecordMsg();
        recordMsg.setOrderNo(orderNo);
        recordMsg.setType(1);

        Map<String, Object> requestContent = new HashMap<>();
        requestContent.put("Authorization", reqParam.get("Authorization"));
        requestContent.put("Body", JSONObject.toJSONString(param));

        recordMsg.setRequestContent(JSONObject.toJSONString(requestContent));
        recordMsg.setResponseCode(responseBody.getString("retCode"));
        recordMsg.setResponseMsg(responseBody.getString("retMsg"));
        recordMsg.setResponseContent(responseBody.toJSONString());
        merContractRecordMsgService.insertRecordMsg(recordMsg);
    }

    /**
     * 地址去除省、市
     * @param str
     * @return
     */
    public static String dislodge(String str) {
        char[] chars = str.toCharArray();
// oP: '省' 的偏移, oC: '市' 的偏移, oR: "自治区" 的偏移
        int oP = -1, oC = -1, oR = -1;
        char ch;
        for (int i = 0; i < chars.length; i++) {
            ch = chars[i];
            // 一般来说 '省' 的位置会比 '市' 早出现
            if (ch == '省') {
                oP = i;
            } else if (ch == '市') {
                oC = i;
                // 找到 '市' 后就可以跳出循环了
                break;
            } else if (ch == '自'
                    && i + 2 < chars.length
                    && chars[i + 1] == '治'
                    && chars[i + 2] == '区') {
                // "自治区" 出现的几率挺小
                oR = i + 2;
            }
        }

        if (oC != -1) {
            str = str.substring(oC + 1);
        } else if (oP != -1) {
            str = str.substring(oP + 1);
        } else if (oR != -1) {
            str = str.substring(oR + 1);
        }

        return str;
    }
}
