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

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import javax.annotation.Resource;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.dxhy.common.constant.DictConstant;
import com.dxhy.common.service.DictdetaServcice;
import com.dxhy.core.dao.BasisSysDeptCfgDao;
import com.dxhy.core.entity.BasisSysDeptCfg;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dxhy.common.constant.DbConstant;
import com.dxhy.common.datasource.config.DynamicContextHolder;
import com.dxhy.common.service.InvoiceLogService;
import com.dxhy.common.vo.InvoiceLog;
import com.dxhy.core.dao.ConfirmDao;
import com.dxhy.core.dao.TDxApplyRecordDao;
import com.dxhy.core.entity.TDxRecordInvoice;
import com.dxhy.core.job.dao.TDxDkCountDao;
import com.dxhy.core.job.dao.TDxTaxCurrentDao;
import com.dxhy.core.job.dao.TDxTaxHandlelogDao;
import com.dxhy.core.job.entity.*;
import com.dxhy.core.job.pojo.*;
import com.dxhy.core.job.service.ConfirmService;

import cn.hutool.core.codec.Base64;
import cn.hutool.http.HttpUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.CollectionUtils;

/**
 * 接口服务 发票认证接口 认证接口获取接口 属期获取接口
 *
 * @author 陈刚扬
 * @date 2020/10/28
 * @return
 */
@SuppressWarnings({"AlibabaUndefineMagicConstant", "AlibabaMethodTooLong", "DuplicatedCode"})
@Service("confirmService")
@Slf4j

public class ConfirmServiceImpl extends ServiceImpl<ConfirmDao, TDxHttpLog> implements ConfirmService {

    @Value("${jxjk.collectUrl}")
    private String url;
    @Value("${jxjk.taxperiod}")
    private String taxperiod;
    @Value("${jxjk.ltgalizeStatus}")
    private String ltgalizeResult;
    @Value("${jxjk.applyLtgalize}")
    private String applyLtgalize;
    @Value("${jxjk.enterpriseCode}")
    private String enterpriseCode;
    @Value("${jxjk.version}")
    private String version;
    @Value("${jxjk.appId}")
    private String appid;

    @Resource
    private ConfirmDao confirmDao;
    @Resource
    private TDxApplyRecordDao tDxApplyRecordDao;
    @Resource
    private MakeAppSecService makeAppSecService;

    @Resource
    private TDxTaxHandlelogDao tDxTaxHandlelogDao;
    @Resource
    private TDxTaxCurrentDao taxCurrentDao;
    @Resource
    private TDxDkCountDao tDxDkCountDao;
    @Resource
    private InvoiceLogService invoiceLogService;
    @Resource
    private DictdetaServcice dictdetaServcice;
    @Resource
    private BasisSysDeptCfgDao basisSysDeptCfgDao;

    @Override
    public void getTaxCurrent() {
        log.info("进入属期获取执行方法");
        TDxHttpLog tDxHttpLog = null;

        PeriodData taxnodata = new PeriodData();
        TAcOrg org;
        try {
            String dataExchangeId = makeExchangeId();
            // 查询税号
            DynamicContextHolder.push(DbConstant.BASICS_READ);
            List<TAcOrg> list = confirmDao.getTaxno();

            if (list != null && list.size() > 0) {
                for (TAcOrg tAcOrg : list) {

                    DynamicContextHolder.push(DbConstant.BASICS_READ);

                    BasisSysDeptCfg baseSysDeptCfg = basisSysDeptCfgDao.selectOne(new QueryWrapper<BasisSysDeptCfg>().eq("nsrsbh", tAcOrg.getTaxno()));
                    if (baseSysDeptCfg != null) {
                        continue;
                    }
                    tDxHttpLog = new TDxHttpLog();
                    tDxHttpLog.setType("05");
                    // 加密请求数据
                    org = tAcOrg;
                    String db = org.getDbName();
                    String aceId = org.getAceId();
                    String aceKey = org.getAceKey();
                    tDxHttpLog.setTaxno(org.getTaxno());
                    taxnodata.setTaxno(org.getTaxno());
                    String requstData;
                    String dataStr = JSONObject.toJSONString(taxnodata);
                    String base64Data = Base64.encode(dataStr);
                    // 生成加密串
                    String appSec = makeAppSecService.makeAppSec(aceId, appid, enterpriseCode, taxperiod, version,
                        base64Data, dataExchangeId, aceKey);
                    log.info("本地请求生成加密串=======" + appSec);
                    requstData = requestData(appSec, dataExchangeId, base64Data, taxperiod, aceId);
                    log.info("属期获取请求报文为=======" + requstData);
                    tDxHttpLog.setReqText(requstData);
                    tDxHttpLog.setReqDate(new Date());
                    // 发送请求
                    String responseJson = HttpUtil.post(url, requstData, 120000);
                    tDxHttpLog.setResDate(new Date());
                    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();
                                TaxCurrent taxCurrent =
                                    JSONObject.parseObject(Base64.decodeStr(data), TaxCurrent.class);
                                DynamicContextHolder.push(db + DbConstant.BUSINESS_READ);
                                TaxCurrent taxCurrent1 = confirmDao.qryTaxCurrent(org.getTaxno());
                                String indexInfo = taxCurrent.getIndexInfo();
                                if (StringUtils.isNotBlank(indexInfo)) {
                                    String[] arr = indexInfo.split(";");
                                    taxCurrent.setPeriodIndexInfo(arr[0]);
                                    if (arr.length > 1) {
                                        taxCurrent.setMonthIndexInfo(arr[1]);
                                    }
                                }
                                int count = 0;
                                DynamicContextHolder.push(db + DbConstant.BUSINESS_WRITE);
                                if (taxCurrent1 != null) {
                                    count = confirmDao.findDkCount(org.getTaxno(), taxCurrent1.getIncomeMoth());
                                    taxCurrent.setLatchStatus(taxCurrent1.getLatchStatus());
                                    taxCurrent.setLimitDkse(taxCurrent1.getLimitDkse());
                                    String newTaxCurrent = taxCurrent.getIncomeMoth();
                                    String oldTaxCurrent = taxCurrent1.getIncomeMoth();
                                    if (newTaxCurrent != null && !newTaxCurrent.equals(oldTaxCurrent)) {
                                        taxCurrent.setLimitDkse(null);
                                        if ("1".equals(taxCurrent1.getLatchStatus())) {

                                            taxCurrent.setLatchStatus("0");
                                            TaxHandlelog handlelog = new TaxHandlelog();
                                            handlelog.setHandleType("0");
                                            handlelog.setUserAccount(null);
                                            handlelog.setUserName("系统");
                                            handlelog.setPeriod(newTaxCurrent);
                                            handlelog.setTaxno(org.getTaxno());
                                            tDxTaxHandlelogDao.insert(handlelog);
                                        }
                                        if (newTaxCurrent.compareTo(oldTaxCurrent) > 0) {
                                            // 更新当前税款所属期 -- 是否当前税款所属期
                                            List<TDxDkCount> allDkCount = confirmDao.findAllDkCount(taxCurrent.getCurTaxno());
                                            if(!CollectionUtils.isEmpty(allDkCount)){
                                                allDkCount.stream().forEach(tDxDkCount->{
                                                    if(tDxDkCount!=null && "0".equals(tDxDkCount.getQsStatus())){
                                                        confirmDao.updateDkCounts(taxCurrent.getCurTaxno(),tDxDkCount.getSkssq());
                                                    }else {
                                                        confirmDao.updateDkCount(taxCurrent.getCurTaxno());
                                                    }
                                                });
                                            }
                                            // 属期变更插入抵扣信息表
                                            insertDkCount(org, taxCurrent);
                                        } else if (newTaxCurrent.compareTo(oldTaxCurrent) < 0) {
                                            confirmDao.deleteDkCount(taxCurrent.getCurTaxno(), newTaxCurrent);
                                            confirmDao.deleteDkCountDetail(taxCurrent.getCurTaxno(), newTaxCurrent);
                                            confirmDao.updateDkCountToNew(taxCurrent.getCurTaxno(), newTaxCurrent);
                                        }
                                    }
                                    confirmDao.updateCurrent(taxCurrent);
                                } else {
                                    TDxTaxCurrent tax = new TDxTaxCurrent();
                                    tax.setTaxno(taxCurrent.getCurTaxno());
                                    tax.setTaxname(taxCurrent.getCompName());
                                    tax.setCurrentTaxPeriod(taxCurrent.getIncomeMoth());
                                    tax.setSelectStartDate(taxCurrent.getSelectStartDate());
                                    tax.setSelectEndDate(taxCurrent.getSelectEndDate());
                                    tax.setOperationEndDate(taxCurrent.getIncomeEndDate());
                                    tax.setOldTaxNo(taxCurrent.getOldTaxno());
                                    tax.setDeclarePeriod(taxCurrent.getAppPeriod());
                                    tax.setCreditRating(taxCurrent.getCompLevel());
                                    tax.setCompanyType(taxCurrent.getCompanyType());
                                    tax.setOilType(taxCurrent.getOilType());
                                    tax.setTaxpayerType(taxCurrent.getTaxpayerType());
                                    tax.setSyncTime(taxCurrent.getSyncTime());
                                    tax.setIndexInfo(taxCurrent.getIndexInfo());
                                    tax.setPeriodIndexInfo(taxCurrent.getPeriodIndexInfo());
                                    tax.setMonthIndexInfo(taxCurrent.getMonthIndexInfo());
                                    tax.setCreateTime(new Date());
                                    taxCurrentDao.insert(tax);

                                }
                                if (count == 0 && taxCurrent1 == null) {
                                    insertDkCount(org, taxCurrent);
                                }

                            }
                        }
                    } catch (Exception e) {
                        tDxHttpLog.setStatus("2");
                        DynamicContextHolder.push(db + DbConstant.BUSINESS_WRITE);
                        confirmDao.insert(tDxHttpLog);
                        e.printStackTrace();
                    }

                }
            } else {
                log.info("没有要获取属期的税号");
            }
        } catch (Exception e) {
            log.info("属期获取执行失败");
            e.printStackTrace();
        }
    }

    private void insertDkCount(TAcOrg org, TaxCurrent taxCurrent) {
        // 插入抵扣统计表
        TDxDkCount entity = new TDxDkCount();
        entity.setTaxno(taxCurrent.getCurTaxno());
        entity.setTaxname(taxCurrent.getCompName());
        entity.setSkssq(taxCurrent.getIncomeMoth());
        entity.setSignStatus("0");
        entity.setCreateDate(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        entity.setSfdqskssq("1");
        entity.setApplyStatus("0");
        entity.setCompany(org.getCompany());
        tDxDkCountDao.insert(entity);
    }

    @Override
    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 String makeExchangeId() {
        SimpleDateFormat tempDate = new SimpleDateFormat("yyyyMMddHHmmss");
        String timestamp = tempDate.format(new java.util.Date());
        return "ZZSPT" + timestamp + "abc";
    }

    @Override
    public void getLtgalizeResult() {
        log.info("进入认证结果获取执行方法");
        TDxHttpLog tDxHttpLog = new TDxHttpLog();
        tDxHttpLog.setType("04");
        BatchData batchData = new BatchData();
        try {
            // 查询数据库 遍历数据源
            DynamicContextHolder.push(DbConstant.BASICS_READ);
            List<String> dbList = confirmDao.getDbSource();
            for (String db : dbList) {
                String dataExchangeId = makeExchangeId();
                DynamicContextHolder.push(db + DbConstant.BUSINESS_READ);
                // 查询认证申请记录表中状态为N的批次号
                List<TDxApplyRecord> list = confirmDao.getBatchNo();
                if (list != null && list.size() > 0) {
                    for (TDxApplyRecord tDxApplyRecord : list) {
                        String batchNo = tDxApplyRecord.getBatchNo();
                        // 请求数据加密
                        batchData.setBatchNo(batchNo);
                        String dataStr = JSONObject.toJSONString(batchData);
                        String base64Data = Base64.encode(dataStr);
                        // 加密串生成
                        String appSec = makeAppSecService.makeAppSec(tDxApplyRecord.getAceId(), appid, enterpriseCode,
                            ltgalizeResult, version, base64Data, dataExchangeId, tDxApplyRecord.getAceKey());
                        log.info("本地请求生成加密串=======" + appSec);
                        // 请求报文拼接
                        String requstData =
                            requestData(appSec, dataExchangeId, base64Data, ltgalizeResult, tDxApplyRecord.getAceId());
                        log.info("认证结果获取请求报文为=======" + requstData);
                        // 发送请求返回请求报文
                        tDxHttpLog.setReqText(requstData);
                        tDxHttpLog.setReqDate(new Date());
                        String 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;
                                        List<LegalizeResult> datalist =
                                            JSONArray.parseArray(dataJosn.getString("invoices"), LegalizeResult.class);
                                        List<InvoiceLog> logList = new ArrayList<>();
                                        for (LegalizeResult legalizeResult : datalist) {
                                            SimpleDateFormat tempDate = new SimpleDateFormat("yyyy-MM-dd");
                                            String uuid =
                                                legalizeResult.getInvoiceCode() + legalizeResult.getInvoiceNo();

                                            log.info(legalizeResult.getLegalizeDate());
                                            if (!"".equals(legalizeResult.getLegalizeDate())
                                                && legalizeResult.getLegalizeDate() != null
                                                && !" ".equals(legalizeResult.getLegalizeDate())) {
                                                rzhDate = tempDate.parse(legalizeResult.getLegalizeDate());
                                            }
                                            if ("0".equals(legalizeResult.getLegalizeState())) {
                                                legalizeResult.setLegalizeType("");
                                            }
                                            // 转换失败原因
                                            String failCode = exchangeFailCode(legalizeResult.getFailureReason());
                                            legalizeResult.setFailureReason(failCode);
                                            DynamicContextHolder.push(db + DbConstant.BUSINESS_WRITE);
                                            InvoiceLog invoiceLog = new InvoiceLog();
                                            invoiceLog.setInvoiceCode(legalizeResult.getInvoiceCode());
                                            invoiceLog.setInvoiceNo(legalizeResult.getInvoiceNo());
                                            invoiceLog.setCreateDate(new Date());
                                            if ("2".equals(legalizeResult.getRzlx())
                                                || "3".equals(legalizeResult.getRzlx())) {
                                                invoiceLog.setType("7");
                                                if ("4".equals(legalizeResult.getAuthState())) {
                                                    legalizeResult.setLegalizeState("1");
                                                    invoiceLog.setInputStatus("3");
                                                } else {
                                                    invoiceLog.setInputStatus("4");
                                                }
                                                confirmDao.updateRecordForDrawback(legalizeResult, uuid, rzhDate);
                                                confirmDao.updateApply(uuid);
                                            } else if ("4".equals(legalizeResult.getRzlx())) {
                                                invoiceLog.setType("5");
                                                if ("4".equals(legalizeResult.getAuthState())) {
                                                    legalizeResult.setLegalizeState("2");
                                                    invoiceLog.setInputStatus("8");
                                                } else {
                                                    invoiceLog.setInputStatus("9");
                                                }
                                                confirmDao.updateRecordForNoDeduction(legalizeResult, uuid, rzhDate);
                                                confirmDao.updateApply(uuid);
                                            } else if ("5".equals(legalizeResult.getRzlx())) {
                                                invoiceLog.setType("2");
                                                if ("4".equals(legalizeResult.getAuthState())) {
                                                    invoiceLog.setInputStatus("16");
                                                } else {
                                                    invoiceLog.setInputStatus("17");
                                                }
                                                // 撤销抵扣 清空认证等字段
                                                confirmDao.updateRecordForRebackRz(legalizeResult, uuid, rzhDate);
                                                confirmDao.updateApply(uuid);
                                            } else if ("6".equals(legalizeResult.getRzlx())) {
                                                invoiceLog.setType("5");
                                                if ("4".equals(legalizeResult.getAuthState())) {
                                                    invoiceLog.setInputStatus("11");
                                                } else {
                                                    invoiceLog.setInputStatus("12");
                                                }
                                                // 如果撤销不抵扣申请成功 更新不抵扣相关字段
                                                confirmDao.updateRecordForRebackNoDeduction(legalizeResult, uuid,
                                                    rzhDate);
                                                confirmDao.updateApply(uuid);
                                            } else {
                                                invoiceLog.setType("2");
                                                if ("4".equals(legalizeResult.getAuthState())) {
                                                    invoiceLog.setInputStatus("3");
                                                } else {
                                                    invoiceLog.setInputStatus("4");
                                                }
                                                confirmDao.updateRecord(legalizeResult, uuid, rzhDate);
                                                confirmDao.updateApply(uuid);
                                            }
                                            logList.add(invoiceLog);
                                        }
                                        if (logList.size() > 0) {
                                            invoiceLogService.toInvoiceLog(logList);
                                        }
                                    }
                                }
                            }
                        } catch (Exception e) {
                            DynamicContextHolder.push(DbConstant.BUSINESS_WRITE);
                            tDxHttpLog.setStatus("2");
                            confirmDao.insert(tDxHttpLog);
                            e.printStackTrace();
                        }
                    }

                } else {
                    log.info("数据库没有未返回认证结果的记录");
                }
            }
        } catch (Exception e) {
            log.info("认证结果获取执行失败");
            e.printStackTrace();
        }
    }

    private String exchangeFailCode(String failureReason) {
        if (!isBlank(failureReason)) {
//            if ("1".equals(failureReason)) {
//                return "成功";
//            }
//            if ("2".equals(failureReason)) {
//                return "无此票";
//            }
//            if ("3".equals(failureReason)) {
//                return "该票异常无法认证";
//            }
//            if ("4".equals(failureReason)) {
//                return "该票已认证";
//            }
//            if ("5".equals(failureReason)) {
//                return "该票已经逾期无法认证";
//            }
//            if ("6".equals(failureReason)) {
//                return "该票已经申请认证";
//            }
//            if ("7".equals(failureReason)) {
//                return "申请认证月份不匹配";
//            }
//            if ("8".equals(failureReason)) {
//                return "其他异常";
//            }
//            if ("9".equals(failureReason)) {
//                return "该票未到期";
//            }
//            if ("10".equals(failureReason)) {
//                return "红票无法认证";
//            }
//            if ("11".equals(failureReason)) {
//                return "认证类型不匹配";
//            }
//            if ("12".equals(failureReason)) {
//                return "信用等级异常";
//            }
//            if ("13".equals(failureReason)) {
//                return "token超过五天未获取";
//            }
//            if ("14".equals(failureReason)) {
//                return "该票不可勾选为逾期";
//            }
//            if ("15".equals(failureReason)) {
//                return "有效税额异常（有效税额大于实际税额）";
//            }
//            if ("16".equals(failureReason)) {
//                return "当期已锁定";
//            }
            String failureReasonName = dictdetaServcice.queryDictName(DictConstant.failureReason, failureReason);
            if (!isBlank(failureReason)) {
                return failureReasonName;
            } else {
                return failureReason;
            }
        }
        return "";
    }

    private static Boolean isBlank(String str) {
        return str == null || str.trim().length() == 0;

    }

    @Override
    public void invoiceLegalize() {

        log.info("进入认证申请认证执行方法");
        ApplyInfo applyInfo = new ApplyInfo();
        TDxHttpLog tDxHttpLog = new TDxHttpLog();
        tDxHttpLog.setType("03");
        try {
            // 查询数据库 遍历数据源
            DynamicContextHolder.push(DbConstant.BASICS_READ);
            List<String> dbList = confirmDao.getDbSource();
            for (String db : dbList) {
                String dataExchangeId = makeExchangeId();
                DynamicContextHolder.push(db + DbConstant.BUSINESS_READ);
                // 查询汇总需要发送税号发票的税号
                List<String> taxList = confirmDao.getAllNeedSendTaxNo();
                for (String taxno : taxList) {
                    //判断是否为大企业税号
                    DynamicContextHolder.push(DbConstant.BASICS_READ);
                    BasisSysDeptCfg baseSysDeptCfg = basisSysDeptCfgDao.selectOne(new QueryWrapper<BasisSysDeptCfg>().eq("nsrsbh", taxno));
                    if (baseSysDeptCfg != null) {
                        continue;
                    }
                    TAcOrg org = selectIdAndKey(taxno);
                    DynamicContextHolder.push(db + DbConstant.BUSINESS_READ);
                    // 通过税号查询发票数据
                    // 查询需要发送认证的发票
                    int count = confirmDao.getApplyInvoiceByCount(taxno);
                    if (count > 0) {
                        int m = count / 200 + 1;
                        for (int k = 0; k < m; k++) {
                            List<TDxRecordInvoice> list = confirmDao.getApplyInvoice(taxno);
                            String batchNo;
                            // 申请认证请求报文发票list
                            List<ApplyInvoice> invoiceList = new ArrayList<>();
                            // 申请认证记录发票list
                            List<TDxApplyRecord> recordList = new ArrayList<>();
                            for (int i = 0; i < list.size(); i++) {
                                TDxApplyRecord applyRecord = new TDxApplyRecord();
                                ApplyInvoice applyInvoice = new ApplyInvoice();
                                // 申请记录表
                                applyRecord.setInvoiceCode(list.get(i).getInvoiceCode());
                                applyRecord.setInvoiceNo(list.get(i).getInvoiceNo());
                                applyRecord.setUuid((StringUtils.isBlank(list.get(i).getInvoiceCode())?"":list.get(i).getInvoiceCode()) + list.get(i).getInvoiceNo());
                                applyRecord.setRzlx(list.get(i).getRzlx());
                                applyInvoice.setInvoiceCode(list.get(i).getInvoiceCode());
                                applyInvoice.setInvoiceNo(list.get(i).getInvoiceNo());
                                applyInvoice.setApplyTaxPeriod(list.get(i).getRzhBelongDate());
                                applyInvoice.setBuyerTaxNo(list.get(i).getGfTaxNo());
                                applyInvoice.setApplyRzlx(list.get(i).getRzlx());
                                applyInvoice.setInvoiceType(list.get(i).getInvoiceType());
//                                if (list.get(i).getDkTaxAmount() == null) {
//                                    applyInvoice.setYxse(list.get(i).getTaxAmount().toString());
//                                } else {
//                                    applyInvoice.setYxse(list.get(i).getDkTaxAmount().toString());
//                                }
                                if("31".equals(list.get(i).getInvoiceType()) ||"32".equals(list.get(i).getInvoiceType())
                                        || "185".equals(list.get(i).getInvoiceType())){
                                    if(StringUtils.isNotEmpty(list.get(i).getInvoiceNo()) && list.get(i).getInvoiceNo().length() == 20){

                                        String invoiceCode = list.get(i).getInvoiceNo().substring(0,12);
                                        String invoiceNum = list.get(i).getInvoiceNo().substring(12);
                                        log.info("全电发票申请认证 invoiceCode={},invoiceNum={}",invoiceCode,invoiceNum);
                                        applyInvoice.setInvoiceCode(invoiceCode);
                                        applyInvoice.setInvoiceNo(invoiceNum);
                                    }
                                }

                                log.info("list.get(i).getDkTaxAmount() = {}",list.get(i).getDkTaxAmount());
                                log.info("list.get(i).getTaxAmount() = {}",list.get(i).getTaxAmount());
                                if("31".equals(list.get(i).getInvoiceType()) && list.get(i).getDkTaxAmount() != null){
                                    applyInvoice.setYxse(list.get(i).getDkTaxAmount().toString());
                                }else if(list.get(i).getTaxAmount() != null){
                                    applyInvoice.setYxse(list.get(i).getTaxAmount().toString());
                                }
                                if("4".equals(list.get(i).getRzlx()) || "6".equals(list.get(i).getRzlx())) {
                                    applyInvoice.setBdkMessage(list.get(i).getBdkMessage());
                                }
                                invoiceList.add(applyInvoice);
                                recordList.add(applyRecord);
                                if (i == list.size() - 1) {
                                    String aaa = UUID.randomUUID().toString();
                                    batchNo = aaa.replaceAll("-", "");
                                    applyInfo.setInvoices(invoiceList);
                                    applyInfo.setBuyerTaxNo(list.get(i).getGfTaxNo());
                                    applyInfo.setContentRows(invoiceList.size());
                                    applyInfo.setBatchNo(batchNo);
                                    String dataStr = JSONObject.toJSONString(applyInfo);
                                    String base64Data = Base64.encode(dataStr);
                                    log.info("org.getAceId()={},appid={},enterpriseCode={},applyLtgalize={},version={},base64Data={},dataExchangeId={},org.getAceKey={}",
                                            org.getAceId(),appid,enterpriseCode,applyLtgalize,version,base64Data,dataExchangeId,org.getAceKey());
                                    // 加密串生成
                                    String appSec = makeAppSecService.makeAppSec(org.getAceId(), appid, enterpriseCode,
                                        applyLtgalize, version, base64Data, dataExchangeId, org.getAceKey());
                                    // 请求报文拼接
                                    String requstData =
                                        requestData(appSec, dataExchangeId, base64Data, applyLtgalize, org.getAceId());
                                    log.info("申请认证取请求报文为=======" + requstData);
                                    // 发送请求返回请求报文
                                    tDxHttpLog.setReqText(requstData);
                                    tDxHttpLog.setReqDate(new Date());
                                    String responseJson = HttpUtil.post(url, requstData, 60000);
                                    tDxHttpLog.setResText(responseJson);
                                    tDxHttpLog.setResDate(new Date());
                                    log.info("响应请求数据为=" + responseJson);
                                    DynamicContextHolder.push(db + DbConstant.BUSINESS_WRITE);
                                    try {
                                        if (responseJson != null) {
                                            ResponesJson gatherData =
                                                JSONObject.parseObject(responseJson, ResponesJson.class);
                                            ReturnStateInfo returnStateInfo = gatherData.getReturnStateInfo();
                                            if ("0000".equals(returnStateInfo.getReturnCode())) {
                                                for (TDxApplyRecord apply1 : recordList) {
                                                    apply1.setBatchNo(batchNo);
                                                    apply1.setCreateDate(new Date());
                                                    apply1.setResultStatus("N");
                                                    apply1.setAceId(org.getAceId());
                                                    apply1.setAceKey(org.getAceKey());
                                                    tDxApplyRecordDao.insert(apply1);
                                                    if ("1".equals(apply1.getRzlx()) || "4".equals(apply1.getRzlx())
                                                        || "2".equals(apply1.getRzlx())) {
                                                        confirmDao.updateInvoiceRecord(apply1);
                                                    } else if ("5".equals(apply1.getRzlx())) {
                                                        confirmDao.updateInvoiceRecordForRebackRz(apply1);
                                                    } else if ("6".equals(apply1.getRzlx())) {
                                                        confirmDao.updateInvoiceRecordForRebackNoDeduction(apply1);
                                                    }
                                                }
                                            }
                                        }
                                    } catch (Exception e) {
                                        tDxHttpLog.setStatus("2");
                                        baseMapper.insert(tDxHttpLog);
                                        e.printStackTrace();
                                    }
                                }
                            }
                        }
                    } else {
                        log.info("数据库没有需要申请认证的发票");
                    }
                }
            }
        } catch (Exception e) {
            log.error("申请认证执行失败,失败原因是:{}",e);
            e.printStackTrace();
        }
    }

    private TAcOrg selectIdAndKey(String taxno) {
        DynamicContextHolder.push(DbConstant.BASICS_READ);
        // 通过税号查询id和Key
        return confirmDao.findIdAndKeyByTaxno(taxno);
    }

    @Override
    public void applyOverdue() {

        log.info("进入逾期申请执行方法");
        ApplyInfo applyInfo = new ApplyInfo();
        TDxHttpLog tDxHttpLog = new TDxHttpLog();
        tDxHttpLog.setType("07");
        try {
            // 查询数据库 遍历数据源
            DynamicContextHolder.push(DbConstant.BASICS_READ);
            List<String> dbList = confirmDao.getDbSource();
            for (String db : dbList) {
                String dataExchangeId = makeExchangeId();
                DynamicContextHolder.push(db + DbConstant.BUSINESS_READ);
                // 查询汇总需要发送税号发票的税号
                List<String> taxList = confirmDao.getNeedSendTaxNo("5");
                for (String taxno : taxList) {
                    // 通过税号查询id和Key
                    TAcOrg org = selectIdAndKey(taxno);
                    DynamicContextHolder.push(db + DbConstant.BUSINESS_READ);
                    // 查询需要发送逾期的发票
                    int count = confirmDao.getApplyOverdueCount(taxno);
                    if (count > 0) {
                        int m = count / 200 + 1;
                        for (int k = 0; k < m; k++) {
                            List<TDxRecordInvoice> list = confirmDao.getApplyOverdue(taxno);
                            String batchNo;
                            // 申请认证请求报文发票list
                            List<ApplyInvoice> invoiceList = new ArrayList<>();
                            // 申请认证记录发票list
                            List<TDxApplyRecord> recordList = new ArrayList<>();
                            for (int i = 0; i < list.size(); i++) {
                                TDxApplyRecord applyRecord = new TDxApplyRecord();
                                ApplyInvoice applyInvoice = new ApplyInvoice();
                                // 申请记录表
                                applyRecord.setInvoiceCode(list.get(i).getInvoiceCode());
                                applyRecord.setInvoiceNo(list.get(i).getInvoiceNo());
                                applyRecord.setUuid(list.get(i).getInvoiceCode() + list.get(i).getInvoiceNo());
                                // 申请数据准备
                                applyInvoice.setInvoiceCode(list.get(i).getInvoiceCode());
                                applyInvoice.setInvoiceNo(list.get(i).getInvoiceNo());
                                applyInvoice.setApplyTaxPeriod(list.get(i).getRzhBelongDate());
                                applyInvoice.setBuyerTaxNo(list.get(i).getGfTaxNo());
                                applyInvoice.setApplyRzlx(list.get(i).getRzlx());
                                applyInvoice.setInvoiceType(list.get(i).getInvoiceType());
                                if (list.get(i).getDkTaxAmount() == null) {
                                    applyInvoice.setYxse(list.get(i).getTaxAmount().toString());
                                } else {
                                    applyInvoice.setYxse(list.get(i).getDkTaxAmount().toString());
                                }
                                invoiceList.add(applyInvoice);
                                recordList.add(applyRecord);
                                if (i == list.size() - 1) {
                                    String aaa = UUID.randomUUID().toString();
                                    batchNo = aaa.replaceAll("-", "");
                                    applyInfo.setInvoices(invoiceList);
                                    applyInfo.setBuyerTaxNo(list.get(i).getGfTaxNo());
                                    applyInfo.setContentRows(invoiceList.size());
                                    applyInfo.setBatchNo(batchNo);
                                    String dataStr = JSONObject.toJSONString(applyInfo);
                                    String base64Data = Base64.encode(dataStr);
                                    // 加密串生成
                                    String appSec = makeAppSecService.makeAppSec(org.getAceId(), appid, enterpriseCode,
                                        applyLtgalize, version, base64Data, dataExchangeId, org.getAceKey());
                                    // 请求报文拼接
                                    String requstData =
                                        requestData(appSec, dataExchangeId, base64Data, applyLtgalize, org.getAceId());
                                    log.info("申请逾期取请求报文为=======" + requstData);
                                    // 发送请求返回请求报文
                                    tDxHttpLog.setReqText(requstData);
                                    tDxHttpLog.setReqDate(new Date());
                                    String responseJson = HttpUtil.post(url, requstData, 60000);
                                    tDxHttpLog.setResText(responseJson);
                                    tDxHttpLog.setResDate(new Date());
                                    log.info("申请逾期响应请求数据为=" + responseJson);
                                    DynamicContextHolder.push(db + DbConstant.BUSINESS_WRITE);
                                    try {
                                        if (responseJson != null) {
                                            ResponesJson gatherData =
                                                JSONObject.parseObject(responseJson, ResponesJson.class);
                                            ReturnStateInfo returnStateInfo = gatherData.getReturnStateInfo();
                                            if ("0000".equals(returnStateInfo.getReturnCode())) {
                                                for (TDxApplyRecord apply : recordList) {
                                                    apply.setBatchNo(batchNo);
                                                    apply.setCreateDate(new Date());
                                                    apply.setResultStatus("N");
                                                    apply.setAceId(org.getAceId());
                                                    apply.setAceKey(org.getAceKey());
                                                    tDxApplyRecordDao.insert(apply);
                                                    confirmDao.updateInvoiceRecordForOverdue(apply);
                                                }
                                            }
                                        }
                                    } catch (Exception e) {
                                        tDxHttpLog.setStatus("2");
                                        baseMapper.insert(tDxHttpLog);
                                        e.printStackTrace();
                                    }
                                }
                            }
                        }
                    } else {
                        log.info("数据库没有需要申请逾期认证的发票");
                    }
                }
            }
        } catch (Exception e) {
            log.info("申请逾期认证执行失败");
            e.printStackTrace();
        }
    }

    @Override
    public void applyNoDeduction() {

        log.info("进入申请不抵扣执行方法");
        ApplyInfo applyInfo = new ApplyInfo();
        TDxHttpLog tDxHttpLog = new TDxHttpLog();
        tDxHttpLog.setType("08");
        try {
            // 查询数据库 遍历数据源
            DynamicContextHolder.push(DbConstant.BASICS_READ);
            List<String> dbList = confirmDao.getDbSource();
            for (String db : dbList) {
                String dataExchangeId = makeExchangeId();
                DynamicContextHolder.push(db + DbConstant.BUSINESS_READ);
                // 查询汇总需要发送税号发票的税号
                List<String> taxList = confirmDao.getNeedSendTaxNo("4");
                for (String taxno : taxList) {
                    // 通过税号查询id和Key
                    TAcOrg org = selectIdAndKey(taxno);
                    DynamicContextHolder.push(db + DbConstant.BUSINESS_READ);
                    // 查询需要发送逾期的发票
                    int count = confirmDao.getApplyNoDeductionCount(taxno);
                    if (count > 0) {
                        int m = count / 200 + 1;
                        for (int k = 0; k < m; k++) {
                            List<TDxRecordInvoice> list = confirmDao.getApplyNoDeduction(taxno);
                            String batchNo;
                            // 申请认证请求报文发票list
                            List<ApplyInvoice> invoiceList = new ArrayList<>();
                            // 申请认证记录发票list
                            List<TDxApplyRecord> recordList = new ArrayList<>();
                            for (int i = 0; i < list.size(); i++) {
                                TDxApplyRecord applyRecord = new TDxApplyRecord();
                                ApplyInvoice applyInvoice = new ApplyInvoice();
                                // 申请记录表
                                applyRecord.setInvoiceCode(list.get(i).getInvoiceCode());
                                applyRecord.setInvoiceNo(list.get(i).getInvoiceNo());
                                applyRecord.setUuid(list.get(i).getInvoiceCode() + list.get(i).getInvoiceNo());
                                // 申请数据准备
                                applyInvoice.setInvoiceCode(list.get(i).getInvoiceCode());
                                applyInvoice.setInvoiceNo(list.get(i).getInvoiceNo());
                                applyInvoice.setApplyTaxPeriod(list.get(i).getRzhBelongDate());
                                applyInvoice.setBuyerTaxNo(list.get(i).getGfTaxNo());
                                applyInvoice.setApplyRzlx(list.get(i).getRzlx());
                                applyInvoice.setInvoiceType(list.get(i).getInvoiceType());
                                if (list.get(i).getDkTaxAmount() == null) {
                                    applyInvoice.setYxse(list.get(i).getTaxAmount().toString());
                                } else {
                                    applyInvoice.setYxse(list.get(i).getDkTaxAmount().toString());
                                }
                                invoiceList.add(applyInvoice);
                                recordList.add(applyRecord);
                                if (i == list.size() - 1) {
                                    String aaa = UUID.randomUUID().toString();
                                    batchNo = aaa.replaceAll("-", "");
                                    applyInfo.setInvoices(invoiceList);
                                    applyInfo.setBuyerTaxNo(list.get(i).getGfTaxNo());
                                    applyInfo.setContentRows(invoiceList.size());
                                    applyInfo.setBatchNo(batchNo);
                                    String dataStr = JSONObject.toJSONString(applyInfo);
                                    String base64Data = Base64.encode(dataStr);
                                    // 加密串生成
                                    String appSec = makeAppSecService.makeAppSec(org.getAceId(), appid, enterpriseCode,
                                        applyLtgalize, version, base64Data, dataExchangeId, org.getAceKey());
                                    // 请求报文拼接
                                    String requstData =
                                        requestData(appSec, dataExchangeId, base64Data, applyLtgalize, org.getAceId());
                                    log.info("申请不抵扣请求报文为=======" + requstData);
                                    // 发送请求返回请求报文
                                    tDxHttpLog.setReqText(requstData);
                                    tDxHttpLog.setReqDate(new Date());
                                    String responseJson = HttpUtil.post(url, requstData, 60000);
                                    tDxHttpLog.setResText(responseJson);
                                    tDxHttpLog.setResDate(new Date());
                                    log.info("申请不抵扣响应请求数据为=" + responseJson);
                                    DynamicContextHolder.push(db + DbConstant.BUSINESS_WRITE);
                                    try {
                                        if (responseJson != null) {
                                            ResponesJson gatherData =
                                                JSONObject.parseObject(responseJson, ResponesJson.class);
                                            ReturnStateInfo returnStateInfo = gatherData.getReturnStateInfo();
                                            if ("0000".equals(returnStateInfo.getReturnCode())) {
                                                for (TDxApplyRecord apply : recordList) {
                                                    apply.setBatchNo(batchNo);
                                                    apply.setCreateDate(new Date());
                                                    apply.setResultStatus("N");
                                                    apply.setAceId(org.getAceId());
                                                    apply.setAceKey(org.getAceKey());
                                                    tDxApplyRecordDao.insert(apply);
                                                    confirmDao.updateInvoiceRecord(apply);
                                                }
                                            }
                                        }
                                    } catch (Exception e) {
                                        tDxHttpLog.setStatus("2");
                                        baseMapper.insert(tDxHttpLog);
                                        e.printStackTrace();
                                    }
                                }
                            }
                        }
                    } else {
                        log.info("数据库没有需要申请不抵扣认证的发票");
                    }
                }
            }
        } catch (Exception e) {
            log.info("申请不抵扣执行失败");
            e.printStackTrace();
        }
    }

    @Override
    public void applyRebackRz() {

        log.info("进入申请撤销抵扣执行方法");
        ApplyInfo applyInfo = new ApplyInfo();
        TDxHttpLog tDxHttpLog = new TDxHttpLog();
        tDxHttpLog.setType("08");
        try {
            // 查询数据库 遍历数据源
            DynamicContextHolder.push(DbConstant.BASICS_READ);
            List<String> dbList = confirmDao.getDbSource();
            for (String db : dbList) {
                String dataExchangeId = makeExchangeId();
                DynamicContextHolder.push(db + DbConstant.BUSINESS_READ);
                // 查询汇总需要发送税号发票的税号
                List<String> taxList = confirmDao.getNeedSendTaxNo("6");
                for (String taxno : taxList) {
                    // 通过税号查询id和Key
                    TAcOrg org = selectIdAndKey(taxno);
                    DynamicContextHolder.push(db + DbConstant.BUSINESS_READ);
                    // 查询需要发送逾期的发票
                    int count = confirmDao.getApplyRebackRzCount(taxno);
                    if (count > 0) {
                        int m = count / 200 + 1;
                        for (int k = 0; k < m; k++) {
                            List<TDxRecordInvoice> list = confirmDao.getApplyRebackRz(taxno);
                            String batchNo;
                            // 申请认证请求报文发票list
                            List<ApplyInvoice> invoiceList = new ArrayList<>();
                            // 申请认证记录发票list
                            List<TDxApplyRecord> recordList = new ArrayList<>();
                            for (int i = 0; i < list.size(); i++) {
                                TDxApplyRecord applyRecord = new TDxApplyRecord();
                                ApplyInvoice applyInvoice = new ApplyInvoice();
                                // 申请记录表
                                applyRecord.setInvoiceCode(list.get(i).getInvoiceCode());
                                applyRecord.setInvoiceNo(list.get(i).getInvoiceNo());
                                applyRecord.setUuid(list.get(i).getInvoiceCode() + list.get(i).getInvoiceNo());
                                // 申请数据准备
                                applyInvoice.setInvoiceCode(list.get(i).getInvoiceCode());
                                applyInvoice.setInvoiceNo(list.get(i).getInvoiceNo());
                                applyInvoice.setApplyTaxPeriod(list.get(i).getRzhBelongDate());
                                applyInvoice.setBuyerTaxNo(list.get(i).getGfTaxNo());
                                applyInvoice.setApplyRzlx(list.get(i).getRzlx());
                                applyInvoice.setInvoiceType(list.get(i).getInvoiceType());
                                if (list.get(i).getDkTaxAmount() == null) {
                                    applyInvoice.setYxse(list.get(i).getTaxAmount().toString());
                                } else {
                                    applyInvoice.setYxse(list.get(i).getDkTaxAmount().toString());
                                }
                                invoiceList.add(applyInvoice);
                                recordList.add(applyRecord);
                                if (i == list.size() - 1) {
                                    String aaa = UUID.randomUUID().toString();
                                    batchNo = aaa.replaceAll("-", "");
                                    applyInfo.setInvoices(invoiceList);
                                    applyInfo.setBuyerTaxNo(list.get(i).getGfTaxNo());
                                    applyInfo.setContentRows(invoiceList.size());
                                    applyInfo.setBatchNo(batchNo);
                                    String dataStr = JSONObject.toJSONString(applyInfo);
                                    String base64Data = Base64.encode(dataStr);
                                    // 加密串生成
                                    String appSec = makeAppSecService.makeAppSec(org.getAceId(), appid, enterpriseCode,
                                        applyLtgalize, version, base64Data, dataExchangeId, org.getAceKey());
                                    // 请求报文拼接
                                    String requstData =
                                        requestData(appSec, dataExchangeId, base64Data, applyLtgalize, org.getAceId());
                                    log.info("申请撤销抵扣请求报文为=======" + requstData);
                                    // 发送请求返回请求报文
                                    tDxHttpLog.setReqText(requstData);
                                    tDxHttpLog.setReqDate(new Date());
                                    String responseJson = HttpUtil.post(url, requstData, 60000);
                                    tDxHttpLog.setResText(responseJson);
                                    tDxHttpLog.setResDate(new Date());
                                    log.info("申请撤销抵扣响应请求数据为=" + responseJson);
                                    DynamicContextHolder.push(db + DbConstant.BUSINESS_WRITE);
                                    try {
                                        if (responseJson != null) {
                                            ResponesJson gatherData =
                                                JSONObject.parseObject(responseJson, ResponesJson.class);
                                            ReturnStateInfo returnStateInfo = gatherData.getReturnStateInfo();
                                            if ("0000".equals(returnStateInfo.getReturnCode())) {
                                                for (TDxApplyRecord apply : recordList) {
                                                    apply.setBatchNo(batchNo);
                                                    apply.setCreateDate(new Date());
                                                    apply.setResultStatus("N");
                                                    apply.setAceId(org.getAceId());
                                                    apply.setAceKey(org.getAceKey());
                                                    tDxApplyRecordDao.insert(apply);
                                                    confirmDao.updateInvoiceRecordForRebackRz(apply);
                                                }
                                            }
                                        }
                                    } catch (Exception e) {
                                        tDxHttpLog.setStatus("2");
                                        baseMapper.insert(tDxHttpLog);
                                        e.printStackTrace();
                                    }
                                }
                            }
                        }
                    } else {
                        log.info("数据库没有需要申请撤销抵扣的发票");
                    }
                }
            }
        } catch (Exception e) {
            log.info("撤销抵扣执行失败");
            e.printStackTrace();
        }
    }

    @Override
    public void applyRebackNoDeduction() {

        log.info("进入申请撤销抵扣执行方法");
        ApplyInfo applyInfo = new ApplyInfo();
        TDxHttpLog tDxHttpLog = new TDxHttpLog();
        tDxHttpLog.setType("08");
        try {
            // 查询数据库 遍历数据源
            DynamicContextHolder.push(DbConstant.BASICS_READ);
            List<String> dbList = confirmDao.getDbSource();
            for (String db : dbList) {
                String dataExchangeId = makeExchangeId();
                DynamicContextHolder.push(db + DbConstant.BUSINESS_READ);
                // 查询汇总需要发送税号发票的税号
                List<String> taxList = confirmDao.getNeedSendTaxNo("7");
                for (String taxno : taxList) {
                    // 通过税号查询id和Key
                    TAcOrg org = selectIdAndKey(taxno);
                    DynamicContextHolder.push(db + DbConstant.BUSINESS_READ);
                    // 查询需要发送逾期的发票
                    int count = confirmDao.getApplyRebackNoDeductionCount(taxno);
                    if (count > 0) {
                        int m = count / 200 + 1;
                        for (int k = 0; k < m; k++) {
                            List<TDxRecordInvoice> list = confirmDao.getApplyRebackNoDeduction(taxno);
                            String batchNo;
                            // 申请认证请求报文发票list
                            List<ApplyInvoice> invoiceList = new ArrayList<>();
                            // 申请认证记录发票list
                            List<TDxApplyRecord> recordList = new ArrayList<>();
                            for (int i = 0; i < list.size(); i++) {
                                TDxApplyRecord applyRecord = new TDxApplyRecord();
                                ApplyInvoice applyInvoice = new ApplyInvoice();
                                // 申请记录表
                                applyRecord.setInvoiceCode(list.get(i).getInvoiceCode());
                                applyRecord.setInvoiceNo(list.get(i).getInvoiceNo());
                                applyRecord.setUuid(list.get(i).getInvoiceCode() + list.get(i).getInvoiceNo());
                                // 申请数据准备
                                applyInvoice.setInvoiceCode(list.get(i).getInvoiceCode());
                                applyInvoice.setInvoiceNo(list.get(i).getInvoiceNo());
                                applyInvoice.setApplyTaxPeriod(list.get(i).getRzhBelongDate());
                                applyInvoice.setBuyerTaxNo(list.get(i).getGfTaxNo());
                                applyInvoice.setApplyRzlx(list.get(i).getRzlx());
                                applyInvoice.setInvoiceType(list.get(i).getInvoiceType());
                                if (list.get(i).getDkTaxAmount() == null) {
                                    applyInvoice.setYxse(list.get(i).getTaxAmount().toString());
                                } else {
                                    applyInvoice.setYxse(list.get(i).getDkTaxAmount().toString());
                                }
                                invoiceList.add(applyInvoice);
                                recordList.add(applyRecord);
                                if (i == list.size() - 1) {
                                    String aaa = UUID.randomUUID().toString();
                                    batchNo = aaa.replaceAll("-", "");
                                    applyInfo.setInvoices(invoiceList);
                                    applyInfo.setBuyerTaxNo(list.get(i).getGfTaxNo());
                                    applyInfo.setContentRows(invoiceList.size());
                                    applyInfo.setBatchNo(batchNo);
                                    String dataStr = JSONObject.toJSONString(applyInfo);
                                    String base64Data = Base64.encode(dataStr);
                                    // 加密串生成
                                    String appSec = makeAppSecService.makeAppSec(org.getAceId(), appid, enterpriseCode,
                                        applyLtgalize, version, base64Data, dataExchangeId, org.getAceKey());
                                    // 请求报文拼接
                                    String requstData =
                                        requestData(appSec, dataExchangeId, base64Data, applyLtgalize, org.getAceId());
                                    log.info("申请撤销抵扣请求报文为=======" + requstData);
                                    // 发送请求返回请求报文
                                    tDxHttpLog.setReqText(requstData);
                                    tDxHttpLog.setReqDate(new Date());
                                    String responseJson = HttpUtil.post(url, requstData, 60000);
                                    tDxHttpLog.setResText(responseJson);
                                    tDxHttpLog.setResDate(new Date());
                                    log.info("申请撤销抵扣响应请求数据为=" + responseJson);
                                    DynamicContextHolder.push(db + DbConstant.BUSINESS_WRITE);
                                    try {
                                        if (responseJson != null) {
                                            ResponesJson gatherData =
                                                JSONObject.parseObject(responseJson, ResponesJson.class);
                                            ReturnStateInfo returnStateInfo = gatherData.getReturnStateInfo();
                                            if ("0000".equals(returnStateInfo.getReturnCode())) {
                                                for (TDxApplyRecord apply : recordList) {
                                                    apply.setBatchNo(batchNo);
                                                    apply.setCreateDate(new Date());
                                                    apply.setResultStatus("N");
                                                    apply.setAceId(org.getAceId());
                                                    apply.setAceKey(org.getAceKey());
                                                    tDxApplyRecordDao.insert(apply);
                                                    confirmDao.updateInvoiceRecordForRebackNoDeduction(apply);
                                                }
                                            }
                                        }
                                    } catch (Exception e) {
                                        tDxHttpLog.setStatus("2");
                                        baseMapper.insert(tDxHttpLog);
                                        e.printStackTrace();
                                    }
                                }
                            }
                        }
                    } else {
                        log.info("数据库没有需要申请撤销抵扣的发票");
                    }
                }
            }
        } catch (Exception e) {
            log.info("撤销抵扣执行失败");
            e.printStackTrace();
        }
    }
}
