package com.hfkj.schedule;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.hfkj.channel.lakala.LaKaLaLedgerService;
import com.hfkj.channel.saas.SaasMerService;
import com.hfkj.channel.weixin.WeiXinMerService;
import com.hfkj.common.exception.ErrorCode;
import com.hfkj.common.exception.ErrorHelp;
import com.hfkj.common.exception.SysCode;
import com.hfkj.entity.*;
import com.hfkj.service.*;
import com.hfkj.sysenum.*;
import lombok.SneakyThrows;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.util.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.Scheduled;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * @className: Mer
 * @author: HuRui
 * @date: 2022/12/4
 **/
@Configuration
public class Merchant {

    private static final Logger log = LoggerFactory.getLogger(Merchant.class);

    @Resource
    private BsMerService merService;

    @Resource
    private BsStoreService storeService;

    @Resource
    private BsMerContractRecordService merContractRecordService;

    @Resource
    private BsMerPlatformNoService merPlatformNoService;

    @Resource
    private BsMerPlatformTermService merPlatformTermService;

    @Resource
    private BsMerContractRecordMsgService merContractRecordMsgService;

    @Resource
    private BsMerSettleAcctApplyService merSettleAcctApplyService;
    @Resource
    private BsMerSettleAcctService merSettleAcctService;
    @Resource
    private BsMerRateApplyService merRateApplyService;
    @Resource
    private BsMerRateService merRateService;
    @Resource
    private SaasMerService saasMerService;
    @Resource
    private BsMerLedgerService merLedgerService;
    @Resource
    private LaKaLaLedgerService laKaLaLedgerService;


    /**
     * 审批状态查询
     */
/*    @SneakyThrows
    @Scheduled(cron="0 0/1 * * * ?")   //每1分钟执行一次
    public void applyment() {
        Map<String, Object> param = new HashMap<>();
        param.put("status", 1);
        List<BsMerContractRecord> list = merContractRecordService.getContractRecordList(param);
        for (BsMerContractRecord contractRecord : list) {
            try {

                BsMer mer = merService.getMer(contractRecord.getMerId());
                if (mer != null && mer.getMerStatus().equals(MerStatusEnum.status3.getNumber())) {

                    // 查询申请记录
                    JSONObject applyment = weiXinMerService.getApplyment(contractRecord.getOrderNo());
                    BsMerContractRecordMsg msg = new BsMerContractRecordMsg();
                    msg.setOrderNo(contractRecord.getOrderNo());
                    msg.setType(1);
                    msg.setResponseContent(applyment.toJSONString());
                    merContractRecordMsgService.insertRecordMsg(msg);

                    if (applyment != null) {
                    *//*1、APPLYMENT_STATE_EDITTING（编辑中）：提交申请发生错误导致，请尝试重新提交。
                    2、APPLYMENT_STATE_AUDITING（审核中）：申请单正在审核中，超级管理员用微信打开“签约链接”，完成绑定微信号后，申请单进度将通过微信公众号通知超级管理员，引导完成后续步骤。
                    3、APPLYMENT_STATE_REJECTED（已驳回）：请按照驳回原因修改申请资料，超级管理员用微信打开“签约链接”，完成绑定微信号，后续申请单进度将通过微信公众号通知超级管理员。
                    4、APPLYMENT_STATE_TO_BE_CONFIRMED（待账户验证）：请超级管理员使用微信打开返回的“签约链接”，根据页面指引完成账户验证。
                    5、APPLYMENT_STATE_TO_BE_SIGNED（待签约）：请超级管理员使用微信打开返回的“签约链接”，根据页面指引完成签约。
                    6、APPLYMENT_STATE_SIGNING（开通权限中）：系统开通相关权限中，请耐心等待。
                    7、APPLYMENT_STATE_FINISHED（已完成）：商户入驻申请已完成。
                    8、APPLYMENT_STATE_CANCELED（已作废）：申请单已被撤销。*//*
                    String applymentState = applyment.getString("applyment_state");
                    if (applymentState.equals("APPLYMENT_STATE_FINISHED")) {
                        contractRecord.setStatus(2);
                        merContractRecordService.updateRecord(contractRecord);

                        mer.setMerStatus(MerStatusEnum.status1.getNumber());
                        merService.editMer(mer);

                        List<BsStore> storeList = storeService.getStoreByMerId(mer.getId(), StoreCreateTypeEnum.type1);
                        if (storeList.size() > 0) {
                            BsStore store = storeList.get(0);
                            store.setStatus(StoreStatusEnum.status2.getNumber());
                            storeService.editStore(store);
                        }

                        BsMerPlatformNo merPlatformNo = new BsMerPlatformNo();
                        merPlatformNo.setMerId(mer.getId());
                        merPlatformNo.setMerNo(mer.getMerNo());
                        merPlatformNo.setPlatformType(PlatformTypeEnum.type4.getNumber());
                        merPlatformNo.setPlatformNo(applyment.getString("sub_mchid"));
                        merPlatformNoService.editMerPlatformNo(merPlatformNo);

                        BsMerContractRecordMsg merContractRecordMsg = new BsMerContractRecordMsg();
                        merContractRecordMsg.setOrderNo(contractRecord.getOrderNo());
                        merContractRecordMsg.setType(1);
                        merContractRecordMsg.setResponseCode("成功");
                        merContractRecordMsg.setResponseMsg("");
                        merContractRecordMsg.setResponseMsg(applyment.toJSONString());
                        merContractRecordMsgService.insertRecordMsg(merContractRecordMsg);

                        // 已作废
                    } else if (applymentState.equals("APPLYMENT_STATE_CANCELED")) {
                        contractRecord.setStatus(4);
                        merContractRecordService.updateRecord(contractRecord);

                        mer.setMerStatus(MerStatusEnum.status4.getNumber());
                        merService.editMer(mer);

                        JSONObject auditDetail = applyment.getJSONObject("audit_detail");
                        BsMerContractRecordMsg merContractRecordMsg = new BsMerContractRecordMsg();
                        merContractRecordMsg.setOrderNo(contractRecord.getOrderNo());
                        merContractRecordMsg.setType(1);
                        merContractRecordMsg.setResponseCode(auditDetail.getString("field"));
                        merContractRecordMsg.setResponseMsg(auditDetail.getString("reject_reason"));
                        merContractRecordMsg.setResponseMsg(applyment.toJSONString());
                        merContractRecordMsgService.insertRecordMsg(merContractRecordMsg);

                        // 已驳回
                    } else if (applymentState.equals("APPLYMENT_STATE_REJECTED")) {
                        contractRecord.setStatus(3);
                        merContractRecordService.updateRecord(contractRecord);

                        mer.setMerStatus(MerStatusEnum.status4.getNumber());
                        merService.editMer(mer);

                        JSONArray auditDetailList = applyment.getJSONArray("audit_detail");
                        for (Object obj : auditDetailList) {
                            JSONObject auditDetail = (JSONObject) obj;
                            BsMerContractRecordMsg merContractRecordMsg = new BsMerContractRecordMsg();
                            merContractRecordMsg.setOrderNo(contractRecord.getOrderNo());
                            merContractRecordMsg.setType(1);
                            merContractRecordMsg.setResponseCode(auditDetail.getString("field"));
                            merContractRecordMsg.setResponseMsg(auditDetail.getString("reject_reason"));
                            merContractRecordMsg.setResponseMsg(applyment.toJSONString());
                            merContractRecordMsgService.insertRecordMsg(merContractRecordMsg);
                        }
                    }
                }
            }

            } catch (Exception e) {

            }
        }

    }*/


    /**
     * 审批状态查询
     */
    @SneakyThrows
    @Scheduled(cron="0 0/1 * * * ?")   //每1分钟执行一次
    public void lklSaasApplyment() {
        Map<String, Object> param = new HashMap<>();
        param.put("status", 1);
        List<BsMerContractRecord> list = merContractRecordService.getContractRecordList(param);
        for (BsMerContractRecord contractRecord : list) {
            try {
                BsMer mer = merService.getMer(contractRecord.getMerId());
                if (mer != null) {
                    if (contractRecord.getPlatformType().equals(PlatformTypeEnum.type1.getNumber())) {
                        BsMerPlatformNo platform = merPlatformNoService.getPlatformNo(mer.getId(), PlatformTypeEnum.type1, MerPlatformNoStatusEnum.status2);
                        if (platform != null) {
                            JSONObject merchantInfo = saasMerService.merchantInfo(platform.getPlatformNo());
                            // 查询申请记录
                            BsMerContractRecordMsg msg = new BsMerContractRecordMsg();
                            msg.setOrderNo(contractRecord.getOrderNo());
                            msg.setType(1);
                            msg.setResponseContent(merchantInfo.toJSONString());
                            merContractRecordMsgService.insertRecordMsg(msg);

                            JSONObject customer = merchantInfo.getJSONObject("customer");
                            // 商户状态 OPEN:开通，CLOSE:关闭，LOSS:流失, REJECT：拒绝。可用值:OPEN,ACTIVITY,WAIT_COMMIT,WAIT_AUDI,REJECT, CLOSE,INIT
                            if (customer.getString("customerStatus").equals("OPEN")) {
                                contractRecord.setStatus(2);
                                merContractRecordService.updateRecord(contractRecord);

                                mer.setMerStatus(MerStatusEnum.status1.getNumber());
                                merService.editMer(mer);

                                List<BsStore> storeList = storeService.getStoreByMerId(mer.getId(), StoreCreateTypeEnum.type1);
                                if (storeList.size() > 0) {
                                    BsStore store = storeList.get(0);
                                    store.setStatus(StoreStatusEnum.status2.getNumber());
                                    storeService.editStore(store);
                                }
                                platform.setStatus(MerPlatformNoStatusEnum.status1.getNumber());
                                platform.setCupNo(customer.getString("externalCustomerNo"));
                                merPlatformNoService.editMerPlatformNo(platform);

                                // 终端信息
                                BsMerPlatformTerm term = new BsMerPlatformTerm();
                                term.setMerPlatformNoId(platform.getId());
                                term.setMerId(platform.getMerId());
                                term.setActiveNo(customer.getString("activeNo"));
                                term.setBusiTypeCode(customer.getString("bzPos"));
                                term.setBusiTypeName("码牌");
                                term.setProductCode(customer.getString("bzPos"));
                                term.setProductName("码牌");
                                term.setTermNo(customer.getString("termNo"));
                                merPlatformTermService.editMerPlatformTerm(term);

                                JSONArray terminalList = merchantInfo.getJSONArray("terminalInfo");
                                for (Object terminalObj : terminalList) {
                                    JSONObject terminal = (JSONObject) terminalObj;
                                    // 终端编号
                                    JSONArray termNoList = terminal.getJSONArray("termNoList");
                                    for (Object termNo : termNoList) {
                                        term = new BsMerPlatformTerm();
                                        term.setMerPlatformNoId(platform.getId());
                                        term.setMerId(platform.getMerId());
                                        term.setActiveNo(customer.getString("activeNo"));
                                        term.setBusiTypeCode(terminal.getString("termTypeCode"));
                                        term.setBusiTypeName(terminal.getString("termTypeName"));
                                        term.setProductCode(terminal.getString("termTypeCode"));
                                        term.setProductName(terminal.getString("termTypeName"));
                                        term.setTermId(terminal.getString("coreTermId"));
                                        term.setTermNo(termNo.toString());
                                        merPlatformTermService.editMerPlatformTerm(term);
                                    }
                                }

                                BsMerPlatformNo merPlatform = merPlatformNoService.getPlatformNo(mer.getId(), PlatformTypeEnum.type1);

                                BsMerLedger merLedger = merLedgerService.getMerLedger(mer.getId(), PlatformTypeEnum.type1);
                                if (merLedger == null) {
                                    merLedger = new BsMerLedger();
                                    merLedger.setMerId(mer.getId());
                                    merLedger.setMerName(mer.getMerName());
                                    merLedger.setPlatformType(merPlatform.getPlatformType());
                                    merLedger.setPlatformNo(merPlatform.getPlatformNo());
                                    merLedger.setCupNo(merPlatform.getCupNo());
                                    merLedger.setStatus(MerLedgerStatusEnum.status4.getNumber());
                                    merLedger.setReceiverStatus(false);
                                    merLedgerService.editMerLedger(merLedger);

                                    laKaLaLedgerService.applyLedgerReceiver(merLedger.getMerId());
                                }
                            } else if (customer.getString("customerStatus").equals("REJECT")) {

                                contractRecord.setStatus(3);
                                merContractRecordService.updateRecord(contractRecord);

                                if (!mer.getMerStatus().equals(MerStatusEnum.status1.getNumber())) {
                                    mer.setMerStatus(MerStatusEnum.status4.getNumber());
                                    merService.editMer(mer);
                                }

                                platform.setStatus(MerPlatformNoStatusEnum.status3.getNumber());
                                platform.setSuggestionReject(customer.getString("auditRemark"));
                                merPlatformNoService.editMerPlatformNo(platform);

                                BsMerContractRecordMsg merContractRecordMsg = new BsMerContractRecordMsg();
                                merContractRecordMsg.setOrderNo(contractRecord.getOrderNo());
                                merContractRecordMsg.setType(1);
                                merContractRecordMsg.setResponseCode(customer.getString("customerStatus"));
                                merContractRecordMsg.setResponseMsg(customer.getString("auditRemark"));
                                merContractRecordMsgService.insertRecordMsg(merContractRecordMsg);
                            }
                        }
                    }
                }
            } catch (Exception e) {

            }
        }

    }

    /**
     * 修改结算审批查询并更新
     */
    @SneakyThrows
    @Scheduled(cron="0 0/1 * * * ?")   //每1分钟执行一次
    public void lklSettleAcctApply() {
        Map<String, Object> param = new HashMap<>();
        param.put("applyNoIsNotNull", true);
        param.put("status", MerSettleAcctApplyStatus.status5.getNumber());
        List<BsMerSettleAcctApply> applyList = merSettleAcctApplyService.getApplyList(param);
        for (BsMerSettleAcctApply merSettleAcctApply : applyList) {
            try {
                JSONObject responseObj = saasMerService.updateReview(merSettleAcctApply.getApplyNo());
                if (responseObj != null) {
                    if (responseObj.getString("reviewPass").equals("PASS")) {

                        BsMerSettleAcct settle = merSettleAcctService.getMerSettleByMerId(merSettleAcctApply.getMerId());
                        if (settle != null) {
                            settle.setStatus(0);
                            merSettleAcctService.editMerSettleAcct(settle);
                        }

                        BsMerSettleAcct newSettle = new BsMerSettleAcct();
                        newSettle.setMerId(merSettleAcctApply.getMerId());
                        newSettle.setSettleType(merSettleAcctApply.getSettleType());
                        newSettle.setBankCardImg(merSettleAcctApply.getBankCardImg());
                        newSettle.setBankName(merSettleAcctApply.getBankName());
                        newSettle.setBankCardNo(merSettleAcctApply.getBankCardNo());
                        newSettle.setBankCardHolder(merSettleAcctApply.getBankCardHolder());

                        newSettle.setOpenningBankCityCode(merSettleAcctApply.getOpenningBankCityCode());
                        newSettle.setOpenningBankCityName(merSettleAcctApply.getOpenningBankCityName());
                        newSettle.setOpenningBankAreaCode(merSettleAcctApply.getOpenningBankAreaCode());
                        newSettle.setOpenningBankAreaName(merSettleAcctApply.getOpenningBankAreaName());
                        newSettle.setOpenningBankProvinceCode(merSettleAcctApply.getOpenningBankProvinceCode());
                        newSettle.setOpenningBankProvinceName(merSettleAcctApply.getOpenningBankProvinceName());
                        newSettle.setOpenningBankCode(merSettleAcctApply.getOpenningBankCode());
                        newSettle.setOpenningBankName(merSettleAcctApply.getOpenningBankName());
                        newSettle.setOpenningBankLicenseUrl(merSettleAcctApply.getOpenningBankLicenseUrl());
                        newSettle.setClearingBankCode(merSettleAcctApply.getClearingBankCode());

                        newSettle.setSettleIdCardName(merSettleAcctApply.getSettleIdCardName());
                        newSettle.setSettleIdCardNo(merSettleAcctApply.getSettleIdCardNo());
                        newSettle.setSettleIdCardAddress(merSettleAcctApply.getSettleIdCardAddress());
                        newSettle.setSettleIdCardPortraitImg(merSettleAcctApply.getSettleIdCardPortraitImg());
                        newSettle.setSettleIdCardNationalEmblemImg(merSettleAcctApply.getSettleIdCardNationalEmblemImg());
                        newSettle.setSettleIdPeriodType(merSettleAcctApply.getSettleIdPeriodType());
                        newSettle.setSettleIdCardPeriodStart(merSettleAcctApply.getSettleIdCardPeriodStart());
                        newSettle.setSettleIdCardPeriodEnd(merSettleAcctApply.getSettleIdCardPeriodEnd());
                        merSettleAcctService.editMerSettleAcct(newSettle);

                        merSettleAcctApply.setStatus(MerSettleAcctApplyStatus.status3.getNumber());
                        merSettleAcctApplyService.editData(merSettleAcctApply);

                        BsMerLedger ledger = merLedgerService.getMerLedger(merSettleAcctApply.getMerId(), PlatformTypeEnum.type1);
                        if (ledger != null) {
                            ledger.setStatus(MerLedgerStatusEnum.status0.getNumber());
                            merLedgerService.editMerLedger(ledger);

                        } else {
                            BsMerPlatformNo merPlatform = merPlatformNoService.getPlatformNo(merSettleAcctApply.getMerId(), PlatformTypeEnum.type1);
                            BsMerLedger merLedger = new BsMerLedger();
                            merLedger.setMerId(merSettleAcctApply.getMerId());
                            merLedger.setMerName(merSettleAcctApply.getMerName());
                            merLedger.setPlatformType(merPlatform.getPlatformType());
                            merLedger.setPlatformNo(merPlatform.getPlatformNo());
                            merLedger.setCupNo(merPlatform.getCupNo());
                            merLedger.setStatus(MerLedgerStatusEnum.status2.getNumber());
                            merLedger.setReceiverStatus(false);
                            merLedgerService.editMerLedger(merLedger);
                            laKaLaLedgerService.applyLedgerReceiver(merLedger.getMerId());
                        }

                    } else if (responseObj.getString("reviewPass").equals("UNPASS")) {
                        merSettleAcctApply.setStatus(MerSettleAcctApplyStatus.status6.getNumber());
                        merSettleAcctApply.setRejectReason(responseObj.getString("reviewResult"));
                        merSettleAcctApplyService.editData(merSettleAcctApply);
                    }
                }
            } catch (Exception e) {

            }
        }
    }

    /**
     * 修改费率审批查询并更新
     */
    @SneakyThrows
    @Scheduled(cron="0 0/1 * * * ?")   //每1分钟执行一次
    public void lklRateApply() {
        Map<String, Object> param = new HashMap<>();
        param.put("status", MerRateApplyStatusEnum.status5.getNumber());
        List<BsMerRateApply> rateApplyList = merRateApplyService.getRateApplyList(param);
        for (BsMerRateApply rateApply : rateApplyList) {
            if (StringUtils.isNotBlank(rateApply.getApplyNo())) {

                JSONObject responseObj = saasMerService.updateReview(rateApply.getApplyNo());
                if (responseObj != null) {
                    if (responseObj.getString("reviewPass").equals("PASS")) {
                        rateApply.setStatus(MerRateApplyStatusEnum.status3.getNumber());
                        merRateApplyService.editData(rateApply);

                        // 旧费率 作废
                        List<BsMerRate> oldMerRateList = merRateService.getRateListByMerId(rateApply.getMerId());
                        for (BsMerRate merRate : oldMerRateList) {
                            merRate.setStatus(0);
                            merRateService.editMerRate(merRate);
                        }

                        // 生成新费率
                        List<BsMerRateApplyDetail> merRateApplyDetailList = merRateApplyService.getRateApplyDetailListByApply(rateApply.getId());
                        for (BsMerRateApplyDetail rateApplyDetail : merRateApplyDetailList) {
                            BsMerRate newMerRate = new BsMerRate();
                            newMerRate.setMerId(rateApply.getMerId());
                            newMerRate.setMerNo(rateApply.getMerNo());
                            newMerRate.setRateTypeCode(rateApplyDetail.getRateTypeCode());
                            newMerRate.setRateTypeName(rateApplyDetail.getRateTypeName());
                            newMerRate.setRateSaasTypeCode(rateApplyDetail.getRateSaasTypeCode());
                            newMerRate.setRatePct(rateApplyDetail.getRatePct());
                            newMerRate.setStatus(1);
                            merRateService.editMerRate(newMerRate);
                        }

                    } else if (responseObj.getString("reviewPass").equals("UNPASS")) {
                        rateApply.setStatus(MerRateApplyStatusEnum.status6.getNumber());
                        rateApply.setRejectReason(responseObj.getString("reviewResult"));
                        merRateApplyService.editData(rateApply);
                    }
                }
            }
        }
    }

}
