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

import cn.hutool.core.codec.Base64;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dxhy.common.constant.DbConstant;
import com.dxhy.common.datasource.config.DynamicContextHolder;
import com.dxhy.core.dao.BasisSysDeptCfgDao;
import com.dxhy.core.dao.ConfirmDao;
import com.dxhy.core.entity.BasisSysDeptCfg;
import com.dxhy.core.job.dao.ApplyStatDao;
import com.dxhy.core.job.dao.TDxApplyStatRecordDao;
import com.dxhy.core.job.dao.TDxDkCountDao;
import com.dxhy.core.job.dao.TDxDkCountDetailDao;
import com.dxhy.core.job.entity.*;
import com.dxhy.core.job.pojo.*;
import com.dxhy.core.job.service.ApplyService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

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

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

    @Value("${jxjk.collectUrl}")
    private String url;
    @Value("${jxjk.applyStat}")
    private String applyStat;
    @Value("${jxjk.applyStatStatus}")
    private String applyStatResult;
    @Value("${jxjk.applyConfirm}")
    private String applyConfirm;
    @Value("${jxjk.applyConfirmStatus}")
    private String applyConfirmResult;
    @Value("${jxjk.applyCount}")
    private String applyCount;
    @Value("${jxjk.enterpriseCode}")
    private String enterpriseCode;
    @Value("${jxjk.version}")
    private String version;
    @Value("${jxjk.appId}")
    private String appid;

    @Value("${setPwd}")
    private String setPwd;
    @Value("${resetPwd}")
    private String resetPwd;

    @Resource
    private ApplyStatDao applyStatDao;

    @Resource
    private MakeAppSecService makeAppSecService;
    @Resource
    private ConfirmDao confirmDao;
    @Resource
    private TDxApplyStatRecordDao tDxApplyStatRecordDao;
    @Resource
    private TDxDkCountDetailDao tDxDkCountDetailDao;
    @Resource
    private TDxDkCountDao dkCountDao;
    @Resource
    private BasisSysDeptCfgDao basisSysDeptCfgDao;

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

        // 查询数据库 遍历数据源
        DynamicContextHolder.push(DbConstant.BASICS_READ);
        List<String> dbList = confirmDao.getDbSource();
        for (String db : dbList) {
            DynamicContextHolder.push(db + DbConstant.BUSINESS_READ);
            // 获取数据库中申请的数据
            List<TDxDkCount> list = applyStatDao.getApplyData();
            String dataExchangeId = makeExchangeId();
            // 发送申请接口
            for (TDxDkCount dkentity : list) {
                try {
                    DynamicContextHolder.push(DbConstant.BASICS_READ);
                    //判断是否为大企业税号
                    BasisSysDeptCfg baseSysDeptCfg = basisSysDeptCfgDao.selectOne(new QueryWrapper<BasisSysDeptCfg>().eq("nsrsbh", dkentity.getTaxno()));
                    if (baseSysDeptCfg != null) {
                        continue;
                    }
                    // 通过税号获取id和key
                    TAcOrg org = confirmDao.findIdAndKeyByTaxno(dkentity.getTaxno());
                    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(), appid, enterpriseCode, applyStat,
                        version, base64Data, dataExchangeId, org.getAceKey());
                    log.info("本地请求生成加密串=======" + appSec);
                    requstData = requestData(appSec, dataExchangeId, base64Data, applyStat, org.getAceId());
                    log.info("申请统计请求报文为=======" + requstData);
                    tDxHttpLog.setReqText(requstData);
                    tDxHttpLog.setReqDate(new Date());
                    // 发送请求
                    String responseJson = HttpUtil.post(url, 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");
                    confirmDao.insert(tDxHttpLog);
                    e.printStackTrace();
                    log.error("执行定时任务报错,报错信息是:{}",e);
                }
            }
        }
        log.info("申请统计接口结束");
    }

    /**
     * 查询数据库，获取申请统计结果
     */
    @Override
    public void getApplyStatResult() {
        log.info("进入申请统计结果获取执行方法--");
        // 查询数据库 遍历数据源
        DynamicContextHolder.push(DbConstant.BASICS_READ);
        List<String> dbList = confirmDao.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);
                    //判断是否为大企业税号
                    BasisSysDeptCfg baseSysDeptCfg = basisSysDeptCfgDao.selectOne(new QueryWrapper<BasisSysDeptCfg>().eq("nsrsbh", entity.getTaxno()));
                    if (baseSysDeptCfg != null) {
                        continue;
                    }
                    // 通过税号获取id和key
                    TAcOrg org = confirmDao.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(), appid, enterpriseCode, applyStatResult,
                        version, base64Data, dataExchangeId, org.getAceKey());
                    log.info("本地请求生成加密串=======" + appSec);
                    // 请求报文拼接
                    String requstData =
                        requestData(appSec, dataExchangeId, base64Data, applyStatResult, org.getAceId());
                    log.info("统计结果获取请求报文为=======" + requstData);
                    // 发送请求返回请求报文
                    tDxHttpLog.setReqText(requstData);
                    tDxHttpLog.setReqDate(new Date());
                    String responseJson;
                    responseJson = HttpUtil.post(url, 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) {
                                                TDxDkCountDetail detail = new TDxDkCountDetail();
                                                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);
                                            }
                                        }
                                        // 撤销统计
                                        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");
                        confirmDao.insert(tDxHttpLog);
                        e.printStackTrace();
                        log.error("执行定时任务报错,报错信息是:{}",e);
                    }
                }

            } catch (Exception e1) {

                DynamicContextHolder.push(db + DbConstant.BUSINESS_WRITE);
                tDxHttpLog.setStatus("2");
                confirmDao.insert(tDxHttpLog);
                e1.printStackTrace();
                log.error("执行定时任务报错,报错信息是:{}",e1);
            }
        }
    }

    /**
     * 解析统计结果信息 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(result[0]);
                    entity.setDkInvoiceNum(result[1]);
                    entity.setDkTotalAmount(result[2]);
                    entity.setTotalYxAmount(result[3]);
                    entity.setBdkInvoiceNum(result[4]);
                    entity.setBdkTotalAmount(result[5]);
                    entity.setBdkTotalYxAmount(result[6]);
                    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(appid);
            globalInfo.setDataExchangeId(dataExchangeId);
            globalInfo.setEnterpriseCode(enterpriseCode);
            globalInfo.setInterfaceCode(interfaceCode);
            globalInfo.setVersion(version);
            periodRequestData.setGlobalInfo(globalInfo);
            periodRequestData.setData(base64Data);
            requstData = JSONObject.toJSONString(periodRequestData);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return requstData;
    }

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

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

            // 获取数据库中申请的数据
            List<TDxDkCount> list = applyStatDao.getApplyConfirmData();
            String dataExchangeId = makeExchangeId();
            // 发送申请接口
            for (TDxDkCount dkentity : list) {
                try {
                    DynamicContextHolder.push(DbConstant.BASICS_READ);
                    //判断是否为大企业税号
                    BasisSysDeptCfg baseSysDeptCfg = basisSysDeptCfgDao.selectOne(new QueryWrapper<BasisSysDeptCfg>().eq("nsrsbh", dkentity.getTaxno()));
                    if (baseSysDeptCfg != null) {
                        continue;
                    }
                    // 通过税号获取id和key
                    TAcOrg org = confirmDao.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(), appid, enterpriseCode, applyConfirm,
                        version, base64Data, dataExchangeId, org.getAceKey());
                    log.info("本地请求生成加密串=======" + appSec);
                    requstData = requestData(appSec, dataExchangeId, base64Data, applyConfirm, org.getAceId());
                    log.info("申请确认请求报文为=======" + requstData);
                    tDxHttpLog.setReqText(requstData);
                    tDxHttpLog.setReqDate(new Date());
                    // 发送请求
                    String responseJson = HttpUtil.post(url, 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");
                    confirmDao.insert(tDxHttpLog);
                    e.printStackTrace();
                    log.error("执行定时任务报错,报错信息是:{}",e);
                }
            }
        }
        log.info("申请确认接口结束");
    }

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

        // 查询数据库 遍历数据源
        DynamicContextHolder.push(DbConstant.BASICS_READ);
        List<String> dbList = confirmDao.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);
                    //判断是否为大企业税号
                    BasisSysDeptCfg baseSysDeptCfg = basisSysDeptCfgDao.selectOne(new QueryWrapper<BasisSysDeptCfg>().eq("nsrsbh", entity.getTaxno()));
                    if (baseSysDeptCfg != null) {
                        continue;
                    }
                    // 通过税号获取id和key
                    TAcOrg org = confirmDao.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(), appid, enterpriseCode,
                        applyConfirmResult, version, base64Data, dataExchangeId, org.getAceKey());
                    log.info("本地请求生成加密串=======" + appSec);
                    // 请求报文拼接
                    String requstData =
                        requestData(appSec, dataExchangeId, base64Data, applyConfirmResult, org.getAceId());
                    log.info("统计结果获取请求报文为=======" + requstData);
                    // 发送请求返回请求报文
                    tDxHttpLog.setReqText(requstData);
                    tDxHttpLog.setReqDate(new Date());
                    String responseJson;
                    responseJson = HttpUtil.post(url, 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());
                                    }
                                }
                            }
                        }
                    } catch (Exception e) {
                        DynamicContextHolder.push(db + DbConstant.BUSINESS_WRITE);
                        tDxHttpLog.setStatus("2");
                        confirmDao.insert(tDxHttpLog);
                        e.printStackTrace();
                        log.error("执行定时任务报错,报错信息是:{}",e);
                    }
                }

            } catch (Exception e1) {

                DynamicContextHolder.push(db + DbConstant.BUSINESS_WRITE);
                tDxHttpLog.setStatus("2");
                confirmDao.insert(tDxHttpLog);
                e1.printStackTrace();
                log.error("执行定时任务报错,报错信息是:{}",e1);
            }
        }

    }

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

            // 查询数据库
            String dataExchangeId = makeExchangeId();
            TDxHttpLog tDxHttpLog = new TDxHttpLog();
            tDxHttpLog.setType("10");
            tDxHttpLog.setReqDate(new Date());
            tDxHttpLog.setResDate(new Date());
            // 获取统计信息
            ApplyStatPo batchData = new ApplyStatPo();
            try {
                List<TAcOrg> orgList = confirmDao.getUpgradTaxno();
                if (orgList != null && orgList.size() > 0) {
                    for (TAcOrg acOrg : orgList) {
                        //判断是否为大企业税号
                        DynamicContextHolder.push(DbConstant.BASICS_READ);
                        BasisSysDeptCfg baseSysDeptCfg = basisSysDeptCfgDao.selectOne(new QueryWrapper<BasisSysDeptCfg>().eq("nsrsbh", acOrg.getTaxno()));
                        if (baseSysDeptCfg != null) {
                            continue;
                        }

                        DynamicContextHolder.push(db + DbConstant.BUSINESS_READ);
                        TaxCurrent current = confirmDao.qryTaxCurrent(acOrg.getTaxno());
                        List<TDxDkCount> dkList = confirmDao.findAllDkCount(acOrg.getTaxno());
                        if (current != null) {
                            String taxno = current.getCurTaxno();
                            String curskssq = current.getIncomeMoth();
                            LocalDate localDate = LocalDate.of(Integer.parseInt(curskssq.substring(0, 4)),
                                Integer.parseInt(curskssq.substring(4)), 1);
                            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;
                                TDxDkCount tDxDkCount = null;
                                for (TDxDkCount count : dkList) {
                                    if (skssq.equals(count.getSkssq())) {
                                        existFlag = true;
                                        tDxDkCount = count;
                                        //非当前所属期统计成功的不再获取统计信息
                                        if (!"1".equals(count.getSfdqskssq()) && "2".equals(count.getTjStatus())) {
                                            flag = false;
                                        }
                                    }
                                }
                                if (curskssq.equals(skssq)) {
                                    curFalg = true;
                                }
                                // 若不是当前属期，且统计表包含则不调用
                                if (flag) {
                                    DynamicContextHolder.push(DbConstant.BASICS_READ);
                                    // 通过税号获取id和key
                                    TAcOrg org = confirmDao.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(), appid, enterpriseCode,
                                        applyCount, version, base64Data, dataExchangeId, org.getAceKey());
                                    log.info("本地请求生成加密串=======" + appSec);
                                    // 请求报文拼接
                                    String requstData =
                                        requestData(appSec, dataExchangeId, base64Data, applyCount, org.getAceId());
                                    log.info("获取统计信息请求报文为=======" + requstData);
                                    // 发送请求返回请求报文
                                    tDxHttpLog.setReqText(requstData);
                                    String responseJson;
                                    responseJson = HttpUtil.post(url, requstData, 60000);
                                    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) {
                                                        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);
                                                                TDxDkCount dkCount = new TDxDkCount();
                                                                dkCount.setTjStatus("2");
                                                                if ("03".equals(result.getCountFlag())) {
                                                                    dkCount.setQsStatus("2");
                                                                    if (!"2".equals(tDxDkCount.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(tDxDkCount.getQrDate());
                                                                        }
                                                                    }
                                                                    if (tDxDkCount != null
                                                                        && "2".equals(tDxDkCount.getCxqsStatus())) {
                                                                        dkCount.setCxqsStatus("0");
                                                                    }
                                                                } else {
                                                                    if (tDxDkCount != null
                                                                        && "2".equals(tDxDkCount.getQsStatus())) {
                                                                        dkCount.setQsStatus("0");
                                                                        dkCount.setQrDate(null);
                                                                    }
                                                                }
                                                                if (tDxDkCount != null
                                                                    && "2".equals(tDxDkCount.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());
                                                                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);
                                                                    }
                                                                }
                                                                // 删除旧明细
                                                                ApplyStatResult statResult = new ApplyStatResult();
                                                                statResult.setBuyerTaxNo(dkCount.getTaxno());
                                                                statResult.setStatisticMonth(dkCount.getSkssq());
                                                                applyStatDao.deleteDetailBySkssq(statResult,
                                                                    dkCount.getSkssq());
                                                                // 增加新明细
                                                                for (StatResult stat : reslist) {
                                                                    TDxDkCountDetail detail = new TDxDkCountDetail();
                                                                    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);
                                                                }
                                                            }
                                                        } else if ("01".equals(result.getCountFlag())) {
                                                            if ("00".equals(result.getCountStatus())) {
                                                                if (tDxDkCount != null
                                                                    && "2".equals(tDxDkCount.getTjStatus())) {
                                                                    ApplyStatResult statResult = new ApplyStatResult();
                                                                    statResult.setBuyerTaxNo(taxno);
                                                                    statResult.setStatisticMonth(skssq);
                                                                    applyStatDao.deleteDetailBySkssq(statResult, skssq);
                                                                    applyStatDao.updateCxCount(taxno, skssq);
                                                                }
                                                            }

                                                        }
                                                    } else {
                                                        if ("20".equals(result.getCountStatus())
                                                            || "22".equals(result.getCountStatus())) {
                                                            String res = result.getCountReport();
                                                            List<StatResult> reslist = string2List(res);
                                                            TDxDkCount dkCount = new TDxDkCount();
                                                            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);
                                                            }

                                                            // 删除旧明细
                                                            ApplyStatResult statResult = new ApplyStatResult();
                                                            statResult.setBuyerTaxNo(dkCount.getTaxno());
                                                            statResult.setStatisticMonth(dkCount.getSkssq());
                                                            applyStatDao.deleteDetailBySkssq(statResult,
                                                                dkCount.getSkssq());
                                                            // 增加新明细
                                                            for (StatResult stat : reslist) {
                                                                TDxDkCountDetail detail = new TDxDkCountDetail();
                                                                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);
                                                            }
                                                        }
                                                    }

                                                }

                                            }
                                        }
                                    } catch (Exception e) {
                                        DynamicContextHolder.push(db + DbConstant.BUSINESS_WRITE);
                                        tDxHttpLog.setStatus("2");
                                        confirmDao.insert(tDxHttpLog);
                                        e.printStackTrace();
                                        log.error("执行定时任务报错,报错信息是:{}",e);
                                    }
                                }

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

            } catch (Exception e1) {
                log.error("执行定时任务报错,报错信息是:{}",e1);
                DynamicContextHolder.push(db + DbConstant.BUSINESS_WRITE);
                tDxHttpLog.setStatus("2");
                confirmDao.insert(tDxHttpLog);
                e1.printStackTrace();

            }
        }
    }

    public void insertDkCount(TAcOrg acOrg, String skssq, boolean qsFlag, String tjDate, boolean curflag) {
        TDxDkCount dkCount1 = new TDxDkCount();
        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 = confirmDao.findIdAndKeyByTaxno(params.get("taxno"));
            // 加密请求数据
            String requstData = null;
            String dataStr = JSONObject.toJSONString(params);
            String base64Data = Base64.encode(dataStr);
            // 生成加密串
            String appSec = makeAppSecService.makeAppSec(orgkey.getAceId(), appid, enterpriseCode, setPwd, version,
                base64Data, dataExchangeId, orgkey.getAceKey());
            log.info("本地请求生成加密串=======" + appSec);
            requstData = requestData(appSec, dataExchangeId, base64Data, setPwd, orgkey.getAceId());
            log.info("设置密码请求报文为=======" + requstData);
            // 发送请求
            String responseJson = HttpUtil.post(url, 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) {
            e.printStackTrace();
        }

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

    @Override
    public String resetPwd(Map<String, String> params) {
        log.info("重置密码接口开始");
        String dataExchangeId = makeExchangeId();
        // 发送申请接口
        try {
            DynamicContextHolder.push(DbConstant.BASICS_READ);
            TAcOrg orgkey = confirmDao.findIdAndKeyByTaxno(params.get("taxno"));
            String requstData = null;
            String dataStr = JSONObject.toJSONString(params);
            String base64Data = Base64.encode(dataStr);
            // 生成加密串
            String appSec = makeAppSecService.makeAppSec(orgkey.getAceId(), appid, enterpriseCode, resetPwd, version,
                base64Data, dataExchangeId, orgkey.getAceKey());
            log.info("本地请求生成加密串=======" + appSec);
            requstData = requestData(appSec, dataExchangeId, base64Data, resetPwd, orgkey.getAceId());
            log.info("重置密码请求报文为=======" + requstData);
            // 发送请求
            String responseJson = HttpUtil.post(url, 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) {
            e.printStackTrace();
        }

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

}
