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

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.jeequan.jeepay.core.entity.MchApplyment;
import com.jeequan.jeepay.core.entity.MchModifyApplyment;
import com.jeequan.jeepay.core.exception.BizException;
import com.jeequan.jeepay.core.interfaces.paychannel.IIsvmchModifyApplymentService;
import com.jeequan.jeepay.core.model.applyment.KqpayApplymentInfo;
import com.jeequan.jeepay.core.model.applyment.MchModifyApplymentModel;
import com.jeequan.jeepay.core.model.params.kqpay.KqpayIsvParams;
import com.jeequan.jeepay.thirdparty.channel.kqpay.model.KqpayResp;
import com.jeequan.jeepay.thirdparty.channel.kqpay.util.KqpayConst;
import com.jeequan.jeepay.thirdparty.service.ConfigContextQueryService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.tuple.MutablePair;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

@Slf4j
@Service
public class KqpayMchModifyApplymentService implements IIsvmchModifyApplymentService {

    @Autowired
    private ConfigContextQueryService configContextQueryService;

    @Override
    public MutablePair<MchModifyApplyment, MchApplyment> localModifyBase(MutablePair<MchModifyApplyment, MchApplyment> mchDataPair) {
        MchModifyApplyment resultModifyApplyment = new MchModifyApplyment();
        MchApplyment resultMchApplyment = new MchApplyment();

        MchModifyApplyment mchModifyApplyment = mchDataPair.getKey();
        resultModifyApplyment.setModifyApplyId(mchModifyApplyment.getModifyApplyId());
        resultModifyApplyment.setState(MchApplyment.STATE_SUCCESS);
        MchApplyment mchApplyment = mchDataPair.getValue();
        resultMchApplyment.setApplyId(mchApplyment.getApplyId());

        String applyDetailInfo = mchModifyApplyment.getApplyDetailInfo();
        MchModifyApplymentModel mchModifyData = JSON.parseObject(applyDetailInfo, MchModifyApplymentModel.class);

        String originApplyDetailInfo = mchApplyment.getApplyDetailInfo();
        KqpayApplymentInfo originMchModifyData = JSON.parseObject(originApplyDetailInfo, KqpayApplymentInfo.class);
        resultMchApplyment.setApplyDetailInfo(JSON.toJSONString(originMchModifyData));

        originMchModifyData.setMchShortName(mchModifyData.getMchShortName());
        resultMchApplyment.setMchShortName(mchModifyData.getMchShortName());

        return new MutablePair<>(resultModifyApplyment, resultMchApplyment);
    }

    @Override
    public MutablePair<MchModifyApplyment, MchApplyment> localModifySettlement(MutablePair<MchModifyApplyment, MchApplyment> mchDataPair) {
        MchModifyApplyment resultModifyApplyment = new MchModifyApplyment();
        MchApplyment resultMchApplyment = new MchApplyment();

        MchModifyApplyment mchModifyApplyment = mchDataPair.getKey();
        resultModifyApplyment.setModifyApplyId(mchModifyApplyment.getModifyApplyId());
        resultModifyApplyment.setState(MchApplyment.STATE_SUCCESS);
        MchApplyment mchApplyment = mchDataPair.getValue();
        resultMchApplyment.setApplyId(mchApplyment.getApplyId());

        String applyDetailInfo = mchModifyApplyment.getApplyDetailInfo();
        MchModifyApplymentModel mchModifyData = JSON.parseObject(applyDetailInfo, MchModifyApplymentModel.class);

        String originApplyDetailInfo = mchApplyment.getApplyDetailInfo();
        KqpayApplymentInfo originMchModifyData = JSON.parseObject(originApplyDetailInfo, KqpayApplymentInfo.class);
        resultMchApplyment.setApplyDetailInfo(JSON.toJSONString(originMchModifyData));

        originMchModifyData.setSettAccountType(mchModifyData.getSettAccountType());
        originMchModifyData.setIsUncrpSett(mchModifyData.getIllegal());
        originMchModifyData.setSettAccountLicenseImg(mchModifyData.getSettAccountLicenseImg());
        originMchModifyData.setSettAccountName(mchModifyData.getSettAccountName());
        originMchModifyData.setSettAccountNo(mchModifyData.getSettAccountNo());
        originMchModifyData.setSettAccountBankName(mchModifyData.getSettAccountBankName());
        originMchModifyData.setPersonalInformationAttorney(mchModifyData.getNonLegSettleAuthPic());
        originMchModifyData.setSettAccountIdcardNo(mchModifyData.getSettAccountIdcardNo());
        originMchModifyData.setSettAccountIdcard1Img(mchModifyData.getSettAccountIdcard1Img());
        originMchModifyData.setSettAccountIdcard2Img(mchModifyData.getSettAccountIdcard2Img());
        originMchModifyData.setSettAccountIdcardEffectBegin(mchModifyData.getSettAccountIdcardEffectBegin());
        originMchModifyData.setSettAccountIdcardEffectEnd(mchModifyData.getSettAccountIdcardEffectEnd());

        return new MutablePair<>(resultModifyApplyment, resultMchApplyment);
    }

    @Override
    public MutablePair<MchModifyApplyment, MchApplyment> localModifyRate(MutablePair<MchModifyApplyment, MchApplyment> mchDataPair) {
        return null;
    }

    @Override
    public MutablePair<MchModifyApplyment, MchApplyment> syncChannelModifyBase(MutablePair<MchModifyApplyment, MchApplyment> mchDataPair) {
        throw new BizException("暂不支持该操作");
//        MchModifyApplyment modifyApplyment = mchDataPair.getLeft();
//        MchApplyment mchApplyment = mchDataPair.getRight();
//
//        KqpayApplymentInfo kqpayApplymentInfo = JSON.parseObject(mchApplyment.getApplyDetailInfo(), KqpayApplymentInfo.class);
//
//        JSONObject param = new JSONObject();
//        param.fluentPut("operator", "admin")
//                .fluentPut("subBillAccount", kqpayApplymentInfo.getContactEmail());
//
//        // 套餐信息
//        JSONObject packageInfo = new JSONObject();
//        param.put("packageInfo", packageInfo);
//        packageInfo.put("packageCode", KqpayConst.Package.COMPANY_BASE_EDIT.getCode());
//
//        String openAccountWillingnessLetter = "https://syb-jq-public.oss-cn-hangzhou.aliyuncs.com/applyment/38835122-55b6-48be-884e-35e4aa856b99.jpg";
//
//        KqpayIsvParams isvParams = (KqpayIsvParams) configContextQueryService.queryIsvParams(mchApplyment);
//        String openAccountWillingnessLetterFssId = KqpayKit.uploadRequest(openAccountWillingnessLetter, isvParams);
//
//        List<Object> additionList = new ArrayList<>();
//        param.put("additionList", additionList);
//        Map<String, Object> addition = new HashMap<>();
//        additionList.add(addition);
//        addition.put("additionFssId", openAccountWillingnessLetterFssId);
//        addition.put("additionFileType", "OPEN_ACCOUNT_WILLINGNESS_LETTER");
//        addition.put("additionRemark", "开户意愿确认函");
//        addition.put("extName", "jpg");
//
//        KqpayResp kqpayResp = KqpayKit.applymentRequest(KqpayConst.ReqMethod.BS005, isvParams, param);
//
//        return mchDataPair;
    }

    @Override
    public MutablePair<MchModifyApplyment, MchApplyment> syncChannelModifySettlement(MutablePair<MchModifyApplyment, MchApplyment> mchDataPair) {
        MchModifyApplyment resultModifyApplyment = new MchModifyApplyment();
        MchApplyment resultMchApplyment = new MchApplyment();

        MchModifyApplyment modifyApplyment = mchDataPair.getLeft();
        resultModifyApplyment.setModifyApplyId(modifyApplyment.getModifyApplyId());
        MchApplyment mchApplyment = mchDataPair.getRight();
        resultMchApplyment.setApplyId(mchApplyment.getApplyId());

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

        KqpayApplymentInfo kqpayApplymentInfo = JSON.parseObject(mchApplyment.getApplyDetailInfo(), KqpayApplymentInfo.class);

        MchModifyApplymentModel modifyApplyBiz = JSON.parseObject(modifyApplyment.getApplyDetailInfo(), MchModifyApplymentModel.class);

        JSONObject param = new JSONObject();
        param.fluentPut("operator", "admin")
                .fluentPut("subBillAccount", kqpayApplymentInfo.getContactEmail());

        // 套餐信息
        JSONObject packageInfo = new JSONObject();
        param.put("packageInfo", packageInfo);
        packageInfo.put("packageCode", KqpayConst.Package.COMPANY_BASE_EDIT.getCode());

        JSONObject packageParam = new JSONObject();
        packageInfo.put("packageParameter", packageParam);
        // 定向付款信息域
        JSONObject settlementInfo = new JSONObject();
        packageParam.put("packageParam", settlementInfo);
        settlementInfo.put("bankMobilePhone", modifyApplyBiz.getPhone());
        if (modifyApplyBiz.getSettAccountType().equals("B")) {
            settlementInfo.put("accountType", "0");
        } else {
            if (modifyApplyBiz.getIllegal().equals("Y")) {
                settlementInfo.put("accountType", "2");
            } else {
                settlementInfo.put("accountType", "1");
            }
        }
        settlementInfo.put("accountNo", modifyApplyBiz.getSettAccountNo());
        settlementInfo.put("accountName", modifyApplyBiz.getSettAccountName());
        settlementInfo.put("bankName", modifyApplyBiz.getSettAccountBankName());
        settlementInfo.put("bankBranch", modifyApplyBiz.getSettAccountBankBranchName());
        Assert.notNull(modifyApplyBiz.getSettAccountBankBranchAreaCode(), "支行地区编码信息不能为空");
        Assert.isTrue(modifyApplyBiz.getSettAccountBankBranchAreaCode().size() >= 2, "支行地区编码信息不能为空");
        settlementInfo.put("areaCode", modifyApplyBiz.getSettAccountBankBranchAreaCode().getString(1));

        if (kqpayApplymentInfo.getMerchantType() != MchApplyment.MERCHANT_TYPE_PERSONAL) {
            JSONObject accOpenInfo = new JSONObject();
            packageParam.put("accOpenInfo", accOpenInfo);
            String accOpenFssId = KqpayKit.uploadRequest(modifyApplyBiz.getAccOpenCertImg(), isvParams);
        }

        if (modifyApplyBiz.getIllegal().equals("Y")) {
            JSONObject authorizerInfo = new JSONObject();
            packageParam.put("authorizerInfo", authorizerInfo);
            String authFssId = KqpayKit.uploadRequest(modifyApplyBiz.getNonLegSettleAuthPic(), isvParams);
            authorizerInfo.put("authFssId", authFssId);
            String idCard1Img = KqpayKit.uploadRequest(modifyApplyBiz.getSettAccountIdcard1Img(), isvParams);
            authorizerInfo.put("authNationalFssId", idCard1Img);
            String idCard2Img = KqpayKit.uploadRequest(modifyApplyBiz.getSettAccountIdcard2Img(), isvParams);
            authorizerInfo.put("authPersonFssId", idCard2Img);
            authorizerInfo.put("beginDate", modifyApplyBiz.getSettAccountIdcardEffectBegin());
            authorizerInfo.put("expireDate", modifyApplyBiz.getSettAccountIdcardEffectEnd());
            authorizerInfo.put("authIdCard", modifyApplyBiz.getSettAccountIdcardNo());
            authorizerInfo.put("authTel", modifyApplyBiz.getPhone());
            authorizerInfo.put("authName", modifyApplyBiz.getSettAccountName());
            String authHandFssId = KqpayKit.uploadRequest(modifyApplyBiz.getAuthHandImg(), isvParams);
            authorizerInfo.put("authHandFssId", authHandFssId);
        }

        try {
            KqpayResp kqpayResp = KqpayKit.applymentRequest(KqpayConst.ReqMethod.BS005, isvParams, param);
            JSONObject responseBody = kqpayResp.getResponseBody();
            String bizResponseCode = responseBody.getString("bizResponseCode");
            String bizResponseMessage = responseBody.getString("bizResponseMessage");

            resultModifyApplyment.setChannelVar1(responseBody.toJSONString());

            if (!KqpayConst.SUCCESS.equals(bizResponseCode)) {
                resultModifyApplyment.setApplyDetailInfo("[" + bizResponseMessage + "]");

                resultModifyApplyment.setState(MchApplyment.STATE_REJECT_WAIT_MODIFY);
                return new MutablePair<>(resultModifyApplyment, null);
            }

            String orderId = responseBody.getString("orderId");
            resultModifyApplyment.setChannelApplyNo(orderId);
            resultModifyApplyment.setState(MchApplyment.STATE_AUDITING);

            return new MutablePair<>(resultModifyApplyment, null);

        } catch (Exception e) {
            resultModifyApplyment.setApplyDetailInfo("[" + e.getMessage() + "]");
            resultModifyApplyment.setState(MchApplyment.STATE_REJECT_WAIT_MODIFY);

            return new MutablePair<>(resultModifyApplyment, null);
        }
    }

    @Override
    public MutablePair<MchModifyApplyment, MchApplyment> syncChannelModifyRate(MutablePair<MchModifyApplyment, MchApplyment> mchDataPair) {
        return null;
    }

    @Override
    public MutablePair<MchModifyApplyment, MchApplyment> syncChannelModifySettlementType(MutablePair<MchModifyApplyment, MchApplyment> mchDataPair) {
        return null;
    }

    @Override
    public MutablePair<MchModifyApplyment, MchApplyment> queryModifyResult(MutablePair<MchModifyApplyment, MchApplyment> mchDataPair) {
        MchModifyApplyment resultMchModifyApplyment = mchDataPair.left;
        MchApplyment resultMch = mchDataPair.right;

        KqpayIsvParams isvParams = (KqpayIsvParams) configContextQueryService.queryIsvParams(mchDataPair.right);

        JSONObject reqParam = new JSONObject();
        reqParam.put("orderId", resultMchModifyApplyment.getChannelApplyNo());
        KqpayResp kqpayResp = KqpayKit.applymentRequest(KqpayConst.ReqMethod.BS002, isvParams, reqParam);
        JSONObject responseBody = kqpayResp.getResponseBody();
        String bizResponseCode = responseBody.getString("bizResponseCode");
        String bizResponseMessage = responseBody.getString("bizResponseMessage");


        if (!KqpayConst.SUCCESS.equals(bizResponseCode)) {
            log.info("快钱查询商户变更审核状态失败, {}", bizResponseMessage);

            return new MutablePair<>();
        }

        String status = responseBody.getString("status");

        if ("FINISHED".equals(status)) {
            return localModifySettlement(mchDataPair);
        }

        return new MutablePair<>();
    }
}
