package com.gree.mall.manager.logic.settle.repair;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.thread.ThreadUtil;
import com.gree.mall.manager.bean.admin.AdminUserCom;
import com.gree.mall.manager.bean.settle.repair.DailyWokerBankCardMonthBean;
import com.gree.mall.manager.bean.settle.repair.DailyWorkerBankCardBean;
import com.gree.mall.manager.bean.settle.repair.cmc.BankCardInfoBean;
import com.gree.mall.manager.bean.settle.repair.cmc.PayItem;
import com.gree.mall.manager.bean.settle.repair.cmc.ReceivedItem;
import com.gree.mall.manager.commonmapper.DailyMapper;
import com.gree.mall.manager.constant.DailyConstant;
import com.gree.mall.manager.exception.RemoteServiceException;
import com.gree.mall.manager.logic.common.CommonLogic;
import com.gree.mall.manager.logic.settle.repair.cmc.CmcBankLogic;
import com.gree.mall.manager.plus.entity.*;
import com.gree.mall.manager.plus.service.*;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;

@Service
@Slf4j
@RequiredArgsConstructor
public class DailyTransferLogic {

    private final SettleDailyIssueTaskService settleDailyIssueTaskService;
    private final SettleDailyBankCardBalanceService settleDailyBankCardBalanceService;
    private final SettleDailyIssueSummaryMonthRecordService settleDailyIssueSummaryMonthRecordService;
    private final SettleDailyIssueSummaryRecordService settleDailyIssueSummaryRecordService;
    private final SettleDailyBankTransferRecordService settleDailyBankTransferRecordService;
    private final DailyMapper dailyMapper;
    private final CmcBankLogic cmcBankLogic;
    private final CommonLogic commonLogic;

    @Transactional
    public List<String> issueCheck(String summaryBatchNo, List<String> summaryNumberList, boolean isMonth, AdminUserCom adminUser) {
        Integer count = settleDailyIssueTaskService.lambdaQuery()
                .eq(SettleDailyIssueTask::getSummaryBatchNo, summaryBatchNo)
                .eq(SettleDailyIssueTask::getTaskStatus, 1)
                .in(summaryNumberList != null && summaryNumberList.size() > 0, SettleDailyIssueTask::getSummaryNumber, summaryNumberList)
                .count();
        if (count > 0) {
            throw new RemoteServiceException("当前汇总批次号已发放,请勿重复执行。");
        }

        //任务发发放表
        List<SettleDailyIssueTask> list = new ArrayList<>();
        if (CollectionUtil.isEmpty(summaryNumberList)) {
            summaryNumberList = new ArrayList<>();
            List<Map<String, Object>> summaryMap;
            if (isMonth) {
                summaryMap = dailyMapper.querySummaryMonthNumber(adminUser.getAdminCompanyWechat().getCompanyWechatId(), summaryBatchNo);
            } else {
                summaryMap = dailyMapper.querySummaryNumber(adminUser.getAdminCompanyWechat().getCompanyWechatId(), summaryBatchNo);
            }

            if (CollectionUtil.isEmpty(summaryMap)) {
                throw new RemoteServiceException("没有找到可执行结算单位。");
            }
            for (Map item : summaryMap) {
                summaryNumberList.add(item.get("summaryNumber").toString());
            }
        }

        if (CollectionUtil.isEmpty(summaryNumberList)) {
            throw new RemoteServiceException("没有可结算的单位");
        }

        for (String item : summaryNumberList) {
            SettleDailyIssueTask issueTask = new SettleDailyIssueTask();
            issueTask.setTaskStatus(1);
            issueTask.setSummaryBatchNo(summaryBatchNo);
            issueTask.setSummaryNumber(item);
            issueTask.setIsMonth(isMonth);
            issueTask.setCompanyWechatId(adminUser.getAdminCompanyWechat().getCompanyWechatId());
            issueTask.setCompanyWechatName(adminUser.getAdminCompanyWechat().getCompanyName());
            list.add(issueTask);
        }
        settleDailyIssueTaskService.saveBatch(list);
        return summaryNumberList;
    }

    /**
     * 工资发放 (异步)
     */
    @Transactional(rollbackFor = Exception.class)
    public void issueSalary(String summaryBatchNo, List<String> summaryNumberList, Boolean isMonth, AdminUserCom adminUser) {
        String opName = adminUser.getNickName();
        ThreadUtil.execute(() -> {
            for (String summaryNumber : summaryNumberList) {
                if (isMonth) {
                    issueMonthBySummaryNumber(summaryBatchNo, summaryNumber, opName, adminUser);
                } else {
                    issueBySummaryNumber(summaryBatchNo, summaryNumber, opName, adminUser);
                }
            }
        });
    }

    @Transactional
    public void issueMonthBySummaryNumber(String summaryBatchNo, String summaryNumber, String opName, AdminUserCom adminUser) {
        //查询当前账号授权列表
        try {
            //查询结算单位对应银行授权账号
            SettleDailyBankCardBalance authBankCard = settleDailyBankCardBalanceService.lambdaQuery()
                    .eq(SettleDailyBankCardBalance::getCompanyWechatId, adminUser.getAdminCompanyWechat().getCompanyWechatId())
                    .eq(SettleDailyBankCardBalance::getSummaryNumber, summaryNumber)
                    .one();
            if (authBankCard == null) {
                deleteTask(summaryBatchNo, summaryNumber);
                log.warn("查询授权账号失败");
                return;
            }
            String bankCardId = authBankCard.getBankCardId();
            String bankCardCode = authBankCard.getOpenBankOrgId();

            List<BankCardInfoBean> beans = new ArrayList<>();
            beans.add(new BankCardInfoBean(bankCardId, bankCardCode, "2", null));

            String authBankId = authBankCard.getAuthAccountId();

            //查询协议
            Map<String, Object> protocolMap = cmcBankLogic.queryProtocol(new BankCardInfoBean(bankCardId, bankCardCode, null, authBankId), summaryNumber);
            if (DailyConstant.CMC_RESPONSE_FAIL_CODE.equals(protocolMap.get("code").toString())) {
                deleteTask(summaryBatchNo, summaryNumber);
                log.warn("查询授协议失败");
                return;
            }
            List<Map<String, Object>> protocolList = (List<Map<String, Object>>) protocolMap.get("data");
            String protocolStr = protocolList.get(0).get("cnvnbr").toString();
            String ccynbrStr = protocolList.get(0).get("ccynbr").toString();
            String bustypStr = protocolList.get(0).get("bustyp").toString();

            //查询列表
            List<DailyWokerBankCardMonthBean> bankList = dailyMapper.queryIssueSalaryMonthBankCardInfo(summaryBatchNo, summaryNumber, DailyConstant.ISSUE_STATUS_NOT, adminUser.getAdminCompanyWechat().getCompanyWechatId());
            if (bankList == null || bankList.size() == 0) {
                log.warn("没有可发放数据");
                deleteTask(summaryBatchNo, summaryNumber);
                return;
            }

            List<SettleDailyIssueSummaryMonthRecord> issueSummaryRecords = new ArrayList<>();
            String queryDate = DateUtil.format(new Date(), "yyyyMMdd");
            List<ReceivedItem> receiveList = new ArrayList<>();
            BigDecimal totalIssueCost = bankList.stream().map(DailyWokerBankCardMonthBean::getMonthSendCost).reduce(BigDecimal.ZERO, BigDecimal::add);
            PayItem payItem = new PayItem();

            String issueBatchNo = commonLogic.generateNo("FF", "issueBatchNo", 15);
            // 金额大于0才发放

            payItem.setTtlamt(totalIssueCost.toString());
            payItem.setTtlcnt(bankList.size() + "");
            payItem.setCuramt(totalIssueCost.toString());
            payItem.setCurcnt(bankList.size() + "");
            payItem.setCnvnbr(protocolStr);
            //BYBC 代发劳务收入BYBK 代发其他BYFN 代发奖金BYSA 代发工资BYTF 代发报销款
            payItem.setAgctyp(bustypStr);
            //10:人民币
            payItem.setCcynbr(ccynbrStr);
            //分行号
            payItem.setBbknbr(bankCardCode);
            payItem.setAccnbr(bankCardId);
            //授权账号
            payItem.setAutacc(authBankId);
            String reqNo = commonLogic.generateNo("cmc", "requstNo", 15);
            payItem.setYurref(reqNo);
            payItem.setEptdat(queryDate);
            payItem.setEpttim(DateUtil.format(new Date(), "HHmmss"));
            payItem.setTrsrmk("月结工资");

            for (DailyWokerBankCardMonthBean workBean : bankList) {
                if (workBean.getMonthSendCost() != null && workBean.getMonthSendCost().doubleValue() > 0) {
                    String itemReqNo = commonLogic.generateReqNo("1", "requstNo", 8);
                    String depositBank = workBean.getDepositBank();
                    String bankAddr = workBean.getBankAddr();
                    String isCmcBank = "N";
                    if (workBean.getDepositBank().contains("招商银行")) {
                        isCmcBank = "Y";
                        depositBank = "";
                        bankAddr = "";
                    }
                    ReceivedItem receivedItem = new ReceivedItem(
                            itemReqNo,
                            workBean.getBankAccount(),
                            workBean.getBankAccountName(),
                            workBean.getMonthSendCost().toString(),
                            isCmcBank,
                            depositBank,
                            bankAddr
                    );
                    receiveList.add(receivedItem);

                    SettleDailyIssueSummaryMonthRecord record = new SettleDailyIssueSummaryMonthRecord();
                    BeanUtils.copyProperties(workBean, record);
                    record.setRequestNo(itemReqNo);
                    record.setStatus(DailyConstant.ISSUE_STATUS_BANK_DO);
                    record.setIssueBy(opName);
                    record.setIssueTime(new Date());
                    record.setCompanyWechatId(adminUser.getAdminCompanyWechat().getCompanyWechatId());
                    record.setCompanyWechatName(adminUser.getAdminCompanyWechat().getCompanyName());
                    issueSummaryRecords.add(record);
                }
            }
            if (receiveList.size() == 0) {
                deleteTask(summaryBatchNo, summaryNumber);
                log.warn("kPay: 没有可转账的数据");
                return;
            }
            Map<String, Object> payMap = cmcBankLogic.insteadIssue(payItem, receiveList, summaryNumber);
            if (DailyConstant.CMC_RESPONSE_FAIL_CODE.equals(payMap.get("code").toString())) {
                deleteTask(summaryBatchNo, summaryNumber);
                return;
            }
            //拿到流程实例号
            List<Map<String, Object>> insteadIssueList = (List<Map<String, Object>>) payMap.get("data");
            String reqnbr = insteadIssueList.get(0).get("reqnbr").toString();

            //修改对应的状态为发放中
            settleDailyIssueSummaryMonthRecordService.updateBatchById(issueSummaryRecords, 500);
            //等待10S 查询转账转态
            //Thread.sleep(1000 * 10);
            Integer issueStatus = queryMonthTransferResult(issueSummaryRecords, bankList, reqnbr, queryDate, summaryNumber,
                    adminUser.getCompanyWechatId(), adminUser.getCompanyName());
            //记录单次记录
            saveCallApiRecord(issueBatchNo, totalIssueCost, issueStatus, opName, reqnbr, adminUser);
            settleDailyIssueTaskService.lambdaUpdate()
                    .set(SettleDailyIssueTask::getTaskStatus, 2)
                    .set(SettleDailyIssueTask::getRequestNo, reqnbr)
                    .eq(SettleDailyIssueTask::getCompanyWechatId, adminUser.getAdminCompanyWechat().getCompanyWechatId())
                    .eq(SettleDailyIssueTask::getSummaryNumber, summaryNumber)
                    .eq(SettleDailyIssueTask::getSummaryBatchNo, summaryBatchNo)
                    .update();
        } catch (Exception e) {
            deleteTask(summaryBatchNo, summaryNumber);
            log.info("【月结转账异常】 {} ", e);
        }

    }

    @Transactional
    public void issueBySummaryNumber(String summaryBatchNo, String summaryNumber, String opName, AdminUserCom adminUser) {
        //查询当前账号授权列表
        try {
            //查询结算单位对应银行授权账号
            SettleDailyBankCardBalance authBankCard = settleDailyBankCardBalanceService.lambdaQuery()
                    .eq(SettleDailyBankCardBalance::getCompanyWechatId, adminUser.getCompanyWechatId())
                    .eq(SettleDailyBankCardBalance::getSummaryNumber, summaryNumber)
                    .one();
            if (authBankCard == null) {
                deleteTask(summaryBatchNo, summaryNumber);
                log.warn("查询授权账号失败");
                //  throw new RemoteServiceException("查询授权账号失败");
                return;
            }


            String bankCardId = authBankCard.getBankCardId();
            String bankCardCode = authBankCard.getOpenBankOrgId();

//            List<BankCardInfoBean> beans = new ArrayList<>();
//            beans.add(new BankCardInfoBean(bankCardId, bankCardCode, "2", null));
//
//            Map<String, Object> authMap = cmcBankLogic.getAuthAccount(beans,summaryNumber);
//            if (DailyConstant.CMC_RESPONSE_FAIL_CODE.equals(authMap.get("code").toString())) {
//                deleteTask(summaryBatchNo,summaryNumber);
//                log.warn("查询授权账号失败");
//                //throw new RemoteServiceException("查询授权账号失败");
//                return;
//            }
//            //拿到授权账号
//            List<Map<String, Object>> authList = (List<Map<String, Object>>) authMap.get("data");
            String authBankId = authBankCard.getAuthAccountId();

            //查询协议
            Map<String, Object> protocolMap = cmcBankLogic.queryProtocol(new BankCardInfoBean(bankCardId, bankCardCode, null, authBankId), summaryNumber);
            if (DailyConstant.CMC_RESPONSE_FAIL_CODE.equals(protocolMap.get("code").toString())) {
                deleteTask(summaryBatchNo, summaryNumber);
                log.warn("查询授协议失败");
                //throw new RemoteServiceException("查询授协议失败");
                return;
            }
            List<Map<String, Object>> protocolList = (List<Map<String, Object>>) protocolMap.get("data");
            String protocolStr = protocolList.get(0).get("cnvnbr").toString();
            String ccynbrStr = protocolList.get(0).get("ccynbr").toString();
            String bustypStr = protocolList.get(0).get("bustyp").toString();

            //查询列表
            List<DailyWorkerBankCardBean> bankList = dailyMapper.queryIssueSalaryAndBankCardInfo(summaryBatchNo, summaryNumber, DailyConstant.ISSUE_STATUS_NOT, adminUser.getAdminCompanyWechat().getCompanyWechatId());

            List<SettleDailyIssueSummaryRecord> issueSummaryRecords = new ArrayList<>();
            String queryDate = DateUtil.format(new Date(), "yyyyMMdd");
            List<ReceivedItem> receiveList = new ArrayList<>();
            BigDecimal totalIssueCost = bankList.stream().map(DailyWorkerBankCardBean::getIssueCost).reduce(BigDecimal.ZERO, BigDecimal::add);
            PayItem payItem = new PayItem();

            String issueBatchNo = commonLogic.generateNo("FF", "issueBatchNo", 15);
            // 金额大于0才发放
            if (CollectionUtil.isNotEmpty(bankList)) {
                payItem.setTtlamt(totalIssueCost.toString());
                payItem.setTtlcnt(bankList.size() + "");
                payItem.setCuramt(totalIssueCost.toString());
                payItem.setCurcnt(bankList.size() + "");
                payItem.setCnvnbr(protocolStr);
                //BYBC 代发劳务收入BYBK 代发其他BYFN 代发奖金BYSA 代发工资BYTF 代发报销款
                payItem.setAgctyp(bustypStr);
                //10:人民币
                payItem.setCcynbr(ccynbrStr);
                //分行号
                payItem.setBbknbr(bankCardCode);
                payItem.setAccnbr(bankCardId);
                //授权账号
                payItem.setAutacc(authBankId);
                String reqNo = commonLogic.generateNo("cmc", "requstNo", 15);
                payItem.setYurref(reqNo);
                payItem.setEptdat(queryDate);
                payItem.setEpttim(DateUtil.format(new Date(), "HHmmss"));
                payItem.setTrsrmk("日结工资");

                for (DailyWorkerBankCardBean workBean : bankList) {
                    if (workBean.getIssueCost().doubleValue() > 0) {
                        String itemReqNo = commonLogic.generateReqNo("1", "requstNo", 8);
                        String depositBank = workBean.getDepositBank();
                        String bankAddr = workBean.getBankAddr();
                        String isCmcBank = "N";
                        if (workBean.getDepositBank().contains("招商银行")) {
                            isCmcBank = "Y";
                            depositBank = "";
                            bankAddr = "";
                        }
                        ReceivedItem receivedItem = new ReceivedItem(
                                itemReqNo,
                                workBean.getBankAccount(),
                                workBean.getBankAccountName(),
                                workBean.getIssueCost().toString(),
                                isCmcBank,
                                depositBank,
                                bankAddr
                        );
                        receiveList.add(receivedItem);

                        SettleDailyIssueSummaryRecord record = new SettleDailyIssueSummaryRecord();
                        BeanUtils.copyProperties(workBean, record);
                        record.setRequestNo(itemReqNo);
                        record.setStatus(DailyConstant.ISSUE_STATUS_BANK_DO);
                        record.setIssueBatchNo(issueBatchNo);
                        record.setIssueBy(opName);
                        record.setIssueTime(new Date());
                        record.setCompanyWechatId(adminUser.getAdminCompanyWechat().getCompanyWechatId());
                        record.setCompanyWechatName(adminUser.getAdminCompanyWechat().getCompanyName());
                        issueSummaryRecords.add(record);
                    }

                }
            }
            if (receiveList.size() == 0) {
                deleteTask(summaryBatchNo, summaryNumber);
                log.warn("kPay: 日结没有可转账的数据");
                //throw new RemoteServiceException("没有可转账的数据");
                return;
            }
            Map<String, Object> payMap = cmcBankLogic.insteadIssue(payItem, receiveList, summaryNumber);
            if (DailyConstant.CMC_RESPONSE_FAIL_CODE.equals(payMap.get("code").toString())) {
                deleteTask(summaryBatchNo, summaryNumber);
                log.warn("kPay: 待扣支付失败");
                //throw new RemoteServiceException("待扣支付失败");
                return;
            }
            //拿到流程实例号
            List<Map<String, Object>> insteadIssueList = (List<Map<String, Object>>) payMap.get("data");
            String reqnbr = insteadIssueList.get(0).get("reqnbr").toString();

            //修改对应的状态为发放中
            settleDailyIssueSummaryRecordService.updateBatchById(issueSummaryRecords, 500);
            //等待10S 查询转账转态
            //Thread.sleep(1000 * 10);
            Integer issueStatus = queryTransferResult(issueSummaryRecords, bankList, reqnbr, queryDate, summaryNumber,
                    adminUser.getAdminCompanyWechat().getCompanyWechatId(), adminUser.getAdminCompanyWechat().getCompanyName());

            //记录单次记录
            saveCallApiRecord(issueBatchNo, totalIssueCost, issueStatus, opName, reqnbr, adminUser);
            settleDailyIssueTaskService.lambdaUpdate()
                    .set(SettleDailyIssueTask::getTaskStatus, 2)
                    .set(SettleDailyIssueTask::getRequestNo, reqnbr)
                    .eq(SettleDailyIssueTask::getCompanyWechatId, adminUser.getAdminCompanyWechat().getCompanyWechatId())
                    .eq(SettleDailyIssueTask::getSummaryNumber, summaryNumber)
                    .eq(SettleDailyIssueTask::getSummaryBatchNo, summaryBatchNo)
                    .update();
        } catch (Exception e) {
            deleteTask(summaryBatchNo, summaryNumber);
            log.warn("【日结批量经办异常】", e);
        }

    }

    @Transactional
    public void deleteTask(String summaryBatchNo, String summaryNumber) {
        settleDailyIssueTaskService.lambdaUpdate()
                .eq(SettleDailyIssueTask::getSummaryBatchNo, summaryBatchNo)
                .eq(SettleDailyIssueTask::getSummaryNumber, summaryNumber)
                .eq(SettleDailyIssueTask::getTaskStatus, 1)
                .remove();
    }

    @Transactional
    public Integer queryMonthTransferResult(List<SettleDailyIssueSummaryMonthRecord> issueSummaryRecords,
                                            List<DailyWokerBankCardMonthBean> bankList, String reqnbr, String queryDate,
                                            String summaryNumber, String companyId, String companyName) throws Exception {
        Map<String, Object> payResultMap = cmcBankLogic.insteadResult(reqnbr, summaryNumber);
        Integer issueStaus = DailyConstant.ISSUE_STATUS_BANK_DO;
        if (DailyConstant.CMC_RESPONSE_SUCCESS_CODE.equals(payResultMap.get("code").toString())) {
            List<Map<String, Object>> payResultList = (List<Map<String, Object>>) payResultMap.get("data");
            List<SettleDailyIssueSummaryMonthRecord> transferSuccessList = new ArrayList<>();
            List<SettleDailyIssueSummaryMonthRecord> transferFailedList = new ArrayList<>();
            for (Map map : payResultList) {
                //汇款业务状态
                String transferResult = map.get("trssts").toString();
                for (SettleDailyIssueSummaryMonthRecord issueSummaryRecord : issueSummaryRecords) {
                    if (map.get("trsseq").toString().equals(issueSummaryRecord.getRequestNo())) {
                        issueSummaryRecord.setCompanyWechatId(companyId);
                        issueSummaryRecord.setCompanyWechatName(companyName);
                        //转账成功的记录
                        if (Arrays.asList(DailyConstant.TRANSFER_RESP_SUCCESS).contains(transferResult)) {
                            issueSummaryRecord.setStatus(DailyConstant.ISSUE_STATUS_SUCCESS);
                            issueSummaryRecord.setUpdateTime(new Date());
                            //issueSummaryRecord.setEmpInsuranceCost(issueSummaryRecord.getShouldEmpInsuranceCost());
                            //issueSummaryRecord.setResidualInsuranceCost(issueSummaryRecord.getShouldResidualInsuranceCost());
                            //issueSummaryRecord.setReduceCost(issueSummaryRecord.getShouldReduceCost());
                            issueSummaryRecord.setWithholdTotalCost(issueSummaryRecord.getWithholdCost());
                            //issueSummaryRecord.setIssueTimeFmt(queryDate);
                            issueSummaryRecord.setRemark("");

                            transferSuccessList.add(issueSummaryRecord);
                        }
                        //失败的记录
                        if (Arrays.asList(DailyConstant.TRANSFER_RESP_FAILED).contains(transferResult)) {
                            issueSummaryRecord.setStatus(DailyConstant.ISSUE_STATUS_FAILED);
                            issueSummaryRecord.setUpdateTime(new Date());
                            issueSummaryRecord.setRemark(map.get("errtxt").toString());
                            transferFailedList.add(issueSummaryRecord);
                        }
                    }
                }
            }
            if (transferSuccessList.size() == bankList.size()) {
                issueStaus = DailyConstant.ISSUE_STATUS_SUCCESS;
            }
            if (transferFailedList.size() == bankList.size()) {
                issueStaus = DailyConstant.ISSUE_STATUS_FAILED;
            }
            if (transferSuccessList.size() > 0) {
                settleDailyIssueSummaryMonthRecordService.updateBatchById(transferSuccessList, 500);
            }

            if (transferFailedList.size() > 0) {
                settleDailyIssueSummaryMonthRecordService.updateBatchById(transferFailedList, 500);
            }
        }
        return issueStaus;
    }

    @Transactional
    public void saveCallApiRecord(String issueBatchNo, BigDecimal totalAmount, Integer issueStatus, String nickName, String reqnbr, AdminUserCom adminUser) {
        SettleDailyBankTransferRecord record = new SettleDailyBankTransferRecord();
        record.setCallApiTime(new Date());
        record.setCallBackMessage("");
        record.setCreateTime(new Date());
        record.setCreateBy(nickName);
        record.setDoTime(new Date());
        record.setDoBy(nickName);
        record.setCallStatus(1);
        record.setReqNo(reqnbr);
        record.setIssueStatus(issueStatus);
        record.setIssueBatchNo(issueBatchNo);
        record.setSummaryAmount(totalAmount);
        record.setCompanyWechatId(adminUser.getAdminCompanyWechat().getCompanyWechatId());
        record.setCompanyWechatName(adminUser.getAdminCompanyWechat().getCompanyName());
        record.insert();
    }

    @Transactional
    public Integer queryTransferResult(List<SettleDailyIssueSummaryRecord> issueSummaryRecords,
                                       List<DailyWorkerBankCardBean> bankList, String reqnbr, String queryDate,
                                       String summaryNumber, String companyId, String companyName) throws Exception {
        Map<String, Object> payResultMap = cmcBankLogic.insteadResult(reqnbr, summaryNumber);
        Integer issueStaus = DailyConstant.ISSUE_STATUS_BANK_DO;
        if (DailyConstant.CMC_RESPONSE_SUCCESS_CODE.equals(payResultMap.get("code").toString())) {
            List<Map<String, Object>> payResultList = (List<Map<String, Object>>) payResultMap.get("data");
            List<SettleDailyIssueSummaryRecord> transferSuccessList = new ArrayList<>();
            List<SettleDailyIssueSummaryRecord> transferFailedList = new ArrayList<>();
            for (Map map : payResultList) {
                //汇款业务状态
                String transferResult = map.get("trssts").toString();
                for (SettleDailyIssueSummaryRecord issueSummaryRecord : issueSummaryRecords) {
                    if (map.get("trsseq").toString().equals(issueSummaryRecord.getRequestNo())) {
                        issueSummaryRecord.setCompanyWechatId(companyId);
                        issueSummaryRecord.setCompanyWechatId(companyName);
                        //转账成功的记录
                        if (Arrays.asList(DailyConstant.TRANSFER_RESP_SUCCESS).contains(transferResult)) {
                            issueSummaryRecord.setStatus(DailyConstant.ISSUE_STATUS_SUCCESS);
                            issueSummaryRecord.setUpdateTime(new Date());
                            issueSummaryRecord.setIssueTimeFmt(queryDate);
                            //issueSummaryRecord.setEmpInsuranceCost(issueSummaryRecord.getShouldEmpInsuranceCost());
                            //issueSummaryRecord.setResidualInsuranceCost(issueSummaryRecord.getShouldResidualInsuranceCost());
                            //issueSummaryRecord.setReduceCost(issueSummaryRecord.getShouldReduceCost());
                            issueSummaryRecord.setWithholdTotalCost(issueSummaryRecord.getWithholdCost());
                            issueSummaryRecord.setRemark("");
                            transferSuccessList.add(issueSummaryRecord);
                        }
                        //失败的记录
                        if (Arrays.asList(DailyConstant.TRANSFER_RESP_FAILED).contains(transferResult)) {
                            issueSummaryRecord.setStatus(DailyConstant.ISSUE_STATUS_FAILED);
                            issueSummaryRecord.setUpdateTime(new Date());
                            issueSummaryRecord.setRemark(map.get("errtxt").toString());
                            transferFailedList.add(issueSummaryRecord);
                        }
                    }
                }
            }
            if (transferSuccessList.size() == bankList.size()) {
                issueStaus = DailyConstant.ISSUE_STATUS_SUCCESS;
            }
            if (transferFailedList.size() == bankList.size()) {
                issueStaus = DailyConstant.ISSUE_STATUS_FAILED;
            }
            if (transferSuccessList.size() > 0) {
                settleDailyIssueSummaryRecordService.updateBatchById(transferSuccessList, 500);
            }

            if (transferFailedList.size() > 0) {
                settleDailyIssueSummaryRecordService.updateBatchById(transferFailedList, 500);
            }
        }
        return issueStaus;
    }

    public void excute() {
        try {
            List<SettleDailyIssueTask> tasks = settleDailyIssueTaskService.lambdaQuery()
                    .eq(SettleDailyIssueTask::getTaskStatus, 2)
                    .list();
            if (tasks.size() == 0) {
                log.info("【暂无可执行查询数据】");
                return;
            }

            for (SettleDailyIssueTask task : tasks) {
                if (task.getIsMonth()) {
                    log.info("【月结查询】");
                    List<SettleDailyIssueSummaryMonthRecord> items = settleDailyIssueSummaryMonthRecordService.lambdaQuery()
                            .eq(SettleDailyIssueSummaryMonthRecord::getCompanyWechatId, task.getCompanyWechatId())
                            .eq(SettleDailyIssueSummaryMonthRecord::getSummaryBatchNo, task.getSummaryBatchNo())
                            .eq(SettleDailyIssueSummaryMonthRecord::getSummaryNumber, task.getSummaryNumber())
                            .eq(SettleDailyIssueSummaryMonthRecord::getStatus, DailyConstant.ISSUE_STATUS_BANK_DO).list();

                    if (items.size() == 0) {
                        //设置该笔查询状态为完结 taskStatus 1.新建 2.处理中 3.完成
                        task.setTaskStatus(3).setUpdateTime(new Date());
                        task.updateById();
                        continue;
                    }
                    String queryDateEnd = DateUtil.format(new Date(), "yyyyMMdd");
                    List<DailyWokerBankCardMonthBean> bankList = dailyMapper.queryIssueSalaryMonthBankCardInfo(task.getSummaryBatchNo(),
                            task.getSummaryNumber(), DailyConstant.ISSUE_STATUS_BANK_DO, task.getCompanyWechatId());
                    this.queryMonthTransferResult(items, bankList, task.getRequestNo(), queryDateEnd,task.getSummaryNumber(),
                            task.getCompanyWechatId(), task.getCompanyWechatName());

                } else {
                    log.info("【日结查询】");
                    List<SettleDailyIssueSummaryRecord> items = settleDailyIssueSummaryRecordService.lambdaQuery()
                            .eq(SettleDailyIssueSummaryRecord::getCompanyWechatId, task.getCompanyWechatId())
                            .eq(SettleDailyIssueSummaryRecord::getSummaryBatchNo, task.getSummaryBatchNo())
                            .eq(SettleDailyIssueSummaryRecord::getSummaryNumber, task.getSummaryNumber())
                            .eq(SettleDailyIssueSummaryRecord::getStatus, DailyConstant.ISSUE_STATUS_BANK_DO).list();

                    if (items.size() == 0) {
                        task.setTaskStatus(3).setUpdateTime(new Date());
                        task.updateById();
                        continue;
                    }
                    String queryDateEnd = DateUtil.format(new Date(), "yyyyMMdd");

                    List<DailyWorkerBankCardBean> bankList = dailyMapper.queryIssueSalaryAndBankCardInfo(task.getSummaryBatchNo(),
                            task.getSummaryNumber(), DailyConstant.ISSUE_STATUS_BANK_DO, task.getCompanyWechatId());
                    Integer status = this.queryTransferResult(items, bankList, task.getRequestNo(), queryDateEnd,task.getSummaryNumber(),
                            task.getCompanyWechatId(), task.getCompanyWechatName());

                    settleDailyBankTransferRecordService.lambdaUpdate()
                            .set(SettleDailyBankTransferRecord::getIssueStatus,status)
                            .eq(SettleDailyBankTransferRecord::getCompanyWechatId, task.getCompanyWechatId())
                            .eq(SettleDailyBankTransferRecord::getReqNo,task.getRequestNo())
                            .update();
                }
                log.info("【查询转账结果完成】");
            }
        } catch (Exception e) {
            log.info("【查询转账结果出错】：" + e);
        }
    }
}
