package com.dxhy.core.job.service.impl;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dxhy.api.model.config.CollectionControlModel;
import com.dxhy.api.model.config.sys.SysEnterpriseConfigEntity;
import com.dxhy.api.model.db.*;
import com.dxhy.api.model.invoice.TDxHttpLog;
import com.dxhy.common.constant.ConfigureConstant;
import com.dxhy.common.constant.CoreConstants;
import com.dxhy.common.constant.DbConstant;
import com.dxhy.common.datasource.config.DynamicContextHolder;
import com.dxhy.common.util.JsonUtils;
import com.dxhy.common.utils.MakeAppSecService;
import com.dxhy.core.dao.CoreConfirmDao;
import com.dxhy.core.dao.CoreSysEnterpriseConfigCoreDao;
import com.dxhy.core.dao.CoreTDxRecordInvoiceDao;
import com.dxhy.core.job.dao.*;
import com.dxhy.core.job.entity.TAcOrg;
import com.dxhy.core.job.entity.TDxApplyStatRecord;
import com.dxhy.core.job.pojo.*;
import com.dxhy.core.job.service.ApplyService;
import com.dxhy.core.util.Dqyjkdyutil;
import com.dxhy.jxpt.baseService.dao.TdxDkTsCountDao;
import com.dxhy.jxpt.baseService.dao.TdxDkTsCountDetailDao;
import com.dxhy.jxpt.baseService.poolPush.PoolLogService;
import com.dxhy.pojo.obj.DqyTsApplyReq;
import com.dxhy.pojo.obj.DqyTsApplyResultReq;
import com.dxhy.pojo.obj.DqyTsApplyResultResp;
import com.dxhy.pojo.obj.DqyTsApplyResultRespItem;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 接口服务 申请统计接口， 统计结果获取接口 申请确认接口 确认结果获取接口
 *
 * @author 陈刚扬
 * @date 2020/10/28
 * @return
 */
@SuppressWarnings({"AlibabaUndefineMagicConstant", "AlibabaMethodTooLong"})
@Service("applyService")
@Slf4j
public class ApplyServiceImpl extends ServiceImpl<CoreConfirmDao, TDxHttpLog> implements ApplyService {


    @Resource
    private ApplyStatDao applyStatDao;
    @Resource
    private PoolLogService poolLogService;

    @Resource
    private MakeAppSecService makeAppSecService;
    @Resource
    private CoreConfirmDao coreConfirmDao;
    @Resource
    private TDxApplyStatRecordDao tDxApplyStatRecordDao;
    @Resource
    private TDxDkCountDetailDao tDxDkCountDetailDao;
    @Resource
    private TDxDkCountDao dkCountDao;

    @Resource
    private TaxRefundDao taxRefundDao;

    @Resource
    private CoreSysEnterpriseConfigCoreDao coreSysEnterpriseConfigCoreDao;

    @Resource
    private TDxLqApplyStatRecordDao tDxLqApplyStatRecordDao;

    @Resource
    private CoreTDxRecordInvoiceDao coreTDxRecordInvoiceDao;
    @Resource
    private CoreTDxCustomsRecordDao coreTDxCustomsRecordDao;

    @Resource
    private TdxDkTsCountDao tdxDkTsCountDao;

    @Resource
    private TdxDkTsCountDetailDao tdxDkTsCountDetailDao;

    /**
     * 查询数据库，发送申请统计接口
     */
    @Override
    public void getDataForApply() {
        log.info("申请统计接口开始");
        TDxHttpLog tDxHttpLog = new TDxHttpLog();
        tDxHttpLog.setType("07");

        // 查询数据库 遍历数据源
        DynamicContextHolder.push(DbConstant.BASICS_READ);
        List<String> dbList = coreConfirmDao.getDbSource();
        for (String db : dbList) {
            DynamicContextHolder.push(db + DbConstant.BUSINESS_READ);
            // 获取数据库中申请的数据
            List<TDxDkCountEntity> list = applyStatDao.getApplyData();
            String dataExchangeId = makeExchangeId();
            // 发送申请接口
            for (TDxDkCountEntity dkentity : list) {
                try {
                    DynamicContextHolder.push(DbConstant.BASICS_READ);
                    //判断是否为大企业税号
                    SysEnterpriseConfigEntity sysEnterpriseConfigEntity = coreSysEnterpriseConfigCoreDao.selectOne(new QueryWrapper<SysEnterpriseConfigEntity>().eq("nsrsbh", dkentity.getTaxno()));
                    if (ObjectUtil.isNotEmpty(sysEnterpriseConfigEntity)&&"1".equals(sysEnterpriseConfigEntity.getJrfs())) {
                        continue;
                    }
                    // 通过税号获取id和key
                    TAcOrg org = coreConfirmDao.findIdAndKeyByTaxno(dkentity.getTaxno());
                    if(ObjectUtil.isEmpty(org)){
                        log.info("未找到此税号的信息，continue");
                        continue;
                    }
                    ApplyStatPo po = new ApplyStatPo();
                    // 配置接口参数 --调用接口
                    String batchNo = null;
                    String aaa = UUID.randomUUID().toString();
                    batchNo = aaa.replaceAll("-", "");
                    // 加密请求数据
                    tDxHttpLog.setTaxno(dkentity.getTaxno());
                    po.setBuyerTaxNo(dkentity.getTaxno());
                    po.setBatchNo(batchNo);
                    po.setStatisticSymbol(dkentity.getApplyType());
                    po.setRzskssq(dkentity.getSkssq());
                    String requstData = null;
                    String dataStr = JSONObject.toJSONString(po);
                    String base64Data = Base64.encode(dataStr);
                    // 生成加密串
                    String appSec = makeAppSecService.makeAppSec(org.getAceId(), CoreConstants.appId, CoreConstants.enterpriseCode, CoreConstants.applyState,
                            CoreConstants.version, base64Data, dataExchangeId, org.getAceKey());
                    log.info("本地请求生成加密串=======" + appSec);
                    requstData = requestData(appSec, dataExchangeId, base64Data, CoreConstants.applyState, org.getAceId());
                    log.info("申请统计请求报文为=======" + requstData);
                    tDxHttpLog.setReqText(requstData);
                    tDxHttpLog.setReqDate(new Date());
                    // 发送请求
                    String responseJson = HttpUtil.post(CoreConstants.collectUrl, requstData, 60000);
                    tDxHttpLog.setResDate(new Date());
                    tDxHttpLog.setResText(responseJson);
                    log.info("申请统计响应请求数据为=" + responseJson);
                    if (responseJson != null) {
                        ResponesJson gatherData = JSONObject.parseObject(responseJson, ResponesJson.class);
                        ReturnStateInfo returnStateInfo = gatherData.getReturnStateInfo();
                        if ("0000".equals(returnStateInfo.getReturnCode())) {
                            String data = gatherData.getData();
                            // 保存批次号等信息到数据库中
                            DynamicContextHolder.push(db + DbConstant.BUSINESS_WRITE);
                            TDxApplyStatRecord entity = new TDxApplyStatRecord();
                            entity.setApplyType(po.getStatisticSymbol());
                            entity.setBatchNo(po.getBatchNo());
                            entity.setCreateDate(new Date());
                            entity.setInterfaceType("0");
                            entity.setResultStatus("N");
                            entity.setSkssq(dkentity.getSkssq());
                            entity.setTaxno(po.getBuyerTaxNo());
                            tDxApplyStatRecordDao.insert(entity);
                            applyStatDao.updateApplyStatus(dkentity);
                        }
                    }
                } catch (Exception e) {
                    DynamicContextHolder.push(db + DbConstant.BUSINESS_WRITE);
                    tDxHttpLog.setStatus("2");
                    coreConfirmDao.insert(tDxHttpLog);
                   log.info("业务处理异常：{}", e);
                }
            }
        }
        log.info("申请统计接口结束");
    }

    /**
     * 查询数据库，获取申请统计结果
     */
    @Override
    public void getApplyStatResult() {
        log.info("进入申请统计结果获取执行方法--");
        // 查询数据库 遍历数据源
        DynamicContextHolder.push(DbConstant.BASICS_READ);
        List<String> dbList = coreConfirmDao.getDbSource();
        for (String db : dbList) {
            DynamicContextHolder.push(db + DbConstant.BUSINESS_READ);
            // 查询数据库
            String dataExchangeId = makeExchangeId();
            List<ApplyStatRecord> list = applyStatDao.getApplyRecord();
            TDxHttpLog tDxHttpLog = new TDxHttpLog();
            tDxHttpLog.setType("08");
            // 获取申请统计结果po
            ApplyStatRecordPo batchData = new ApplyStatRecordPo();
            try {
                // 调用申请结果统计接口
                for (ApplyStatRecord entity : list) {
                    tDxHttpLog.setTaxno(entity.getTaxno());
                    DynamicContextHolder.push(DbConstant.BASICS_READ);
                    //判断是否为大企业税号
                    SysEnterpriseConfigEntity sysEnterpriseConfigEntity = coreSysEnterpriseConfigCoreDao.selectOne(new QueryWrapper<SysEnterpriseConfigEntity>().eq("nsrsbh", entity.getTaxno()));
                    if (ObjectUtil.isNotEmpty(sysEnterpriseConfigEntity)&&"1".equals(sysEnterpriseConfigEntity.getJrfs())) {
                        continue;
                    }
                    // 通过税号获取id和key
                    TAcOrg org = coreConfirmDao.findIdAndKeyByTaxno(entity.getTaxno());
                    if (org == null) {
                        continue;
                    }
                    // 调用接口获取返回报文
                    String batchNo = entity.getBatchNo();
                    // 请求数据加密
                    batchData.setBatchNo(batchNo);
                    batchData.setBuyerTaxNo(entity.getTaxno());
                    String dataStr = JSONObject.toJSONString(batchData);
                    String base64Data;
                    base64Data = Base64.encode(dataStr);
                    // 加密串生成
                    String appSec = makeAppSecService.makeAppSec(org.getAceId(), CoreConstants.appId, CoreConstants.enterpriseCode,CoreConstants. applyStatResult,
                            CoreConstants.version, base64Data, dataExchangeId, org.getAceKey());
                    log.info("本地请求生成加密串=======" + appSec);
                    // 请求报文拼接
                    String requstData =
                        requestData(appSec, dataExchangeId, base64Data, CoreConstants.applyStatResult, org.getAceId());
                    log.info("统计结果获取请求报文为=======" + requstData);
                    // 发送请求返回请求报文
                    tDxHttpLog.setReqText(requstData);
                    tDxHttpLog.setReqDate(new Date());
                    String responseJson;
                    responseJson = HttpUtil.post(CoreConstants.collectUrl, requstData, 60000);
                    tDxHttpLog.setResText(responseJson);
                    tDxHttpLog.setResDate(new Date());
                    log.info("统计结果响应请求数据为=" + responseJson);
                    try {
                        if (responseJson != null) {
                            // 将返回报文转换成实体
                            ResponesJson gatherData = JSONObject.parseObject(responseJson, ResponesJson.class);
                            ReturnStateInfo returnStateInfo = gatherData.getReturnStateInfo();
                            if ("0000".equals(returnStateInfo.getReturnCode())) {
                                String data = gatherData.getData();
                                JSONObject dataJosn = JSONObject.parseObject(Base64.decodeStr(data));
                                if ("Y".equals(dataJosn.getString("batchState"))) {
                                    Date rzhDate = null;
                                    ApplyStatResult result =
                                        JSONArray.parseObject(dataJosn.toJSONString(), ApplyStatResult.class);
                                    SimpleDateFormat tempDate = new SimpleDateFormat("yyyy-MM-dd");
                                    DynamicContextHolder.push(db + DbConstant.BUSINESS_WRITE);
                                    // 获取返回报文
                                    //3 已统计   5 申请认证月份不匹配
                                    if ("3".equals(result.getStatus()) || "5".equals(result.getStatus())) {
                                        // //转换失败原因记录
                                        // 申请失败，更新失败原因
                                        // 申请统计
                                        result.setStatus("3");
                                        if ("0".equals(result.getApplyTjbz())) {
                                            applyStatDao.updateFailStatus(result, entity.getSkssq());
                                        }
                                        // 申请撤销统计
                                        if ("1".equals(result.getApplyTjbz())) {
                                            applyStatDao.updateRebackFailStatus(result, entity.getSkssq());
                                        }
                                        applyStatDao.updateApplyRecord(entity.getId());
                                    }
                                    //已确认
                                    if ("4".equals(result.getStatus())) {
                                        // 申请统计
                                        if ("0".equals(result.getApplyTjbz())) {
                                            result.setStatus("2");
                                            // 申请成功，更新统计明细
                                            String res = result.getStatisticResult();
                                            List<StatResult> reslist = string2List(res);
                                            applyStatDao.updateSuccessStatus(result, entity.getSkssq());
                                            applyStatDao.deleteDetailBySkssq(result, entity.getSkssq());
                                            for (StatResult statResult : reslist) {
                                                TDxDkCountDetailEntity detail = new TDxDkCountDetailEntity();
                                                detail.setTjjglx("1");
                                                detail.setTaxno(result.getBuyerTaxNo());
                                                detail.setTjMonth(result.getStatisticMonth());
                                                detail.setTjDate(result.getStatisticTime());
                                                detail.setInvoiceType(statResult.getInvoiceType());
                                                detail.setDkInvoiceCount(statResult.getDkInvoiceNum());
                                                detail.setDkAmountCount(statResult.getDkTotalAmount());
                                                detail.setDkTaxAmountCount(statResult.getTotalYxAmount());
                                                detail.setBdkInvoiceCount(statResult.getBdkInvoiceNum());
                                                detail.setBdkAmountCount(statResult.getBdkTotalAmount());
                                                detail.setBdkTaxAmountCount(statResult.getBdkTotalYxAmount());
                                                tDxDkCountDetailDao.insert(detail);
                                            }

                                            //判断是否存在   异常抵扣类勾选统计结果
                                            String ycdkRes = result.getYcdkCountReport();
                                            List<StatResult> ycdkReslist = string2List(ycdkRes);
                                            if(ycdkReslist.size()>0){
                                                log.info("统计结果返回-存在异常抵扣类勾选数据，入库");
                                                // 增加异常明细
                                                for (StatResult statResult : ycdkReslist) {
                                                    TDxDkCountDetailEntity detail = new TDxDkCountDetailEntity();
                                                    detail.setTjjglx("2");
                                                    detail.setTaxno(result.getBuyerTaxNo());
                                                    detail.setTjMonth(result.getStatisticMonth());
                                                    detail.setTjDate(result.getStatisticTime());
                                                    detail.setInvoiceType(statResult.getInvoiceType());
                                                    detail.setDkInvoiceCount(statResult.getDkInvoiceNum());
                                                    detail.setDkAmountCount(statResult.getDkTotalAmount());
                                                    detail.setDkTaxAmountCount(statResult.getTotalYxAmount());
                                                    detail.setBdkInvoiceCount(statResult.getBdkInvoiceNum());
                                                    detail.setBdkAmountCount(statResult.getBdkTotalAmount());
                                                    detail.setBdkTaxAmountCount(statResult.getBdkTotalYxAmount());
                                                    tDxDkCountDetailDao.insert(detail);
                                                }
                                            }

                                            //判断是否存在   农产品勾选统计
                                            String agricRes = result.getAgricCountReport();
                                            List<StatResult> agricReslist = string2ListNcpGx(agricRes);
                                            if(agricReslist.size()>0){
                                                log.info("统计结果返回-农产品勾选统计，入库");
                                                // 增加异常明细
                                                for (StatResult statResult : agricReslist) {
                                                    TDxDkCountDetailEntity detail = new TDxDkCountDetailEntity();
                                                    detail.setTjjglx("4");
                                                    detail.setTaxno(result.getBuyerTaxNo());
                                                    detail.setTjMonth(result.getStatisticMonth());
                                                    detail.setTjDate(result.getStatisticTime());
                                                    detail.setInvoiceType(statResult.getInvoiceType());
                                                    detail.setZsfpfs(statResult.getZsfpfs());
                                                    detail.setZsfpse(statResult.getZsfpse());
                                                    detail.setFsfpfs(statResult.getFsfpfs());
                                                    detail.setFsfpse(statResult.getFsfpse());
                                                    tDxDkCountDetailDao.insert(detail);
                                                }
                                            }

                                            //判断是否存在   增值税申报
                                            String shenBaoRes = result.getTaxCountReport();
                                            List<StatResult> shenBaoReslist = string2ListShenBao(shenBaoRes);
                                            if(shenBaoReslist.size()>0){
                                                log.info("统计结果返回-存在异常抵扣类勾选数据，入库");
                                                // 增加异常明细
                                                for (StatResult statResult : shenBaoReslist) {
                                                    TDxDkCountDetailEntity detail = new TDxDkCountDetailEntity();
                                                    detail.setTjjglx("6");
                                                    detail.setTaxno(result.getBuyerTaxNo());
                                                    detail.setTjMonth(result.getStatisticMonth());
                                                    detail.setTjDate(result.getStatisticTime());
                                                    detail.setInvoiceType(statResult.getInvoiceType());
                                                    detail.setDkInvoiceCount(statResult.getDkInvoiceNum());
                                                    detail.setDkAmountCount(statResult.getDkTotalAmount());
                                                    detail.setDkTaxAmountCount(statResult.getTotalYxAmount());
                                                    tDxDkCountDetailDao.insert(detail);
                                                }
                                            }

                                        }
                                        // 撤销统计
                                        if ("1".equals(result.getApplyTjbz())) {
                                            result.setStatus("2");
                                            result.setQrDate(new Date());
                                            applyStatDao.updateCxtjSuccess(result, entity.getSkssq());
                                            applyStatDao.deleteDetailBySkssq(result, entity.getSkssq());
                                        }
                                        applyStatDao.updateApplyRecord(entity.getId());
                                    }
                                }
                            }
                        }
                    } catch (Exception e) {
                        DynamicContextHolder.push(db + DbConstant.BUSINESS_WRITE);
                        tDxHttpLog.setStatus("2");
                        coreConfirmDao.insert(tDxHttpLog);
                       log.info("业务处理异常：{}", e);
                    }
                }

            } catch (Exception e1) {

                DynamicContextHolder.push(db + DbConstant.BUSINESS_WRITE);
                tDxHttpLog.setStatus("2");
                coreConfirmDao.insert(tDxHttpLog);
                e1.printStackTrace();
            }
        }
    }

    /**
     * 解析统计结果信息 01=10=1000=1000=2=100=100;99=10=1000=1000=2=100=100;
     *
     * @param res
     *            统计结果信息
     * @return 返回
     */
    private List<StatResult> string2List(String res) {

        List<StatResult> list = new LinkedList<>();
        if (!"".equals(res) && res != null) {
            // 因为最后带有; 所以默认去掉最后的值
            String[] arr = res.split(";");

            for (String s : arr) {
                if (StringUtils.isNotBlank(s)) {
                    StatResult entity = new StatResult();
                    String[] result = s.split("=");
                    entity.setInvoiceType("null".equals(result[0])?null:result[0]);
                    entity.setDkInvoiceNum("null".equals(result[1])?null:result[1]);
                    entity.setDkTotalAmount("null".equals(result[2])?null:result[2]);
                    entity.setTotalYxAmount("null".equals(result[3])?null:result[3]);
                    entity.setBdkInvoiceNum("null".equals(result[4])?null:result[4]);
                    entity.setBdkTotalAmount("null".equals(result[5])?null:result[5]);
                    entity.setBdkTotalYxAmount("null".equals(result[6])?null:result[6]);
                    list.add(entity);
                }

            }
        }
        return list;
    }

    private List<StatResult> string2ListNcpGx(String res) {

        List<StatResult> list = new LinkedList<>();
        if (!"".equals(res) && res != null) {
            // 因为最后带有; 所以默认去掉最后的值
            String[] arr = res.split(";");

            for (String s : arr) {
                if (StringUtils.isNotBlank(s)) {
                    StatResult entity = new StatResult();
                    String[] result = s.split("=");
                    entity.setInvoiceType("null".equals(result[0])?null:result[0]);
                    entity.setZsfpfs("null".equals(result[1])?null:result[1]);
                    entity.setZsfpse("null".equals(result[2])?null:result[2]);
                    entity.setFsfpfs("null".equals(result[3])?null:result[3]);
                    entity.setFsfpse("null".equals(result[4])?null:result[4]);

                    list.add(entity);
                }

            }
        }
        return list;
    }

    private List<StatResult> string2ListShenBao(String res) {

        List<StatResult> list = new LinkedList<>();
        if (!"".equals(res) && res != null) {
            // 因为最后带有; 所以默认去掉最后的值
            String[] arr = res.split(";");

            for (String s : arr) {
                if (StringUtils.isNotBlank(s)) {
                    StatResult entity = new StatResult();
                    String[] result = s.split("=");
                    entity.setInvoiceType("null".equals(result[0])?null:result[0]);
                    entity.setDkInvoiceNum("null".equals(result[1])?null:result[1]);
                    entity.setDkTotalAmount("null".equals(result[2])?null:result[2]);
                    entity.setTotalYxAmount("null".equals(result[3])?null:result[3]);
                    list.add(entity);
                }

            }
        }
        return list;
    }

    /**
     * 转换失败原因 --编码 转为汉字说明
     *
     * @param failureReason
     *            失败原因
     * @return 返回
     */
    private String exchangeFailReason(String failureReason) {

        if (!"".equals(failureReason) && failureReason != null) {
            if ("1".equals(failureReason)) {
                return "申请成功";
            }
            if ("2".equals(failureReason)) {
                return "已申请统计";
            }
            if ("3".equals(failureReason)) {
                return "已确认统计";
            }
            if ("5".equals(failureReason)) {
                return "税号不存在";
            }
            if ("6".equals(failureReason)) {
                return "不符合申请生成抵扣统计报表条件";
            }
            if ("7".equals(failureReason)) {
                return "未申请统计";
            }
            if ("8".equals(failureReason)) {
                return "其他异常";
            }
        }
        return "";
    }

    @Override
    public String makeExchangeId() {
        SimpleDateFormat tempDate = new SimpleDateFormat("yyyyMMddHHmmss");
        String timestamp = tempDate.format(new java.util.Date());
        return "JXFPTHREE" + timestamp + "ABC";
    }

    public String requestData(String appSec, String dataExchangeId, String base64Data, String interfaceCode,
        String aceId) {
        String requstData = null;
        try {
            Authorize authorize = new Authorize();
            GlobalInfo globalInfo = new GlobalInfo();
            PeriodRequestData periodRequestData = new PeriodRequestData();
            authorize.setAppSecId(aceId);
            authorize.setAppSec(appSec);
            periodRequestData.setAuthorize(authorize);
            globalInfo.setAppId(CoreConstants.appId);
            globalInfo.setDataExchangeId(dataExchangeId);
            globalInfo.setEnterpriseCode(CoreConstants.enterpriseCode);
            globalInfo.setInterfaceCode(interfaceCode);
            globalInfo.setVersion(CoreConstants.version);
            periodRequestData.setGlobalInfo(globalInfo);
            periodRequestData.setData(base64Data);
            requstData = JSONObject.toJSONString(periodRequestData);
        } catch (Exception e) {
           log.info("业务处理异常：{}", e);
        }
        return requstData;
    }

    /**
     * 从数据库中查询数据发送申请确认接口
     */
    @Override
    public void getDataForConfrim() {
        log.info("申请确认接口开始");
        TDxHttpLog tDxHttpLog = new TDxHttpLog();
        tDxHttpLog.setType("09");

        // 查询数据库 遍历数据源
        DynamicContextHolder.push(DbConstant.BASICS_READ);
        List<String> dbList = coreConfirmDao.getDbSource();
        for (String db : dbList) {
            DynamicContextHolder.push(db + DbConstant.BUSINESS_READ);

            // 获取数据库中申请的数据
            List<TDxDkCountEntity> list = applyStatDao.getApplyConfirmData();
            String dataExchangeId = makeExchangeId();
            // 发送申请接口
            for (TDxDkCountEntity dkentity : list) {
                try {
                    DynamicContextHolder.push(DbConstant.BASICS_READ);
                    //判断是否为大企业税号
                    SysEnterpriseConfigEntity sysEnterpriseConfigEntity = coreSysEnterpriseConfigCoreDao.selectOne(new QueryWrapper<SysEnterpriseConfigEntity>().eq("nsrsbh", dkentity.getTaxno()));
                    if (ObjectUtil.isNotEmpty(sysEnterpriseConfigEntity)&&"1".equals(sysEnterpriseConfigEntity.getJrfs())) {
                        continue;
                    }
                    // 通过税号获取id和key
                    TAcOrg org = coreConfirmDao.findIdAndKeyByTaxno(dkentity.getTaxno());
                    if (org == null) {
                        continue;
                    }
                    ApplyConfirmPo po = new ApplyConfirmPo();
                    // 配置接口参数 --调用接口
                    String batchNo = null;
                    String aaa = UUID.randomUUID().toString();
                    batchNo = aaa.replaceAll("-", "");
                    // 加密请求数据
                    tDxHttpLog.setTaxno(dkentity.getTaxno());
                    po.setBuyerTaxNo(dkentity.getTaxno());
                    po.setBatchNo(batchNo);
                    po.setConfirmSymbol(dkentity.getApplyType());
                    po.setStatisticTime(dkentity.getTjDate());
                    po.setRzskssq(dkentity.getSkssq());
                    po.setYwmm(org.getPassword());
                    String requstData = null;
                    String dataStr = JSONObject.toJSONString(po);
                    log.info("申请确认参数=========" + dataStr);
                    String base64Data = Base64.encode(dataStr);
                    // 生成加密串
                    String appSec = makeAppSecService.makeAppSec(org.getAceId(), CoreConstants.appId, CoreConstants.enterpriseCode, CoreConstants.applyConfirm,
                            CoreConstants.version, base64Data, dataExchangeId, org.getAceKey());
                    log.info("本地请求生成加密串=======" + appSec);
                    requstData = requestData(appSec, dataExchangeId, base64Data, CoreConstants.applyConfirm, org.getAceId());
                    log.info("申请确认请求报文为=======" + requstData);
                    tDxHttpLog.setReqText(requstData);
                    tDxHttpLog.setReqDate(new Date());
                    // 发送请求
                    String responseJson = HttpUtil.post(CoreConstants.collectUrl, requstData, 60000);
                    tDxHttpLog.setResDate(new Date());
                    tDxHttpLog.setResText(responseJson);
                    log.info("申请确认响应请求数据为=" + responseJson);
                    if (responseJson != null) {
                        ResponesJson gatherData = JSONObject.parseObject(responseJson, ResponesJson.class);
                        ReturnStateInfo returnStateInfo = gatherData.getReturnStateInfo();
                        if ("0000".equals(returnStateInfo.getReturnCode())) {
                            DynamicContextHolder.push(db + DbConstant.BUSINESS_WRITE);
                            String data = gatherData.getData();
                            // 保存批次号等信息到数据库中
                            TDxApplyStatRecord entity = new TDxApplyStatRecord();
                            entity.setApplyType(dkentity.getApplyType());
                            entity.setBatchNo(po.getBatchNo());
                            entity.setCreateDate(new Date());
                            entity.setInterfaceType("1");
                            entity.setResultStatus("N");
                            entity.setSkssq(dkentity.getSkssq());
                            entity.setTaxno(po.getBuyerTaxNo());
                            tDxApplyStatRecordDao.insert(entity);
                            applyStatDao.updateApplyConfrimStatus(dkentity);
                        }
                    }
                } catch (Exception e) {
                    DynamicContextHolder.push(db + DbConstant.BUSINESS_WRITE);
                    tDxHttpLog.setStatus("2");
                    coreConfirmDao.insert(tDxHttpLog);
                   log.info("业务处理异常：{}", e);
                }
            }
        }
        log.info("申请确认接口结束");
    }

    /**
     * 获取申请确认结果接口
     */
    @Override
    public void getApplyConfirmResult() {

        // 查询数据库 遍历数据源
        DynamicContextHolder.push(DbConstant.BASICS_READ);
        List<String> dbList = coreConfirmDao.getDbSource();
        for (String db : dbList) {
            DynamicContextHolder.push(db + DbConstant.BUSINESS_READ);
            String dataExchangeId = makeExchangeId();
            List<ApplyStatRecord> list = applyStatDao.getApplyConfirmRecord();
            TDxHttpLog tDxHttpLog = new TDxHttpLog();
            tDxHttpLog.setType("10");
            // 获取申请统计结果po
            ApplyStatRecordPo batchData = new ApplyStatRecordPo();
            try {
                // 调用申请结果统计接口
                for (ApplyStatRecord entity : list) {
                    // 调用接口获取返回报文
                    DynamicContextHolder.push(DbConstant.BASICS_READ);
                    //判断是否为大企业税号
                    SysEnterpriseConfigEntity sysEnterpriseConfigEntity = coreSysEnterpriseConfigCoreDao.selectOne(new QueryWrapper<SysEnterpriseConfigEntity>().eq("nsrsbh", entity.getTaxno()));
                    if (ObjectUtil.isNotEmpty(sysEnterpriseConfigEntity)&&"1".equals(sysEnterpriseConfigEntity.getJrfs())) {
                        continue;
                    }
                    // 通过税号获取id和key
                    TAcOrg org = coreConfirmDao.findIdAndKeyByTaxno(entity.getTaxno());
                    if (org == null) {
                        continue;
                    }
                    String batchNo = entity.getBatchNo();
                    // 请求数据加密
                    batchData.setBatchNo(batchNo);
                    batchData.setBuyerTaxNo(entity.getTaxno());
                    String dataStr = JSONObject.toJSONString(batchData);
                    String base64Data;
                    base64Data = Base64.encode(dataStr);
                    // 加密串生成
                    String appSec = makeAppSecService.makeAppSec(org.getAceId(), CoreConstants.appId, CoreConstants.enterpriseCode,
                            CoreConstants.applyConfirmResult, CoreConstants.version, base64Data, dataExchangeId, org.getAceKey());
                    log.info("本地请求生成加密串=======" + appSec);
                    // 请求报文拼接
                    String requstData =
                        requestData(appSec, dataExchangeId, base64Data, CoreConstants.applyConfirmResult, org.getAceId());
                    log.info("统计结果获取请求报文为=======" + requstData);
                    // 发送请求返回请求报文
                    tDxHttpLog.setReqText(requstData);
                    tDxHttpLog.setReqDate(new Date());
                    String responseJson;
                    responseJson = HttpUtil.post(CoreConstants.collectUrl, requstData, 60000);
                    tDxHttpLog.setResText(responseJson);
                    tDxHttpLog.setResDate(new Date());
                    log.info("统计结果响应数据为=" + responseJson);
                    try {
                        if (responseJson != null) {
                            // 将返回报文转换成实体
                            ResponesJson gatherData = JSONObject.parseObject(responseJson, ResponesJson.class);
                            ReturnStateInfo returnStateInfo = gatherData.getReturnStateInfo();
                            if ("0000".equals(returnStateInfo.getReturnCode())) {
                                String data = gatherData.getData();
                                JSONObject dataJosn = JSONObject.parseObject(Base64.decodeStr(data));
                                if ("Y".equals(dataJosn.getString("batchState"))) {
                                    Date rzhDate = null;
                                    ApplyStatResult result =
                                        JSONArray.parseObject(dataJosn.toJSONString(), ApplyStatResult.class);
                                    SimpleDateFormat tempDate = new SimpleDateFormat("yyyy-MM-dd");
                                    DynamicContextHolder.push(db + DbConstant.BUSINESS_WRITE);
                                    // 获取返回报文
                                    if ("3".equals(result.getStatus()) || "5".equals(result.getStatus())) {
                                        // //转换失败原因记录
                                        result.setStatus("3");
                                        // 申请确认
                                        if ("0".equals(result.getApplyTjbz())) {
                                            applyStatDao.updateComfirmFailStatus(result, entity.getSkssq());
                                        }
                                        // 撤销确认
                                        if ("1".equals(result.getApplyTjbz())) {
                                            applyStatDao.updateCxComfirmFailStatus(result, entity.getSkssq());
                                        }
                                        applyStatDao.updateApplyRecord(entity.getId());
                                    }
                                    if ("4".equals(result.getStatus())) {
                                        result.setStatus("2");
                                        try {
                                            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                                            result.setQrDate(sdf.parse(result.getSignDate()));
                                        } catch (Exception e) {

                                        }

                                        // 申请成功，更新统计明细
                                        // 申请确认
                                        if ("0".equals(result.getApplyTjbz())) {
                                            applyStatDao.updateConfirmSuccessStatus(result, entity.getSkssq());
                                        }
                                        if ("1".equals(result.getApplyTjbz())) {
                                            // 撤销确认
                                            applyStatDao.updateCxConfirmSuccessStatus(result, entity.getSkssq());
                                            applyStatDao.updateCxtjSuccess(result, entity.getSkssq());
                                            applyStatDao.deleteDetailBySkssq(result, entity.getSkssq());
                                        }
                                        applyStatDao.updateApplyRecord(entity.getId());
                                    }

                                    //推送新票池记录表
                                    poolLogService.pushChangeToPool("", result.getBuyerTaxNo()+"@"+entity.getSkssq(), ConfigureConstant.POOL_BGLX_SQZTBG_4);
                                }
                            }
                        }
                    } catch (Exception e) {
                        DynamicContextHolder.push(db + DbConstant.BUSINESS_WRITE);
                        tDxHttpLog.setStatus("2");
                        coreConfirmDao.insert(tDxHttpLog);
                       log.info("业务处理异常：{}", e);
                    }
                }

            } catch (Exception e1) {

                DynamicContextHolder.push(db + DbConstant.BUSINESS_WRITE);
                tDxHttpLog.setStatus("2");
                coreConfirmDao.insert(tDxHttpLog);
                e1.printStackTrace();
            }
        }

    }

    /**
     * 获取统计信息
     */
    @Override
    public void getHistoryMsg() {
        log.info("进入获取统计信息执行方法--");
        // 查询数据库 遍历数据源
        DynamicContextHolder.push(DbConstant.BASICS_READ);
        List<String> dbList = coreConfirmDao.getDbSource();
        for (String db : dbList) {

            // 查询数据库
            String dataExchangeId = makeExchangeId();
            // 获取统计信息
            ApplyStatPo batchData = new ApplyStatPo();
            try {
                DynamicContextHolder.push(db + DbConstant.BASICS_READ);
                List<TAcOrg> orgList = coreConfirmDao.getUpgradTaxno();
                if (orgList != null && orgList.size() > 0) {
                    for (TAcOrg acOrg : orgList) {
                        DynamicContextHolder.push(db + DbConstant.BASICS_READ);
                        //判断是否为大企业税号
                        SysEnterpriseConfigEntity sysEnterpriseConfigEntity = coreSysEnterpriseConfigCoreDao.selectOne(new QueryWrapper<SysEnterpriseConfigEntity>().eq("nsrsbh", acOrg.getTaxno()));
                        if (ObjectUtil.isNotEmpty(sysEnterpriseConfigEntity)&&"1".equals(sysEnterpriseConfigEntity.getJrfs())) {
                            continue;
                        }
                        DynamicContextHolder.push(db + DbConstant.BUSINESS_READ);
                        //企业当前属期表
                        TaxCurrent current = coreConfirmDao.qryTaxCurrent(acOrg.getTaxno());
                        //抵扣表里数据
                        List<TDxDkCountEntity> dkList = coreConfirmDao.findAllDkCount(acOrg.getTaxno());
                        if (current != null) {
                            String taxno = current.getCurTaxno();
                            String curskssq = current.getIncomeMoth();
                            //current里的属期 年月
                            LocalDate localDate = LocalDate.of(Integer.parseInt(curskssq.substring(0, 4)),
                                Integer.parseInt(curskssq.substring(4)), 1);
                            //从当前属期里的第一个月开始 年01 例如 202401
                            LocalDate newDate = LocalDate.of(Integer.parseInt(curskssq.substring(0, 4)), 1, 1);
                            if ("2019".equals(curskssq.substring(0, 4))) {
                                newDate = LocalDate.of(2019, 7, 1);
                            }
                            while (newDate.isBefore(localDate) || newDate.equals(localDate)) {
                                String skssq =
                                    "" + newDate.getYear() + newDate.format(DateTimeFormatter.ofPattern("MM"));
                                // 是否当前属期
                                boolean curFalg = false;
                                // 抵扣统计表是否存在
                                boolean existFlag = false;
                                boolean flag = true;
                                TDxDkCountEntity tDxDkCountEntity = null;
                                for (TDxDkCountEntity count : dkList) {
                                    if (skssq.equals(count.getSkssq())) {
                                        existFlag = true;
                                        tDxDkCountEntity = count;
                                        //非当前所属期统计成功的不再获取统计信息
                                        if (!"1".equals(count.getSfdqskssq()) && "2".equals(count.getTjStatus())) {
                                            flag = false;
                                        }
                                    }
                                }
                                if (curskssq.equals(skssq)) {
                                    curFalg = true;
                                }
                                // 若不是当前属期，且统计表包含则不调用
                                if (flag) {
                                    TDxHttpLog tDxHttpLog = new TDxHttpLog();
                                    tDxHttpLog.setType("10");
                                    tDxHttpLog.setReqDate(new Date());
                                    tDxHttpLog.setResDate(new Date());
                                    DynamicContextHolder.push(DbConstant.BASICS_READ);
                                    // 通过税号获取id和key
                                    TAcOrg org = coreConfirmDao.findIdAndKeyByTaxno(taxno);
                                    // 请求数据加密
                                    batchData.setBuyerTaxNo(taxno);
                                    batchData.setRzskssq(skssq);
                                    String dataStr = JSONObject.toJSONString(batchData);
                                    String base64Data;
                                    base64Data = Base64.encode(dataStr);
                                    // 加密串生成
                                    String appSec = makeAppSecService.makeAppSec(org.getAceId(), CoreConstants.appId, CoreConstants.enterpriseCode,
                                            CoreConstants.applyCount, CoreConstants.version, base64Data, dataExchangeId, org.getAceKey());
                                    log.info("本地请求生成加密串=======" + appSec);
                                    // 请求报文拼接
                                    String requstData =
                                        requestData(appSec, dataExchangeId, base64Data, CoreConstants.applyCount, org.getAceId());
                                    log.info("获取统计信息请求报文为=======" + requstData);
                                    // 发送请求返回请求报文
                                    tDxHttpLog.setReqText(requstData);
                                    String responseJson;
                                    responseJson = HttpUtil.post(CoreConstants.collectUrl, requstData, 60000);
                                    //responseJson = FileUtil.readUtf8String("/home/baowen.txt");
                                    //responseJson = "{\"data\":\"ew0KICAiaW5jb21lTW9udGgiOiIyMDIzMDgiLCANCiAgInRheG5vIjoiOTExMTAxMDhNQTAwNENQTjk1IiwgDQogICJjb3VudERhdGUiOiIyMDIzLTA0LTA1IDE2OjA1OjAwIiwgDQogICJjb3VudFN0YXR1cyI6IjIwIiwgDQogICJjb3VudFJlcG9ydCI6IjAxPTI9MTA2MDk0PTMxODIuODI9Mj01NzQ0Mz0xNzIzLjI5OzAzPTA9MD0wPTA9MD0wOzA4PTA9MD0w\n" +
                                    //        "PTA9MD0wOzE0PTA9MD0wPTA9MD0wOzI0PTA9MD0wPTA9MD0wOzgwPTA9MD0wPTA9MD0wOzk5PTI9MTA2MDk0PTMxODIuODI9Mj01NzQ0Mz0xNzIzLjI5OyIsIA0KICAic2lnbkRhdGUiOiIyMDIzLTA0LTA1IDE2OjA1OjAwIiwgDQogICJjYW5jZWxGbGFnIjoiIiwgDQogICJjb3VudEZsYWciOiIwMiIsIA0KICAieWNka0NvdW50UmVwb3J0IjoiIg0KfQ\",\"globalInfo\":{\"appId\":\"JXFP\",\"dataExchangeId\":\"JXFPTHREE20240701150430ABC\",\"encryption\":\"\",\"enterpriseCode\":\"JXFPGLPT\",\"interfaceCode\":\"INVOICE.APPLYCOUNT\",\"version\":\"v1.0\"},\"returnStateInfo\":{\"returnCode\":\"0000\",\"returnMessage\":\"处理成功\"}}";
                                    tDxHttpLog.setResText(responseJson);
                                    log.info("获取统计信息响应数据为=" + responseJson);
                                    try {
                                        if (responseJson != null) {
                                            // 将返回报文转换成实体
                                            ResponesJson gatherData =
                                                JSONObject.parseObject(responseJson, ResponesJson.class);
                                            ReturnStateInfo returnStateInfo = gatherData.getReturnStateInfo();
                                            if ("0000".equals(returnStateInfo.getReturnCode())) {
                                                String data = gatherData.getData();
                                                if (data != null) {
                                                    JSONObject dataJosn =
                                                        JSONObject.parseObject(Base64.decodeStr(data));
                                                    Date rzhDate = null;
                                                    CountMsgResult result = JSONArray
                                                        .parseObject(dataJosn.toJSONString(), CountMsgResult.class);
                                                    SimpleDateFormat tempDate = new SimpleDateFormat("yyyy-MM-dd");
                                                    DynamicContextHolder.push(db + DbConstant.BUSINESS_WRITE);
                                                    // 获取返回报文
                                                    if (curFalg) {
                                                        log.info("处理当前属期");
                                                        if(StringUtils.isBlank(result.getCountFlag())){
                                                            log.info("countFlag为空，走全电平台逻辑");
                                                            if( "0".equals(result.getCountStatus())||"1".equals(result.getCountStatus())||"2".equals(result.getCountStatus())||"3".equals(result.getCountStatus())||"4".equals(result.getCountStatus()) ){
                                                                if("1".equals(tDxDkCountEntity.getTjStatus())||"1".equals(tDxDkCountEntity.getQsStatus())||"1".equals(tDxDkCountEntity.getCxtjStatus())||"1".equals(tDxDkCountEntity.getCxqsStatus()) ){
                                                                    log.info("当前属期，如果：统计，确认，撤销统计，撤销确认  有一个为1(申请中)则不处理，按原有定时任务去处理");
                                                                    continue;
                                                                }else{
                                                                    //处理全电平台返回的countstatus
                                                                    TDxDkCountEntity dkCount = new TDxDkCountEntity();
                                                                    qdptDealCountStatus(dkCount,result,tDxDkCountEntity);

                                                                    String res = result.getCountReport();
                                                                    List<StatResult> reslist = string2List(res);
                                                                    log.info("处理当前属期入库数据");
                                                                    dealCurDkCountDetailData(result,dkCount,reslist);

                                                                    if("3".equals(result.getCountStatus())){
                                                                        log.info("如果是3 撤销统计 ，清除统计的明细，初始化当前属期的count表");
                                                                        ApplyStatResult statResult = new ApplyStatResult();
                                                                        statResult.setBuyerTaxNo(taxno);
                                                                        statResult.setStatisticMonth(skssq);
                                                                        applyStatDao.deleteDetailBySkssq(statResult, skssq);
                                                                        applyStatDao.updateCxCount(taxno, skssq);
                                                                    }
                                                                }
                                                            }else{
                                                                log.info("全电平台返回的countstatus:{}没有此业务",result.getCountStatus());
                                                            }
                                                        }else{
                                                            log.info("countFlag不为空，按原先综服逻辑");
                                                            if ("02".equals(result.getCountFlag())
                                                                    || "03".equals(result.getCountFlag())) {
                                                                if ("20".equals(result.getCountStatus())
                                                                        || "22".equals(result.getCountStatus())) {
                                                                    String res = result.getCountReport();
                                                                    List<StatResult> reslist = string2List(res);
                                                                    TDxDkCountEntity dkCount = new TDxDkCountEntity();
                                                                    //统计状态(0--未申请 1--申请中 2--申请成功 3--申请失败)
                                                                    dkCount.setTjStatus("2");
                                                                    //00-已申请统计01-可申请统计；02-可确认申报；03-已确认申报
                                                                    //（全电平台该字段默认返回空）
                                                                    if ("03".equals(result.getCountFlag())) {
                                                                        //确认状态(0--未申请 1--申请中 2--申请成功 3--申请失败)
                                                                        dkCount.setQsStatus("2");
                                                                        if (!"2".equals(tDxDkCountEntity.getQsStatus())) {
                                                                            SimpleDateFormat sdf =
                                                                                    new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                                                                            try {
                                                                                //确认时间
                                                                                dkCount.setQrDate(
                                                                                        sdf.parse(result.getSignDate()));
                                                                            } catch (Exception e) {
                                                                                dkCount.setQrDate(new Date());
                                                                            }
                                                                        } else {
                                                                            SimpleDateFormat sdf =
                                                                                    new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                                                                            if (StringUtils
                                                                                    .isNotBlank(result.getSignDate())) {
                                                                                try {
                                                                                    dkCount.setQrDate(
                                                                                            sdf.parse(result.getSignDate()));
                                                                                } catch (Exception e) {
                                                                                }
                                                                            } else {
                                                                                dkCount.setQrDate(tDxDkCountEntity.getQrDate());
                                                                            }
                                                                        }
                                                                        if (tDxDkCountEntity != null
                                                                                && "2".equals(tDxDkCountEntity.getCxqsStatus())) {
                                                                            dkCount.setCxqsStatus("0");
                                                                        }
                                                                    } else {
                                                                        //只03 02 ，则else是
                                                                        // 02-可确认申报
                                                                        if (tDxDkCountEntity != null
                                                                                 ) {
                                                                            if("2".equals(tDxDkCountEntity.getQsStatus())){
                                                                                dkCount.setQsStatus("0");
                                                                                dkCount.setQrDate(null);
                                                                            }else{
                                                                                //维持库里状态
                                                                                dkCount.setQsStatus(tDxDkCountEntity.getQsStatus());
                                                                                dkCount.setQrDate(tDxDkCountEntity.getQrDate());
                                                                            }
                                                                        }
                                                                    }
                                                                    if (tDxDkCountEntity != null
                                                                            && "2".equals(tDxDkCountEntity.getCxtjStatus())) {
                                                                        dkCount.setCxtjStatus("0");
                                                                    }
                                                                    String statisticTime = null;
                                                                    if (StringUtils.isNotBlank(result.getCountDate())) {
                                                                        Date tjDate =
                                                                                new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
                                                                                        .parse(result.getCountDate());
                                                                        statisticTime =
                                                                                new SimpleDateFormat("yyyyMMddHHmmss")
                                                                                        .format(tjDate);
                                                                        dkCount.setTjDate(statisticTime);
                                                                    }
                                                                    dkCount.setTaxno(result.getTaxno());
                                                                    dkCount.setSkssq(result.getIncomeMonth());
                                                                    //00-已申请统计01-可申请统计；02-可确认申报；03-已确认申报
                                                                    //（全电平台该字段默认返回空）
                                                                    if ("02".equals(result.getCountFlag())) {
                                                                        if (existFlag) {

                                                                            applyStatDao.updateCountMsg(dkCount,
                                                                                    dkCount.getSkssq());
                                                                        } else {
                                                                            insertDkCount(acOrg, skssq, false,
                                                                                    statisticTime, true);
                                                                        }
                                                                    } else if ("03".equals(result.getCountFlag())) {
                                                                        if (existFlag) {
                                                                            applyStatDao.updateConfirmMsg(dkCount,
                                                                                    dkCount.getSkssq());
                                                                        } else {
                                                                            insertDkCount(acOrg, skssq, true, statisticTime,
                                                                                    true);
                                                                        }
                                                                    }

                                                                    log.info("处理入库数据");
                                                                    dealCurDkCountDetailData(result,dkCount,reslist);
                                                                }
                                                            } else if ("01".equals(result.getCountFlag())|| StringUtils.isBlank(result.getCountFlag())) {
                                                                if ("00".equals(result.getCountStatus())) {
                                                                    if (tDxDkCountEntity != null
                                                                            && "2".equals(tDxDkCountEntity.getTjStatus())) {
                                                                        ApplyStatResult statResult = new ApplyStatResult();
                                                                        statResult.setBuyerTaxNo(taxno);
                                                                        statResult.setStatisticMonth(skssq);
                                                                        applyStatDao.deleteDetailBySkssq(statResult, skssq);
                                                                        applyStatDao.updateCxCount(taxno, skssq);
                                                                    }
                                                                }

                                                            }

                                                        }
                                                    } else {
                                                        log.info("历史属期");
                                                        if(StringUtils.isBlank(result.getCountFlag())) {
                                                            log.info("countFlag为空，走全电平台逻辑");
                                                            //处理全电平台返回的countstatus
                                                            TDxDkCountEntity dkCount = new TDxDkCountEntity();
                                                            qdptDealCountStatus(dkCount,result,tDxDkCountEntity);

                                                            //处理历史属期入库数据
                                                            String res = result.getCountReport();
                                                            List<StatResult> reslist = string2List(res);
                                                            dealHistoryDkCountDetailData(dkCount,result,reslist);
                                                        }else{
                                                            log.info("countFlag不为空，按原先综服逻辑");
                                                            if ("20".equals(result.getCountStatus())
                                                                    || "22".equals(result.getCountStatus())) {
                                                                String res = result.getCountReport();
                                                                List<StatResult> reslist = string2List(res);
                                                                TDxDkCountEntity dkCount = new TDxDkCountEntity();
                                                                dkCount.setTjStatus("2");
                                                                dkCount.setQsStatus("2");
                                                                String statisticTime = null;
                                                                if (StringUtils.isNotBlank(result.getCountDate())) {
                                                                    Date tjDate =
                                                                            new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
                                                                                    .parse(result.getCountDate());
                                                                    statisticTime = new SimpleDateFormat("yyyyMMddHHmmss")
                                                                            .format(tjDate);
                                                                    dkCount.setTjDate(statisticTime);
                                                                }
                                                                dkCount.setTaxno(result.getTaxno());
                                                                dkCount.setSkssq(result.getIncomeMonth());
                                                                if (existFlag) {
                                                                    applyStatDao.updateConfirmMsg(dkCount,
                                                                            dkCount.getSkssq());
                                                                } else {
                                                                    insertDkCount(acOrg, skssq, true, statisticTime, false);
                                                                }

                                                                dealHistoryDkCountDetailData(dkCount,result,reslist);

                                                            }
                                                        }
                                                    }

                                                    //推送新票池记录表
                                                    poolLogService.pushChangeToPool("", result.getTaxno()+"@"+result.getIncomeMonth(), ConfigureConstant.POOL_BGLX_SQZTBG_4);
                                                }

                                            }
                                        }
                                    } catch (Exception e) {
                                        log.info("业务处理异常：{}",e);
                                        DynamicContextHolder.push(db + DbConstant.BUSINESS_WRITE);
                                        tDxHttpLog.setStatus("2");
                                        coreConfirmDao.insert(tDxHttpLog);
                                    }
                                }

                                newDate = newDate.plusMonths(1);
                            }
                        }
                    }
                }

            } catch (Exception e1) {
                log.info("业务处理异常：{}",e1);
            }
        }
    }

    /**
    * @Description 处理历史属期入库数据
    * @param dkCount
    * @param result
    * @param reslist
    * @Return void
    * @Author wangruwei
    * @Date 2024/6/13 15:55
    **/
    private void dealHistoryDkCountDetailData(TDxDkCountEntity dkCount, CountMsgResult result, List<StatResult> reslist) {
        // 删除旧明细
        ApplyStatResult statResult = new ApplyStatResult();
        statResult.setBuyerTaxNo(dkCount.getTaxno());
        statResult.setStatisticMonth(dkCount.getSkssq());
        applyStatDao.deleteDetailBySkssq(statResult,
                dkCount.getSkssq());
        // 增加新明细
        for (StatResult stat : reslist) {
            TDxDkCountDetailEntity detail = new TDxDkCountDetailEntity();
            detail.setTaxno(result.getTaxno());
            detail.setTjMonth(result.getIncomeMonth());
            detail.setTjDate(dkCount.getTjDate());
            detail.setInvoiceType(stat.getInvoiceType());
            detail.setDkInvoiceCount(stat.getDkInvoiceNum());
            detail.setDkAmountCount(stat.getDkTotalAmount());
            detail.setDkTaxAmountCount(stat.getTotalYxAmount());
            detail.setBdkInvoiceCount(stat.getBdkInvoiceNum());
            detail.setBdkAmountCount(stat.getBdkTotalAmount());
            detail.setBdkTaxAmountCount(stat.getBdkTotalYxAmount());
            tDxDkCountDetailDao.insert(detail);
        }
        //判断是否存在   异常抵扣类勾选统计结果
        String ycdkRes = result.getYcdkCountReport();
        List<StatResult> ycdkReslist = string2List(ycdkRes);
        if(ycdkReslist.size()>0){
            log.info("历史属期存在异常抵扣类勾选数据，入库");
            // 增加异常明细
            for (StatResult stat : ycdkReslist) {
                TDxDkCountDetailEntity detail = new TDxDkCountDetailEntity();
                detail.setTjjglx("3");
                detail.setTaxno(result.getTaxno());
                detail.setTjMonth(result.getIncomeMonth());
                detail.setTjDate(dkCount.getTjDate());
                detail.setInvoiceType(stat.getInvoiceType());
                detail.setDkInvoiceCount(stat.getDkInvoiceNum());
                detail.setDkAmountCount(stat.getDkTotalAmount());
                detail.setDkTaxAmountCount(stat.getTotalYxAmount());
                detail.setBdkInvoiceCount(stat.getBdkInvoiceNum());
                detail.setBdkAmountCount(stat.getBdkTotalAmount());
                detail.setBdkTaxAmountCount(
                        stat.getBdkTotalYxAmount());
                tDxDkCountDetailDao.insert(detail);
            }
        }
    }

    /**
    * @Description 处理当前属期返回的数据
    * @param result
    * @param dkCount
    * @param reslist
    * @Return void
    * @Author wangruwei
    * @Date 2024/6/13 15:41
    **/
    private void dealCurDkCountDetailData(CountMsgResult result, TDxDkCountEntity dkCount, List<StatResult> reslist) {
        // 删除旧明细
        ApplyStatResult statResult = new ApplyStatResult();
        statResult.setBuyerTaxNo(dkCount.getTaxno());
        statResult.setStatisticMonth(dkCount.getSkssq());
        applyStatDao.deleteDetailBySkssq(statResult,
                dkCount.getSkssq());
        // 增加新明细
        for (StatResult stat : reslist) {
            TDxDkCountDetailEntity detail = new TDxDkCountDetailEntity();
            detail.setTaxno(result.getTaxno());
            detail.setTjMonth(result.getIncomeMonth());
            detail.setTjDate(dkCount.getTjDate());
            detail.setInvoiceType(stat.getInvoiceType());
            detail.setDkInvoiceCount(stat.getDkInvoiceNum());
            detail.setDkAmountCount(stat.getDkTotalAmount());
            detail.setDkTaxAmountCount(stat.getTotalYxAmount());
            detail.setBdkInvoiceCount(stat.getBdkInvoiceNum());
            detail.setBdkAmountCount(stat.getBdkTotalAmount());
            detail.setBdkTaxAmountCount(
                    stat.getBdkTotalYxAmount());
            tDxDkCountDetailDao.insert(detail);
        }
        //判断是否存在   异常抵扣类勾选统计结果
        String ycdkRes = result.getYcdkCountReport();
        List<StatResult> ycdkReslist = string2List(ycdkRes);
        if(ycdkReslist.size()>0){
            log.info("当前属期存在异常抵扣类勾选数据，入库");
            // 增加异常明细
            for (StatResult stat : ycdkReslist) {
                TDxDkCountDetailEntity detail = new TDxDkCountDetailEntity();
                detail.setTjjglx("3");
                detail.setTaxno(result.getTaxno());
                detail.setTjMonth(result.getIncomeMonth());
                detail.setTjDate(dkCount.getTjDate());
                detail.setInvoiceType(stat.getInvoiceType());
                detail.setDkInvoiceCount(stat.getDkInvoiceNum());
                detail.setDkAmountCount(stat.getDkTotalAmount());
                detail.setDkTaxAmountCount(stat.getTotalYxAmount());
                detail.setBdkInvoiceCount(stat.getBdkInvoiceNum());
                detail.setBdkAmountCount(stat.getBdkTotalAmount());
                detail.setBdkTaxAmountCount(
                        stat.getBdkTotalYxAmount());
                tDxDkCountDetailDao.insert(detail);
            }
        }

        //判断是否存在   农产品勾选统计
        String agricRes = result.getAgricCountReport();
        List<StatResult> agricReslist = string2ListNcpGx(agricRes);
        if(agricReslist.size()>0){
            log.info("统计结果返回-农产品勾选统计，入库");
            // 增加异常明细
            for (StatResult stat : agricReslist) {
                TDxDkCountDetailEntity detail = new TDxDkCountDetailEntity();
                detail.setTjjglx("4");
                detail.setTaxno(result.getTaxno());
                detail.setTjMonth(result.getIncomeMonth());
                detail.setTjDate(dkCount.getTjDate());
                detail.setInvoiceType(stat.getInvoiceType());
                detail.setZsfpfs(stat.getZsfpfs());
                detail.setZsfpse(stat.getZsfpse());
                detail.setFsfpfs(stat.getFsfpfs());
                detail.setFsfpse(stat.getFsfpse());
                tDxDkCountDetailDao.insert(detail);
            }
        }

        //判断是否存在   增值税申报
        String shenBaoRes = result.getTaxCountReport();
        List<StatResult> shenBaoReslist = string2ListShenBao(shenBaoRes);
        if(shenBaoReslist.size()>0){
            log.info("统计结果返回-存在异常抵扣类勾选数据，入库");
            // 增加异常明细
            for (StatResult stat : shenBaoReslist) {
                TDxDkCountDetailEntity detail = new TDxDkCountDetailEntity();
                detail.setTjjglx("6");
                detail.setTaxno(result.getTaxno());
                detail.setTjMonth(result.getIncomeMonth());
                detail.setTjDate(dkCount.getTjDate());
                detail.setInvoiceType(stat.getInvoiceType());
                detail.setDkInvoiceCount(stat.getDkInvoiceNum());
                detail.setDkAmountCount(stat.getDkTotalAmount());
                detail.setDkTaxAmountCount(stat.getTotalYxAmount());
                tDxDkCountDetailDao.insert(detail);
            }
        }
    }

    /**
    * @Description 处理全电平台返回的数据
    * @param result
    * @param tDxDkCountEntity
    * @Return void
    * @Author wangruwei
    * @Date 2024/6/13 15:16
    **/
    private void qdptDealCountStatus(TDxDkCountEntity dkCount,CountMsgResult result, TDxDkCountEntity tDxDkCountEntity) throws ParseException {
        dkCount.setTaxno(result.getTaxno());
        dkCount.setSkssq(result.getIncomeMonth());
        if("0".equals(result.getCountStatus())){
            log.info("未统计  未确认");
            dkCount.setTjStatus("0");
            dkCount.setTjDate(null);

            dkCount.setQsStatus("0");
            dkCount.setQrDate(null);
        }else if("1".equals(result.getCountStatus())){
            log.info("已统计  未确认");
            dkCount.setTjStatus("2");
            if (StringUtils.isNotBlank(result.getCountDate())) {
                Date tjDate =
                        new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
                                .parse(result.getCountDate());
                String statisticTime =
                        new SimpleDateFormat("yyyyMMddHHmmss")
                                .format(tjDate);
                dkCount.setTjDate(statisticTime);
            }

            dkCount.setQsStatus("0");
            dkCount.setQrDate(null);
        }else if("2".equals(result.getCountStatus())){
            log.info("已统计  已确认");
            dkCount.setTjStatus("2");
            if (StringUtils.isNotBlank(result.getCountDate())) {
                Date tjDate =
                        new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
                                .parse(result.getCountDate());
                String statisticTime =
                        new SimpleDateFormat("yyyyMMddHHmmss")
                                .format(tjDate);
                dkCount.setTjDate(statisticTime);
            }

            dkCount.setQsStatus("2");
            //确认时间不返回，按库时间来
            if(ObjectUtil.isNotEmpty(tDxDkCountEntity.getQrDate())){
                dkCount.setQrDate(tDxDkCountEntity.getQrDate());
            }else{
                dkCount.setQrDate(null);
            }
        }else if("3".equals(result.getCountStatus())){
            log.info("未统计  未确认");
            dkCount.setTjStatus("0");
            dkCount.setTjDate(null);

            dkCount.setQsStatus("0");
            dkCount.setQrDate(null);
        }else if("4".equals(result.getCountStatus())){
            log.info("已统计  未确认");
            dkCount.setTjStatus("2");
            if (StringUtils.isNotBlank(result.getCountDate())) {
                Date tjDate =
                        new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
                                .parse(result.getCountDate());
                String statisticTime =
                        new SimpleDateFormat("yyyyMMddHHmmss")
                                .format(tjDate);
                dkCount.setTjDate(statisticTime);
            }

            dkCount.setQsStatus("0");
            dkCount.setQrDate(null);
        }

        log.info("要更新的数据:{}",JsonUtils.getInstance().toJsonString(dkCount));
        applyStatDao.update(null, new LambdaUpdateWrapper<TDxDkCountEntity>()
                .eq(TDxDkCountEntity::getSkssq, dkCount.getSkssq())
                .eq(TDxDkCountEntity::getTaxno, dkCount.getTaxno())
                .set(TDxDkCountEntity::getTjStatus, dkCount.getTjStatus())
                .set(TDxDkCountEntity::getTjDate, dkCount.getTjDate())
                .set(TDxDkCountEntity::getQsStatus, dkCount.getQsStatus())
                .set(TDxDkCountEntity::getQrDate, dkCount.getQrDate())
        );

    }

    public void insertDkCount(TAcOrg acOrg, String skssq, boolean qsFlag, String tjDate, boolean curflag) {
        TDxDkCountEntity dkCount1 = new TDxDkCountEntity();
        dkCount1.setTaxno(acOrg.getTaxno());
        dkCount1.setTaxname(acOrg.getTaxname());
        dkCount1.setCompany(acOrg.getCompany());
        dkCount1.setSkssq(skssq);
        dkCount1.setApplyStatus("0");
        dkCount1.setSignStatus("0");
        dkCount1.setCreateDate(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        dkCount1.setTjStatus("2");
        if (qsFlag) {
            dkCount1.setQsStatus("2");
        } else {
            dkCount1.setQsStatus("0");
        }
        if (curflag) {
            dkCount1.setSfdqskssq("1");
        } else {
            dkCount1.setSfdqskssq("0");
        }
        dkCount1.setTjDate(tjDate);
        dkCountDao.insert(dkCount1);
    }

    @Override
    public String setPwd(Map<String, String> params) {
        log.info("设置密码接口开始");
        String dataExchangeId = makeExchangeId();
        // 发送申请接口
        try {
            DynamicContextHolder.push(DbConstant.BASICS_READ);
            TAcOrg orgkey = coreConfirmDao.findIdAndKeyByTaxno(params.get("taxno"));
            // 加密请求数据
            String requstData = null;
            String dataStr = JSONObject.toJSONString(params);
            String base64Data = Base64.encode(dataStr);
            // 生成加密串
            String appSec = makeAppSecService.makeAppSec(orgkey.getAceId(), CoreConstants.appId, CoreConstants.enterpriseCode, CoreConstants.setPwd, CoreConstants.version,
                base64Data, dataExchangeId, orgkey.getAceKey());
            log.info("本地请求生成加密串=======" + appSec);
            requstData = requestData(appSec, dataExchangeId, base64Data, CoreConstants.setPwd, orgkey.getAceId());
            log.info("设置密码请求报文为=======" + requstData);
            // 发送请求
            String responseJson = HttpUtil.post(CoreConstants.collectUrl, requstData, 60000);
            log.info("设置密码响应请求数据为=" + responseJson);
            if (responseJson != null) {
                ResponesJson gatherData = JSONObject.parseObject(responseJson, ResponesJson.class);
                ReturnStateInfo returnStateInfo = gatherData.getReturnStateInfo();
                if ("0000".equals(returnStateInfo.getReturnCode())) {
                    String data = gatherData.getData();
                    JSONObject dataJosn = JSONObject.parseObject(Base64.decodeStr(data));
                    // 设置成功更新数据库密码
                    if ("0".equals(dataJosn.getString("status"))) {
                        // 更新属期表密码
                        TaxCurrent taxCurrent = new TaxCurrent();
                        taxCurrent.setBussiPwd(params.get("bussiPwd"));
                        taxCurrent.setCurTaxno(params.get("taxno"));
                        if (params.get("newBussiPwd") != null && !"".equals(params.get("newBussiPwd"))) {
                            taxCurrent.setNewBussiPwd(params.get("newBussiPwd"));
                        } else {
                            taxCurrent.setNewBussiPwd(params.get("bussiPwd"));
                        }
                        DynamicContextHolder.push("business" + DbConstant.BUSINESS_WRITE);
                        applyStatDao.updatePwd(taxCurrent);

                        TAcOrg org = new TAcOrg();
                        if (params.get("newBussiPwd") != null && !"".equals(params.get("newBussiPwd"))) {
                            org.setPassword(params.get("newBussiPwd"));
                        } else {
                            org.setPassword(params.get("bussiPwd"));
                        }
                        org.setTaxno(params.get("taxno"));
                        DynamicContextHolder.push(DbConstant.BASICS_WRITE);
                        applyStatDao.updateYwmm(org);

                        return "设置成功";
                    } else {
                        return dataJosn.getString("failReason");
                    }

                } else {
                    return returnStateInfo.getReturnMessage();
                }
            }
        } catch (Exception e) {
           log.info("业务处理异常：{}", e);
        }

        log.info("设置密码接口结束");
        return "设置失败,请联系管理员";
    }

    @Override
    public String resetPwd(Map<String, String> params) {
        log.info("重置密码接口开始");
        String dataExchangeId = makeExchangeId();
        // 发送申请接口
        try {
            DynamicContextHolder.push(DbConstant.BASICS_READ);
            TAcOrg orgkey = coreConfirmDao.findIdAndKeyByTaxno(params.get("taxno"));
            String requstData = null;
            String dataStr = JSONObject.toJSONString(params);
            String base64Data = Base64.encode(dataStr);
            // 生成加密串
            String appSec = makeAppSecService.makeAppSec(orgkey.getAceId(), CoreConstants.appId, CoreConstants.enterpriseCode, CoreConstants.resetPwd, CoreConstants.version,
                base64Data, dataExchangeId, orgkey.getAceKey());
            log.info("本地请求生成加密串=======" + appSec);
            requstData = requestData(appSec, dataExchangeId, base64Data, CoreConstants.resetPwd, orgkey.getAceId());
            log.info("重置密码请求报文为=======" + requstData);
            // 发送请求
            String responseJson = HttpUtil.post(CoreConstants.collectUrl, requstData, 60000);
            log.info("重置密码响应请求数据为=" + responseJson);
            if (responseJson != null) {
                ResponesJson gatherData = JSONObject.parseObject(responseJson, ResponesJson.class);
                ReturnStateInfo returnStateInfo = gatherData.getReturnStateInfo();
                if ("0000".equals(returnStateInfo.getReturnCode())) {
                    String data = gatherData.getData();
                    JSONObject dataJosn = JSONObject.parseObject(Base64.decodeStr(data));
                    // 设置成功更新数据库密码
                    if ("0".equals(dataJosn.getString("status"))) {
                        // 更新属期表密码
                        TaxCurrent taxCurrent = new TaxCurrent();
                        taxCurrent.setCurTaxno(params.get("taxno"));
                        DynamicContextHolder.push("business" + DbConstant.BUSINESS_WRITE);
                        applyStatDao.updatePwd(taxCurrent);

                        TAcOrg org = new TAcOrg();
                        org.setTaxno(params.get("taxno"));
                        DynamicContextHolder.push(DbConstant.BASICS_WRITE);
                        applyStatDao.updateYwmm(org);

                        return "重置成功";
                    } else {
                        return dataJosn.getString("failReason");
                    }

                } else {
                    return returnStateInfo.getReturnMessage();
                }
            }
        } catch (Exception e) {
           log.info("业务处理异常：{}", e);
        }

        log.info("重置密码接口结束");
        return "重置失败,请联系管理员";
    }

    /**
     * @Description 退税确认申请
     * @Author wangruwei
     * @Date 2024/3/14 15:26
     *
     * @param ccm*/
    @Override
    public void taxRefundApply(CollectionControlModel ccm) {
        log.info("退税确认申请开始");
        log.info("查询出要申请的数据");
        List<Map> result = taxRefundDao.queryRefundList(ccm.getNsrsbh());
        //发票和缴款书明细数据
        //List<Map<String,String>> refundDeatilList = taxRefundDao.queryRefundDeatilList(ccm.getNsrsbh());
        if (CollectionUtils.isNotEmpty(result)) {
            for (int i = 0; i < result.size(); i++) {
                Map map = result.get(i);
                DqyTsApplyReq dqyTsApplyReq =  new DqyTsApplyReq();
                dqyTsApplyReq.setBatchNo(Dqyjkdyutil.getBatchNo());
                dqyTsApplyReq.setBuyerTaxNo(ccm.getNsrsbh());
                dqyTsApplyReq.setRzskssq(map.get("rzhBelongDate").toString());
                BaseResJson gatherData = Dqyjkdyutil.call(new HashMap<>(), CoreConstants.invoiceTsQrSq, ccm.getAceId(),ccm.getAcekey(), dqyTsApplyReq);
                log.info(JSON.toJSONString(gatherData));
                log.info("退税申请响应请求数据为=" + JSON.toJSONString(gatherData));
                try {
                    if (gatherData != null && gatherData.getReturnStateInfo() != null ) {
                        ReturnStateInfo returnStateInfo = gatherData.getReturnStateInfo();
                        if ("0000".equals(returnStateInfo.getReturnCode())) {
                            log.info("大企业接口返回成功，记录请求批次");
                            TDxLqApplyStatRecordEntity tDxLqApplyStatRecordEntity = new TDxLqApplyStatRecordEntity();
                            tDxLqApplyStatRecordEntity.setNsrsbh(ccm.getNsrsbh());
                            tDxLqApplyStatRecordEntity.setSkssq(dqyTsApplyReq.getRzskssq());
                            tDxLqApplyStatRecordEntity.setPclsh(dqyTsApplyReq.getBatchNo());
                            tDxLqApplyStatRecordEntity.setSqlx(ConfigureConstant.STRING_5);
                            tDxLqApplyStatRecordEntity.setResultStatus("N");
                            tDxLqApplyStatRecordEntity.setCreateDate(new Date());
                            tDxLqApplyStatRecordDao.insert(tDxLqApplyStatRecordEntity);

                            log.info("记录退税统计表和明细表");
                            //t_dx_dk_ts_count  t_dx_dk_ts_count_detail
                            TdxDkTsCountEntity tdxDkTsCountEntity = new TdxDkTsCountEntity();
                            tdxDkTsCountEntity.setTaxno(ccm.getNsrsbh());
                            tdxDkTsCountEntity.setTaxname(ccm.getTaxname());
                            tdxDkTsCountEntity.setSkssq(dqyTsApplyReq.getRzskssq());
                            tdxDkTsCountEntity.setApplyStatus(ConfigureConstant.STRING_1);
                            tdxDkTsCountEntity.setQrStatus(ConfigureConstant.STRING_1);
                            //tdxDkTsCountEntity.setSfdqskssq();
                            Calendar calendar = Calendar.getInstance();
                            String yyyyMM = new SimpleDateFormat("yyyyMM").format(calendar.getTime());
                            if(yyyyMM.equals(dqyTsApplyReq.getRzskssq())){
                                tdxDkTsCountEntity.setSfdqskssq("1");
                            }else{
                                tdxDkTsCountEntity.setSfdqskssq("0");
                            }
                            tdxDkTsCountEntity.setCompany(ccm.getCompany());
                            //先删除统计，再插入新的记录。退税可以多次请求
                            tdxDkTsCountDao.delete(new LambdaQueryWrapper<TdxDkTsCountEntity>().eq(TdxDkTsCountEntity::getTaxno, ccm.getNsrsbh())
                                    .eq(TdxDkTsCountEntity::getSkssq, dqyTsApplyReq.getRzskssq())
                            );
                            tdxDkTsCountDao.insert(tdxDkTsCountEntity);
                        }else{
                            log.info("大企业接口返回失败。报文:{}", JsonUtils.getInstance().toJsonString(returnStateInfo));
                        }
                    }else{
                        log.info("大企业接口返回失败：{}", JsonUtils.getInstance().toJsonString(gatherData));
                    }
                }catch (Exception e) {
                    log.info("退税确认申请开始执行失败,{}",e);
                }
            }
        }
    }

    /**
     * @Description 退税确认结果
     * @Author wangruwei
     * @Date 2024/3/14 15:26
     **/
    @Override
    public void taxRefundApplyResult(CollectionControlModel ccm) {
        log.info("退税确认结果开始");

        log.info("查询出要获取结果的请求数据");
        List<TDxLqApplyStatRecordEntity> result = taxRefundDao.queryRefundGetResult(ccm.getNsrsbh());
        if (CollectionUtils.isNotEmpty(result)) {
            for (int i = 0; i < result.size(); i++) {
                TDxLqApplyStatRecordEntity tDxLqApplyStatRecordEntity = result.get(i);
                DqyTsApplyResultReq tsApplyResultReq =  new DqyTsApplyResultReq();
                tsApplyResultReq.setBatchNo(tDxLqApplyStatRecordEntity.getPclsh());
                tsApplyResultReq.setBuyerTaxNo(tDxLqApplyStatRecordEntity.getNsrsbh());
                BaseResJson gatherData = Dqyjkdyutil.call(new HashMap<>(), CoreConstants.invoiceTsQrResult, ccm.getAceId(),ccm.getAcekey(), tsApplyResultReq);
                log.info(JSON.toJSONString(gatherData));
                log.info("退税确认结果响应数据为=" + JSON.toJSONString(gatherData));
                try {
                    if (gatherData != null && gatherData.getReturnStateInfo() != null ) {
                        ReturnStateInfo returnStateInfo = gatherData.getReturnStateInfo();
                        if ("0000".equals(returnStateInfo.getReturnCode())) {
                            log.info("大企业接口返回成功，记录请求批次");
                            DqyTsApplyResultResp rzInvoiceResultResp = JSONObject.parseObject(Base64.decodeStr(gatherData.getData()), DqyTsApplyResultResp.class);
                            if("Y".equals(rzInvoiceResultResp.getBatchState())){
                                if(ConfigureConstant.STRING_2.equals(rzInvoiceResultResp.getStatus())){
                                    log.info("返回status为等待确认结果，等待下次定时任务执行");
                                    continue;
                                }else if(ConfigureConstant.STRING_3.equals(rzInvoiceResultResp.getStatus())){
                                    log.info("返回status为{}确认失败。failreason:{}",rzInvoiceResultResp.getStatus(),rzInvoiceResultResp.getFailReason());
                                    if("2".equals(rzInvoiceResultResp.getFailReason())){
                                        log.info("status为3确认失败，failreason为2已申请确认。代表处理中，定时任务数据保持N");
                                        continue;
                                    }
                                    log.info("更新批次表为获取结果为Y");
                                    tDxLqApplyStatRecordDao.update(null, new LambdaUpdateWrapper<TDxLqApplyStatRecordEntity>()
                                            .set(TDxLqApplyStatRecordEntity::getResultStatus, "Y")
                                            .eq(TDxLqApplyStatRecordEntity::getPclsh, rzInvoiceResultResp.getBatchNo())
                                            .eq(TDxLqApplyStatRecordEntity::getNsrsbh, rzInvoiceResultResp.getBuyerTaxNo())
                                    );
                                    log.info("更新退税统计表为确认失败");
                                    TdxDkTsCountEntity tdxDkTsCountEntity = tdxDkTsCountDao.selectOne(new LambdaQueryWrapper<TdxDkTsCountEntity>()
                                            .eq(TdxDkTsCountEntity::getTaxno, rzInvoiceResultResp.getBuyerTaxNo())
                                            .eq(TdxDkTsCountEntity::getSkssq, rzInvoiceResultResp.getRzskssq())
                                    );
                                    tdxDkTsCountEntity.setApplyStatus(ConfigureConstant.STRING_4);
                                    tdxDkTsCountEntity.setFailReason(rzInvoiceResultResp.getFailReason());
                                    tdxDkTsCountEntity.setQrStatus(ConfigureConstant.STRING_3);
                                    tdxDkTsCountEntity.setUpdateTime(new Date());
                                    tdxDkTsCountDao.updateById(tdxDkTsCountEntity);
                                    continue;
                                }else if(ConfigureConstant.STRING_4.equals(rzInvoiceResultResp.getStatus())){
                                    log.info("返回status为确认成功，更新批次表和底账表状态");
                                    log.info("更新批次表为成功");
                                    tDxLqApplyStatRecordDao.update(null, new LambdaUpdateWrapper<TDxLqApplyStatRecordEntity>()
                                        .set(TDxLqApplyStatRecordEntity::getResultStatus, "Y")
                                        .eq(TDxLqApplyStatRecordEntity::getPclsh, rzInvoiceResultResp.getBatchNo())
                                        .eq(TDxLqApplyStatRecordEntity::getNsrsbh, rzInvoiceResultResp.getBuyerTaxNo())
                                    );
                                    log.info("更新退税统计表为确认成功");
                                    TdxDkTsCountEntity tdxDkTsCountEntity = tdxDkTsCountDao.selectOne(new LambdaQueryWrapper<TdxDkTsCountEntity>()
                                            .eq(TdxDkTsCountEntity::getTaxno, rzInvoiceResultResp.getBuyerTaxNo())
                                            .eq(TdxDkTsCountEntity::getSkssq, rzInvoiceResultResp.getRzskssq())
                                    );
                                    tdxDkTsCountEntity.setApplyStatus(ConfigureConstant.STRING_4);
                                    tdxDkTsCountEntity.setQrStatus(ConfigureConstant.STRING_2);
                                    tdxDkTsCountEntity.setQrDate(rzInvoiceResultResp.getSignDate());
                                    tdxDkTsCountEntity.setUpdateTime(new Date());

                                    tdxDkTsCountDao.update(tdxDkTsCountEntity, new LambdaUpdateWrapper<TdxDkTsCountEntity>()
                                         .set(TdxDkTsCountEntity::getFailReason ,null  )
                                        .eq(TdxDkTsCountEntity::getId, tdxDkTsCountEntity.getId())
                                    );

                                    if(CollectionUtils.isNotEmpty(rzInvoiceResultResp.getList())){
                                        log.info("入库退税统计明细表" );
                                        for (int j = 0; j < rzInvoiceResultResp.getList().size(); j++) {
                                            DqyTsApplyResultRespItem dqyTsApplyResultRespItem = rzInvoiceResultResp.getList().get(j);
                                            TdxDkTsCountDetailEntity tdxDkTsCountDetailEntity = new TdxDkTsCountDetailEntity();
                                            tdxDkTsCountDetailEntity.setTaxno(rzInvoiceResultResp.getBuyerTaxNo());
                                            tdxDkTsCountDetailEntity.setQrMonth(rzInvoiceResultResp.getRzskssq());
                                            tdxDkTsCountDetailEntity.setQrDate(rzInvoiceResultResp.getSignDate());
                                            tdxDkTsCountDetailEntity.setQrjglx(ConfigureConstant.STRING_1);
                                            tdxDkTsCountDetailEntity.setInvoiceType(dqyTsApplyResultRespItem.getInvoiceType());
                                            tdxDkTsCountDetailEntity.setTotalTaxAmount(dqyTsApplyResultRespItem.getTotalTaxAmount());
                                            tdxDkTsCountDetailEntity.setTotalNumber(dqyTsApplyResultRespItem.getTotalNumber());
                                            tdxDkTsCountDetailEntity.setCompany(ccm.getCompany());
                                            tdxDkTsCountDetailDao.insert(tdxDkTsCountDetailEntity);
                                        }
                                    }
                                }
                            }else{
                                log.info("大企业返回结果状态batchState为N，未处理完成");
                            }
                        }else{
                            log.info("大企业接口返回失败。报文:{}", JsonUtils.getInstance().toJsonString(returnStateInfo));
                        }
                    }else{
                        log.info("大企业接口返回失败：{}", JsonUtils.getInstance().toJsonString(gatherData));
                    }
                }catch (Exception e) {
                    log.info("退税确认结果开始执行失败{}",e);
                }
            }
        }
    }

    /**
     * @Description 页面退税确认申请
     * @Author wangruwei
     * @Date 2024/3/14 15:26
     **/
    @Override
    public Map<String,String> taxRefundApplyPage(String nsrsbh,String rzhBelongDate) {
        Map<String,String> result = new HashMap();
        log.info("退税确认申请开始");
        //发票和缴款书明细数据
        List<CollectionControlModel> dqyTaxNo = coreSysEnterpriseConfigCoreDao.getDqyTaxNo();
        List<CollectionControlModel> collect = dqyTaxNo.stream().filter(e -> nsrsbh.equals(e.getNsrsbh())).collect(Collectors.toList());
        if(CollectionUtils.isEmpty(collect)){
            log.info("税号不属于大企业");
            result.put("code", "9999");
            result.put("msg", "税号不属于大企业");
            return result;
        }
        CollectionControlModel ccm = collect.get(0);

        DqyTsApplyReq dqyTsApplyReq =  new DqyTsApplyReq();
        dqyTsApplyReq.setBatchNo(Dqyjkdyutil.getBatchNo());
        dqyTsApplyReq.setBuyerTaxNo(ccm.getNsrsbh());
        dqyTsApplyReq.setRzskssq(rzhBelongDate);
        BaseResJson gatherData = Dqyjkdyutil.call(new HashMap<>(), CoreConstants.invoiceTsQrSq, ccm.getAceId(),ccm.getAcekey(), dqyTsApplyReq);
        log.info(JSON.toJSONString(gatherData));
        log.info("退税申请响应请求数据为=" + JSON.toJSONString(gatherData));
        try {
            if (gatherData != null && gatherData.getReturnStateInfo() != null ) {
                ReturnStateInfo returnStateInfo = gatherData.getReturnStateInfo();
                if ("0000".equals(returnStateInfo.getReturnCode())) {
                    log.info("大企业接口返回成功，记录请求批次");
                    TDxLqApplyStatRecordEntity tDxLqApplyStatRecordEntity = new TDxLqApplyStatRecordEntity();
                    tDxLqApplyStatRecordEntity.setNsrsbh(ccm.getNsrsbh());
                    tDxLqApplyStatRecordEntity.setSkssq(dqyTsApplyReq.getRzskssq());
                    tDxLqApplyStatRecordEntity.setPclsh(dqyTsApplyReq.getBatchNo());
                    tDxLqApplyStatRecordEntity.setSqlx(ConfigureConstant.STRING_5);
                    tDxLqApplyStatRecordEntity.setResultStatus("N");
                    tDxLqApplyStatRecordEntity.setCreateDate(new Date());
                    tDxLqApplyStatRecordDao.insert(tDxLqApplyStatRecordEntity);

                    log.info("记录退税统计表和明细表");
                    //t_dx_dk_ts_count  t_dx_dk_ts_count_detail
                    TdxDkTsCountEntity tdxDkTsCountEntity = new TdxDkTsCountEntity();
                    tdxDkTsCountEntity.setTaxno(ccm.getNsrsbh());
                    tdxDkTsCountEntity.setTaxname(ccm.getTaxname());
                    tdxDkTsCountEntity.setSkssq(dqyTsApplyReq.getRzskssq());
                    tdxDkTsCountEntity.setApplyStatus(ConfigureConstant.STRING_1);
                    tdxDkTsCountEntity.setQrStatus(ConfigureConstant.STRING_1);
                    Calendar calendar = Calendar.getInstance();
                    String yyyyMM = new SimpleDateFormat("yyyyMM").format(calendar.getTime());
                    if(yyyyMM.equals(dqyTsApplyReq.getRzskssq())){
                        tdxDkTsCountEntity.setSfdqskssq("1");
                    }else{
                        tdxDkTsCountEntity.setSfdqskssq("0");
                    }
                    tdxDkTsCountEntity.setCompany(ccm.getCompany());
                    tdxDkTsCountEntity.setCreateTime(new Date());
                    //先删除统计，再插入新的记录。退税可以多次请求
                    tdxDkTsCountDao.delete(new LambdaQueryWrapper<TdxDkTsCountEntity>().eq(TdxDkTsCountEntity::getTaxno, ccm.getNsrsbh())
                            .eq(TdxDkTsCountEntity::getSkssq, dqyTsApplyReq.getRzskssq())
                    );
                    tdxDkTsCountDetailDao.delete(new LambdaQueryWrapper<TdxDkTsCountDetailEntity>().eq(TdxDkTsCountDetailEntity::getTaxno, ccm.getNsrsbh())
                            .eq(TdxDkTsCountDetailEntity::getQrMonth, dqyTsApplyReq.getRzskssq())
                    );
                    tdxDkTsCountDao.insert(tdxDkTsCountEntity);
                    //成功不返回
                    result.put("code", "0000");
                    result.put("batchNo", dqyTsApplyReq.getBatchNo());
                    return result;
                }else{
                    log.info("大企业接口返回失败。报文:{}", JsonUtils.getInstance().toJsonString(returnStateInfo));
                    result.put("code", "9999");
                    result.put("msg", "申请失败："+returnStateInfo.getReturnMessage());
                    return result;
                }
            }else{
                log.info("大企业接口返回失败：{}", JsonUtils.getInstance().toJsonString(gatherData));
                result.put("code", "9999");
                result.put("msg", "申请失败：企业接口返回失败");
                return result;
            }
        }catch (Exception e) {
            log.info("退税确认申请开始执行失败{}",e);
            result.put("code", "9999");
            result.put("msg", "申请失败：企业接口返回失败");
            return result;
        }
    }

}
