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

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

import javax.annotation.Resource;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.dxhy.common.enums.FplxEnum;
import com.dxhy.core.dao.BasisSysDeptCfgDao;
import com.dxhy.core.entity.BasisSysDeptCfg;
import org.apache.commons.lang3.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.dxhy.common.constant.DbConstant;
import com.dxhy.common.datasource.config.DynamicContextHolder;
import com.dxhy.common.service.CustomsLogService;
import com.dxhy.common.service.InvoiceLogService;
import com.dxhy.common.vo.CustomsLog;
import com.dxhy.common.vo.InvoiceLog;
import com.dxhy.core.dao.ConfirmDao;
import com.dxhy.core.dao.TDxCustomsApplyRecordDao;
import com.dxhy.core.job.dao.TDxExportCustomsJobDao;
import com.dxhy.core.job.dao.TDxExportInvoiceJobDao;
import com.dxhy.core.job.entity.*;
import com.dxhy.core.job.pojo.*;
import com.dxhy.core.job.service.ExportInterfaceService;

import cn.hutool.core.codec.Base64;
import cn.hutool.http.HttpUtil;
import lombok.extern.slf4j.Slf4j;

/**
 * 功能描述
 *
 * @author 陈刚扬
 * @date 2020/10/28
 * @return
 */
@SuppressWarnings({"AlibabaUndefineMagicConstant", "AlibabaMethodTooLong", "DuplicatedCode"})
@Service("exportInterfaceService")
@Slf4j

public class ExportInterfaceServiceImpl implements ExportInterfaceService {

    @Resource
    private ConfirmDao confirmDao;

    @Resource
    private TDxExportCustomsJobDao tDxExportCustomsJobDao;

    @Resource
    private TDxExportInvoiceJobDao tDxExportInvoiceDao;

    @Resource
    private TDxCustomsApplyRecordDao applyRecordDao;

    @Resource
    private MakeAppSecService makeAppSecService;

    @Resource
    private CustomsLogService customsLogService;

    @Resource
    private InvoiceLogService invoiceLogService;

    @Value("${jxjk.collectUrl}")
    private String collectUrl;
    @Value("${jxjk.enterpriseCode}")
    private String enterpriseCode;
    @Value("${jxjk.version}")
    private String version;
    @Value("${jxjk.appId}")
    private String appId;
    @Value("${jxjk.exportInvoiceGet}")
    private String exportInvoiceGet;
    @Value("${jxjk.exportInvoiceLegalize}")
    private String exportInvoiceLegalize;
    @Value("${jxjk.exportInvoiceLegalizeStatus}")
    private String exportInvoiceLegalizeStatus;
    @Value("${jxjk.exportCustomsGet}")
    private String exportCustomsGet;
    @Value("${jxjk.exportCustomsLegalize}")
    private String exportCustomsLegalize;
    @Value("${jxjk.exportCustomsLegalizeStatus}")
    private String exportCustomsLegalizeStatus;
    @Resource
    private BasisSysDeptCfgDao basisSysDeptCfgDao;

    @Override
    public void getExportCustoms(String taxno, String db, String aceId, String aceKey, String company, String taxName) {

        // 具体参数
        CollectData collectData = new CollectData();
        int totalRow = 0;
        int addRow = 0;
        log.info("-封装参数-");
        try {

            // 封装参数
            String exchangeId = getDataExchangeId();
            collectData.setBuyerTaxNo(taxno);
            // 随机生成32位批次号
            String batchNo = getBatchNo();
            collectData.setBatchNo(batchNo);
            collectData.setAcquisitionDateBegin(getBeginTime(taxno, db));
            collectData.setAcquisitionDateEnd(getEndTime());
            collectData.setStartRow(1);
            collectData.setStatus("1");

            while (true) {
                String dataStr = JSONObject.toJSONString(collectData);
                log.info("data：" + dataStr);
                String base64Data = Base64.encode(dataStr);
                String appSec = makeAppSecService.makeAppSec(aceId, appId, enterpriseCode, exportCustomsGet, version,
                    base64Data, exchangeId, aceKey);
                // 请求报文拼接
                String collectDataStr = requestData(appSec, exchangeId, base64Data, exportCustomsGet, aceId);
                log.info("url:" + collectUrl);
                log.info("请求参数：" + collectDataStr);
                log.info("发送请求--");
                // 保存请求记录
                TDxHttpLog httpLog = new TDxHttpLog();
                httpLog.setTaxno(taxno);
                httpLog.setType("17");
                httpLog.setReqText(collectDataStr);
                // 得到返回报文，解析拿出返回的数量，累加用于判断数量
                httpLog.setReqDate(new Date());
                String responseJson = HttpUtil.post(collectUrl, collectDataStr, 120000);
                httpLog.setResDate(new Date());
                log.info(responseJson);
                // 根据发票类型保存不同实体
                BaseResJson gatherData = JSONObject.parseObject(responseJson, BaseResJson.class);
                log.info("返回报文：" + responseJson);
                log.info(gatherData.toString());
                String base64data = gatherData.getData();
                String dataJson = "{}";
                if (base64data != null) {
                    dataJson = Base64.decodeStr(base64data);
                }
                log.info("data体：" + dataJson);
                CustomsGatherData gather = JSONObject.parseObject(dataJson, CustomsGatherData.class);
                httpLog.setResText(responseJson);
                httpLog.setStatus("0");
                httpLog.setCompany(company);
                if ("0000".equals(gatherData.getReturnStateInfo().getReturnCode())) {
                    if (gather.getList() != null && gather.getList().size() != 0) {
                        totalRow = gather.getTotalRows();
                        addRow += gather.getContentRows();
                        customsConsumer(responseJson, httpLog, company, db, taxName);
                    } else {
                        break;
                    }
                    if (addRow < totalRow) {
                        collectData.setStartRow(addRow);
                    } else {
                        break;
                    }
                } else {
                    break;
                }
            }

        } catch (Exception ignored) {
            ignored.printStackTrace();
        }
    }

    @Override
    public void exportCustomsLegalize() {

        log.info("进入出口转内销缴款书认证申请认证执行方法--");
        CustomsApplyInfo applyInfo = new CustomsApplyInfo();
        TDxHttpLog tDxHttpLog = new TDxHttpLog();
        tDxHttpLog.setType("18");
        try {
            // 查询数据库 遍历数据源
            DynamicContextHolder.push(DbConstant.BASICS_READ);
            List<String> dbList = confirmDao.getDbSource();
            for (String db : dbList) {
                String dataExchangeId = getDataExchangeId();
                DynamicContextHolder.push(db + DbConstant.BUSINESS_READ);
                // 查询汇总需要发送认证缴款书的税号
                List<String> taxList = tDxExportCustomsJobDao.getNeedSendTaxNo();
                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 = tDxExportCustomsJobDao.getApplyCustomsCount(taxno);
                    if (count > 0) {
                        int m = count / 200 + 1;
                        for (int k = 0; k < m; k++) {
                            List<TDxExportCustomsJob> list = tDxExportCustomsJobDao.getApplyExport(taxno);
                            String batchNo;
                            // 申请认证请求报文缴款书list
                            List<ApplyExportCustoms> customsList = new ArrayList<>();
                            // 申请认证记录缴款书list
                            List<TDxCustomsApplyRecord> recordList = new ArrayList<>();
                            for (int i = 0; i < list.size(); i++) {
                                TDxCustomsApplyRecord applyRecord = new TDxCustomsApplyRecord();
                                ApplyExportCustoms applyCustoms = new ApplyExportCustoms();
                                // 申请记录表
                                applyRecord.setCustomsCode(list.get(i).getCustomsCode());
                                applyRecord.setExportNo(list.get(i).getExportNo());
                                applyRecord.setRzlx(list.get(i).getRzlx());
                                // 申请数据准备
                                applyCustoms.setCustomsNo(list.get(i).getCustomsCode());
                                applyCustoms.setToDivertCode(list.get(i).getExportNo());
                                applyCustoms.setApplyTaxPeriod(list.get(i).getRzhBelongDate());
                                applyCustoms.setBuyerTaxNo(list.get(i).getGfTaxNo());
                                applyCustoms.setApplyRzlx(list.get(i).getRzlx());
                                if (list.get(i).getYxExportTaxAmount() == null) {
                                    applyCustoms.setYxse(list.get(i).getExportTaxAmount());
                                } else {
                                    applyCustoms.setYxse(list.get(i).getYxExportTaxAmount());
                                }
                                if("4".equals(list.get(i).getRzlx()) || "6".equals(list.get(i).getRzlx())){
                                    applyCustoms.setBdkMessage(list.get(i).getBdkMessage());
                                }
                                customsList.add(applyCustoms);
                                recordList.add(applyRecord);
                                if (i == list.size() - 1) {
                                    batchNo = getBatchNo();
                                    applyInfo.setList(customsList);
                                    applyInfo.setBuyerTaxNo(list.get(i).getGfTaxNo());
                                    applyInfo.setContentRows(customsList.size());
                                    applyInfo.setBatchNo(batchNo);
                                    String dataStr = JSONObject.toJSONString(applyInfo);
                                    String base64Data = Base64.encode(dataStr);
                                    // 加密串生成
                                    String appSec = makeAppSecService.makeAppSec(org.getAceId(), appId, enterpriseCode,
                                        exportCustomsLegalize, version, base64Data, dataExchangeId, org.getAceKey());
                                    // 请求报文拼接
                                    String requstData = requestData(appSec, dataExchangeId, base64Data,
                                        exportCustomsLegalize, org.getAceId());
                                    log.info("申请认证取请求报文为=======" + requstData);
                                    // 发送请求返回请求报文
                                    tDxHttpLog.setReqText(requstData);
                                    tDxHttpLog.setReqDate(new Date());
                                    String responseJson = HttpUtil.post(collectUrl, 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 (TDxCustomsApplyRecord apply1 : recordList) {
                                                    apply1.setBatchNo(batchNo);
                                                    apply1.setCreateDate(new Date());
                                                    apply1.setGfTaxNo(taxno);
                                                    apply1.setResultStatus("N");
                                                    apply1.setAceId(org.getAceId());
                                                    apply1.setAceKey(org.getAceKey());
                                                    apply1.setRecordType("3");
                                                    applyRecordDao.insert(apply1);
                                                    tDxExportCustomsJobDao.updateExportApply(apply1.getExportNo(),
                                                        apply1.getRzlx(), apply1.getCustomsCode(), taxno);
                                                }
                                            }
                                        }
                                    } catch (Exception e) {
                                        tDxHttpLog.setStatus("2");
                                        confirmDao.insert(tDxHttpLog);
                                        e.printStackTrace();
                                    }
                                }
                            }
                        }
                    } else {
                        log.info("--数据库没有需要申请认证的出口转内销缴款书--");
                    }
                }
            }
        } catch (Exception e) {
            log.info("出口转内销缴款书申请认证执行失败--");
            e.printStackTrace();
        }
    }

    @Override
    public void getExportCustomsLtgalizeResult() {

        log.info("进入出口转内销缴款书认证结果获取执行方法--");
        TDxHttpLog tDxHttpLog = new TDxHttpLog();
        tDxHttpLog.setType("19");
        BatchData batchData = new BatchData();

        try {
            // 查询数据库 遍历数据源
            DynamicContextHolder.push(DbConstant.BASICS_READ);
            List<String> dbList = confirmDao.getDbSource();
            for (String db : dbList) {
                String dataExchangeId = getDataExchangeId();
                DynamicContextHolder.push(db + DbConstant.BUSINESS_READ);
                // 查询认证申请记录表中状态为N的批次号
                List<TDxCustomsApplyRecord> list = tDxExportCustomsJobDao.getBatchNo("3");
                if (list != null && list.size() > 0) {
                    for (TDxCustomsApplyRecord tDxCustomsApplyRecord : list) {
                        String batchNo = tDxCustomsApplyRecord.getBatchNo();
                        String taxNo = tDxCustomsApplyRecord.getGfTaxNo();
                        DynamicContextHolder.push(DbConstant.BASICS_READ);
                        //判断是否为大企业税号
                        BasisSysDeptCfg baseSysDeptCfg = basisSysDeptCfgDao.selectOne(new QueryWrapper<BasisSysDeptCfg>().eq("nsrsbh", taxNo));
                        if (baseSysDeptCfg != null) {
                            continue;
                        }
                        // 请求数据加密
                        batchData.setBatchNo(batchNo);
                        String dataStr = JSONObject.toJSONString(batchData);
                        String base64Data = Base64.encode(dataStr);
                        // 加密串生成
                        String appSec = makeAppSecService.makeAppSec(tDxCustomsApplyRecord.getAceId(), appId,
                            enterpriseCode, exportCustomsLegalizeStatus, version, base64Data, dataExchangeId,
                            tDxCustomsApplyRecord.getAceKey());
                        log.info("本地请求生成加密串=======" + appSec);

                        // 请求报文拼接
                        String requstData = requestData(appSec, dataExchangeId, base64Data, exportCustomsLegalizeStatus,
                            tDxCustomsApplyRecord.getAceId());
                        log.info("出口转内销缴款书认证结果获取请求报文为=======" + requstData);
                        // 发送请求返回请求报文
                        tDxHttpLog.setReqText(requstData);
                        tDxHttpLog.setReqDate(new Date());
                        String responseJson = HttpUtil.post(collectUrl, requstData, 60000);
                        tDxHttpLog.setResText(responseJson);
                        tDxHttpLog.setResDate(new Date());
                        log.info("响应请求数据为=" + responseJson);
                        try {
                            if (responseJson != null) {
                                // 将返回报文转换成实体
                                ResponesJson gatherData = JSONObject.parseObject(responseJson, ResponesJson.class);
                                ReturnStateInfo returnStateInfo = gatherData.getReturnStateInfo();
                                if ("0000".equals(returnStateInfo.getReturnCode())) {
                                    String data = gatherData.getData();
                                    JSONObject dataJosn = JSONObject.parseObject(Base64.decodeStr(data));
                                    if ("Y".equals(dataJosn.getString("batchState"))) {
                                        Date rzhDate = null;
                                        List<LegalizeResult> datalist =
                                            JSONArray.parseArray(dataJosn.getString("list"), LegalizeResult.class);
                                        List<CustomsLog> logList = new ArrayList<>();
                                        for (LegalizeResult legalizeResult : datalist) {
                                            SimpleDateFormat tempDate = new SimpleDateFormat("yyyy-MM-dd");
                                            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);

                                            CustomsLog customsLog = new CustomsLog();
                                            customsLog.setCustomsCode(legalizeResult.getCustomsNo());
                                            customsLog.setRzType(legalizeResult.getLegalizeType());
                                            customsLog.setCreateDate(new Date());
                                            // 认证不抵扣
                                            if ("4".equals(legalizeResult.getRzlx())) {
                                                customsLog.setType("9");
                                                if ("4".equals(legalizeResult.getAuthState())) {
                                                    legalizeResult.setLegalizeState("2");
                                                    customsLog.setInputStatus("8");
                                                } else {
                                                    customsLog.setInputStatus("9");
                                                }
                                                tDxExportCustomsJobDao.updateRecordForNoDeduction(legalizeResult,
                                                    rzhDate, taxNo);
                                                tDxExportCustomsJobDao.updateApply(legalizeResult.getToDivertCode(),
                                                    legalizeResult.getCustomsNo(), taxNo);
                                            } else if ("5".equals(legalizeResult.getRzlx())) {
                                                customsLog.setType("8");
                                                if ("4".equals(legalizeResult.getAuthState())) {
                                                    customsLog.setInputStatus("16");
                                                } else {
                                                    customsLog.setInputStatus("17");
                                                }
                                                // 撤销抵扣 清空认证等字段
                                                tDxExportCustomsJobDao.updateRecordForRebackRz(legalizeResult, rzhDate,
                                                    taxNo);
                                                tDxExportCustomsJobDao.updateApply(legalizeResult.getToDivertCode(),
                                                    legalizeResult.getCustomsNo(), taxNo);
                                            } else if ("6".equals(legalizeResult.getRzlx())) {
                                                customsLog.setType("9");
                                                if ("4".equals(legalizeResult.getAuthState())) {
                                                    customsLog.setInputStatus("11");
                                                } else {
                                                    customsLog.setInputStatus("12");
                                                }
                                                // 如果撤销不抵扣申请成功 更新不抵扣相关字段
                                                tDxExportCustomsJobDao.updateRecordForRebackNoDeduction(legalizeResult,
                                                    rzhDate, taxNo);
                                                tDxExportCustomsJobDao.updateApply(legalizeResult.getToDivertCode(),
                                                    legalizeResult.getCustomsNo(), taxNo);
                                                // 认证抵扣
                                            } else if ("1".equals(legalizeResult.getRzlx())) {
                                                customsLog.setType("8");
                                                if ("4".equals(legalizeResult.getAuthState())) {
                                                    customsLog.setInputStatus("3");
                                                } else {
                                                    customsLog.setInputStatus("4");
                                                }
                                                tDxExportCustomsJobDao.updateRecord(legalizeResult, rzhDate, taxNo);
                                                tDxExportCustomsJobDao.updateApply(legalizeResult.getToDivertCode(),
                                                    legalizeResult.getCustomsNo(), taxNo);
                                            }
                                            logList.add(customsLog);

                                        }
                                        if (logList.size() > 0) {
                                            customsLogService.toCustomsLog(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();
        }
    }

    @Override
    public void getExportInvoice(String taxno, String db, String aceId, String aceKey, String company, String taxName) {

        // 具体参数
        CollectData collectData = new CollectData();
        int totalRow = 0;
        int addRow = 0;
        log.info("-封装参数-");
        try {

            // 封装参数
            String exchangeId = getDataExchangeId();
            collectData.setBuyerTaxNo(taxno);
            // 随机生成32位批次号
            String batchNo = getBatchNo();
            collectData.setBatchNo(batchNo);
            collectData.setAcquisitionDateBegin(getInvoiceBeginTime(taxno, db));
            collectData.setAcquisitionDateEnd(getEndTime());
            collectData.setStartRow(1);
            collectData.setStatus("1");

            while (true) {
                String dataStr = JSONObject.toJSONString(collectData);
                log.info("data：" + dataStr);
                String base64Data = Base64.encode(dataStr);
                String appSec = makeAppSecService.makeAppSec(aceId, appId, enterpriseCode, exportInvoiceGet, version,
                    base64Data, exchangeId, aceKey);
                // 请求报文拼接
                String collectDataStr = requestData(appSec, exchangeId, base64Data, exportInvoiceGet, aceId);
                log.info("url:" + collectUrl);
                log.info("请求参数：" + collectDataStr);
                log.info("发送请求--");
                // 保存请求记录
                TDxHttpLog httpLog = new TDxHttpLog();
                httpLog.setTaxno(taxno);
                httpLog.setType("20");
                httpLog.setReqText(collectDataStr);
                // 得到返回报文，解析拿出返回的数量，累加用于判断数量
                httpLog.setReqDate(new Date());
                String responseJson = HttpUtil.post(collectUrl, collectDataStr, 120000);
                httpLog.setResDate(new Date());
                log.info(responseJson);
                // 根据发票类型保存不同实体
                BaseResJson gatherData = JSONObject.parseObject(responseJson, BaseResJson.class);
                log.info("返回报文：" + responseJson);
                log.info(gatherData.toString());
                String base64data = gatherData.getData();
                String dataJson = "{}";
                if (base64data != null) {
                    dataJson = Base64.decodeStr(base64data);
                }
                log.info("data体：" + dataJson);
                GatherData gather = JSONObject.parseObject(dataJson, GatherData.class);
                httpLog.setResText(responseJson);
                httpLog.setStatus("0");
                httpLog.setCompany(company);

                if ("0000".equals(gatherData.getReturnStateInfo().getReturnCode())) {
                    if (gather.getInvoices() != null && gather.getInvoices().size() != 0) {
                        totalRow = gather.getTotalRows();
                        addRow += gather.getContentRows();
                        invoiceConsumer(responseJson, httpLog, company, db, taxName);
                    } else {
                        break;
                    }
                    if (addRow < totalRow) {
                        collectData.setStartRow(addRow);
                    } else {
                        break;
                    }
                } else {
                    break;
                }
            }

        } catch (Exception e) {
            e.printStackTrace();

        }
    }

    @Override
    public void exportInvoiceLegalize() {

        log.info("进入出口转内销发票认证申请认证执行方法--");
        ApplyInfo applyInfo = new ApplyInfo();
        TDxHttpLog tDxHttpLog = new TDxHttpLog();
        tDxHttpLog.setType("21");
        try {
            // 查询数据库 遍历数据源
            DynamicContextHolder.push(DbConstant.BASICS_READ);
            List<String> dbList = confirmDao.getDbSource();
            for (String db : dbList) {
                String dataExchangeId = getDataExchangeId();
                DynamicContextHolder.push(db + DbConstant.BUSINESS_READ);
                // 查询汇总需要发送税号发票的税号
                List<String> taxList = tDxExportInvoiceDao.getNeedSendTaxNo();
                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 = tDxExportInvoiceDao.getApplyInvoiceCount(taxno);
                    if (count > 0) {
                        int m = count / 200 + 1;
                        for (int k = 0; k < m; k++) {
                            List<TDxExportInvoiceJob> list = tDxExportInvoiceDao.getApplyExportInvoice(taxno);
                            String batchNo;
                            // 申请认证请求报文发票list
                            List<ApplyExportInvoice> invoiceList = new ArrayList<>();
                            // 申请认证记录发票list
                            List<TDxCustomsApplyRecord> recordList = new ArrayList<>();
                            for (int i = 0; i < list.size(); i++) {
                                TDxCustomsApplyRecord applyRecord = new TDxCustomsApplyRecord();
                                ApplyExportInvoice applyInvoice = new ApplyExportInvoice();
                                // 申请记录表
                                applyRecord.setExportNo(list.get(i).getExportNo());
                                applyRecord.setInvoiceCode(list.get(i).getInvoiceCode());
                                applyRecord.setInvoiceNo(list.get(i).getInvoiceNo());
                                applyRecord.setGfTaxNo(list.get(i).getGfTaxNo());
                                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.setToDivertCode(list.get(i).getExportNo());
                                if ("31".equals(list.get(i).getInvoiceType())) {
                                    applyInvoice.setYxse(list.get(i).getExportYxse());
                                } else if (list.get(i).getExportYxse() == null) {
                                    applyInvoice.setYxse(list.get(i).getExportTaxAmount());
                                }
                                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);
                                    // 加密串生成
                                    String appSec = makeAppSecService.makeAppSec(org.getAceId(), appId, enterpriseCode,
                                        exportInvoiceLegalize, version, base64Data, dataExchangeId, org.getAceKey());
                                    // 请求报文拼接
                                    String requstData = requestData(appSec, dataExchangeId, base64Data,
                                        exportInvoiceLegalize, org.getAceId());
                                    log.info("出口转内销发票申请认证取请求报文为=======" + requstData);
                                    // 发送请求返回请求报文
                                    tDxHttpLog.setReqText(requstData);
                                    tDxHttpLog.setReqDate(new Date());
                                    String responseJson = HttpUtil.post(collectUrl, 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 (TDxCustomsApplyRecord apply1 : recordList) {
                                                    apply1.setBatchNo(batchNo);
                                                    apply1.setCreateDate(new Date());
                                                    apply1.setResultStatus("N");
                                                    apply1.setAceId(org.getAceId());
                                                    apply1.setAceKey(org.getAceKey());
                                                    apply1.setRecordType("4");
                                                    String uuid = (StringUtils.isBlank(apply1.getInvoiceCode())?"":apply1.getInvoiceCode())
                                                            +apply1.getInvoiceNo();
                                                    applyRecordDao.insert(apply1);
                                                    tDxExportInvoiceDao.updateExportInvoiceApply(apply1.getExportNo(),
                                                        apply1.getRzlx(),
                                                        uuid,
                                                        apply1.getGfTaxNo());
                                                }
                                            }
                                        }
                                    } catch (Exception e) {
                                        tDxHttpLog.setStatus("2");
                                        confirmDao.insert(tDxHttpLog);
                                        e.printStackTrace();
                                    }
                                }
                            }
                        }
                    } else {
                        log.info("--数据库没有需要申请认证的出口转内销发票--");
                    }
                }
            }
        } catch (Exception e) {
            log.info("出口转内销发票申请认证执行失败--");
            e.printStackTrace();
        }
    }

    @Override
    public void getExportInvoieLtgalizeResult() {

        log.info("进入转内销发票认证结果获取执行方法--");
        TDxHttpLog tDxHttpLog = new TDxHttpLog();
        tDxHttpLog.setType("22");
        BatchData batchData = new BatchData();
        try {
            // 查询数据库 遍历数据源
            DynamicContextHolder.push(DbConstant.BASICS_READ);
            List<String> dbList = confirmDao.getDbSource();
            for (String db : dbList) {
                String dataExchangeId = getDataExchangeId();
                DynamicContextHolder.push(db + DbConstant.BUSINESS_READ);
                // 查询转内销发票认证申请记录表中状态为N的批次号
                List<TDxCustomsApplyRecord> list = tDxExportInvoiceDao.getBatchNo("4");
                if (list != null && list.size() > 0) {
                    for (TDxCustomsApplyRecord tDxCustomsApplyRecord : list) {
                        String batchNo = tDxCustomsApplyRecord.getBatchNo();
                        String taxNo = tDxCustomsApplyRecord.getGfTaxNo();
                        DynamicContextHolder.push(DbConstant.BASICS_READ);
                        //判断是否为大企业税号
                        BasisSysDeptCfg baseSysDeptCfg = basisSysDeptCfgDao.selectOne(new QueryWrapper<BasisSysDeptCfg>().eq("nsrsbh", taxNo));
                        if (baseSysDeptCfg != null) {
                            continue;
                        }
                        // 请求数据加密
                        batchData.setBatchNo(batchNo);
                        String dataStr = JSONObject.toJSONString(batchData);
                        String base64Data = Base64.encode(dataStr);
                        // 加密串生成
                        String appSec = makeAppSecService.makeAppSec(tDxCustomsApplyRecord.getAceId(), appId,
                            enterpriseCode, exportInvoiceLegalizeStatus, version, base64Data, dataExchangeId,
                            tDxCustomsApplyRecord.getAceKey());
                        log.info("本地请求生成加密串=======" + appSec);
                        // 请求报文拼接
                        String requstData = requestData(appSec, dataExchangeId, base64Data, exportInvoiceLegalizeStatus,
                            tDxCustomsApplyRecord.getAceId());
                        log.info("转内销发票认证结果获取请求报文为=======" + requstData);
                        // 发送请求返回请求报文
                        tDxHttpLog.setReqText(requstData);
                        tDxHttpLog.setReqDate(new Date());
                        String responseJson = HttpUtil.post(collectUrl, requstData, 60000);
                        tDxHttpLog.setResText(responseJson);
                        tDxHttpLog.setResDate(new Date());
                        log.info("响应请求数据为=" + responseJson);
                        try {
                            if (responseJson != null) {
                                // 将返回报文转换成实体
                                ResponesJson gatherData = JSONObject.parseObject(responseJson, ResponesJson.class);
                                ReturnStateInfo returnStateInfo = gatherData.getReturnStateInfo();
                                if ("0000".equals(returnStateInfo.getReturnCode())) {
                                    String data = gatherData.getData();
                                    JSONObject dataJosn = JSONObject.parseObject(Base64.decodeStr(data));
                                    if ("Y".equals(dataJosn.getString("batchState"))) {
                                        Date rzhDate = null;
                                        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");
                                            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);
                                            String uuid = legalizeResult.getInvoiceCode()+legalizeResult.getInvoiceNo();
                                            TDxExportInvoiceJob invoice = tDxExportInvoiceDao.findInvoice(legalizeResult.getToDivertCode(), uuid, taxNo);

                                            InvoiceLog invoiceLog = new InvoiceLog();
                                            invoiceLog.setInvoiceCode(legalizeResult.getInvoiceCode());
                                            invoiceLog.setInvoiceNo(legalizeResult.getInvoiceNo());
                                            invoiceLog.setRzType(legalizeResult.getLegalizeType());
                                            invoiceLog.setCreateDate(new Date());
                                            if ("4".equals(legalizeResult.getRzlx())) {

                                                invoiceLog.setType("9");
                                                if ("4".equals(legalizeResult.getAuthState())) {
                                                    legalizeResult.setLegalizeState("2");
                                                    invoiceLog.setInputStatus("8");
                                                } else {
                                                    invoiceLog.setInputStatus("9");
                                                }

                                                tDxExportInvoiceDao.updateRecordForNoDeduction(legalizeResult, rzhDate,
                                                    taxNo);
                                                tDxExportInvoiceDao.updateApply(legalizeResult.getToDivertCode(),
                                                    legalizeResult.getInvoiceCode(), legalizeResult.getInvoiceNo(),
                                                    taxNo);
                                            } else if ("5".equals(legalizeResult.getRzlx())) {
                                                invoiceLog.setType("8");
                                                if ("4".equals(legalizeResult.getAuthState())) {
                                                    invoiceLog.setInputStatus("16");
                                                } else {
                                                    invoiceLog.setInputStatus("17");
                                                }

                                                // 撤销抵扣 清空认证等字段
                                                tDxExportInvoiceDao.updateRecordForRebackRz(legalizeResult, rzhDate,
                                                    taxNo);
                                                tDxExportInvoiceDao.updateApply(legalizeResult.getToDivertCode(),
                                                    legalizeResult.getInvoiceCode(), legalizeResult.getInvoiceNo(),
                                                    taxNo);
                                            } else if ("6".equals(legalizeResult.getRzlx())) {

                                                invoiceLog.setType("9");
                                                if ("4".equals(legalizeResult.getAuthState())) {
                                                    invoiceLog.setInputStatus("11");
                                                } else {
                                                    invoiceLog.setInputStatus("12");
                                                }
                                                // 如果撤销不抵扣申请成功 更新不抵扣相关字段
                                                tDxExportInvoiceDao.updateRecordForRebackNoDeduction(legalizeResult,
                                                    rzhDate, taxNo);
                                                tDxExportInvoiceDao.updateApply(legalizeResult.getToDivertCode(),
                                                    legalizeResult.getInvoiceCode(), legalizeResult.getInvoiceNo(),
                                                    taxNo);
                                            } else if ("1".equals(legalizeResult.getRzlx())) {

                                                invoiceLog.setType("8");
                                                if ("4".equals(legalizeResult.getAuthState())) {
                                                    invoiceLog.setInputStatus("3");
                                                } else {
                                                    invoiceLog.setInputStatus("4");
                                                }
                                                tDxExportInvoiceDao.updateRecord(legalizeResult, rzhDate, taxNo);
                                                tDxExportInvoiceDao.updateApply(legalizeResult.getToDivertCode(),
                                                    legalizeResult.getInvoiceCode(), legalizeResult.getInvoiceNo(),
                                                    taxNo);
                                            }
                                            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();
        }
    }

    public String getDataExchangeId() {
        // enterpriseCode+8 位日期
        // (YYYYMMDD)+9 位序列号
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
        StringBuilder sb = new StringBuilder();
        Random rand = new Random();
        for (int i = 0; i < 9; i++) {
            sb.append(rand.nextInt(10));
        }
        String data = sb.toString();
        return enterpriseCode + simpleDateFormat.format(new Date()) + data;
    }

    /**
     * 获取批次号
     */
    public String getBatchNo() {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
        String date = simpleDateFormat.format(new Date());
        StringBuilder sb = new StringBuilder();
        Random rand = new Random();
        for (int i = 0; i < 24; i++) {
            sb.append(rand.nextInt(10));
        }
        String data = sb.toString();
        return date + data;
    }

    private String getBeginTime(String taxno, String db) {
        DynamicContextHolder.push(db + DbConstant.BUSINESS_READ);
        String lastTime = tDxExportCustomsJobDao.selectLastExportCustomsDate(taxno);
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
        if (lastTime == null || "".equals(lastTime)) {
            Calendar c2 = new GregorianCalendar();
            c2.set(Calendar.HOUR_OF_DAY, 0);
            c2.set(Calendar.MINUTE, 0);
            c2.set(Calendar.SECOND, 0);
            c2.set(Calendar.DAY_OF_MONTH, 1);
            lastTime = simpleDateFormat.format(c2.getTime());
        } else {
            // 避免防止漏票，提前一小时
            Calendar cal = Calendar.getInstance();
            try {
                int hour = cal.get(Calendar.HOUR_OF_DAY);
                Date date = simpleDateFormat.parse(lastTime);
                cal.setTime(date);
                if (hour >= 22) {
                    cal.add(Calendar.HOUR_OF_DAY, -30);
                } else {
                    cal.add(Calendar.HOUR_OF_DAY, -1);
                }
                date = cal.getTime();
                lastTime = simpleDateFormat.format(date);
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
        return lastTime;
    }

    private String getInvoiceBeginTime(String taxno, String db) {
        DynamicContextHolder.push(db + DbConstant.BUSINESS_READ);
        String lastTime = tDxExportInvoiceDao.selectLastExportInvoiceDate(taxno);
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
        if (lastTime == null || "".equals(lastTime)) {
            Calendar c2 = new GregorianCalendar();
            c2.set(Calendar.HOUR_OF_DAY, 0);
            c2.set(Calendar.MINUTE, 0);
            c2.set(Calendar.SECOND, 0);
            c2.set(Calendar.DAY_OF_MONTH, 1);
            lastTime = simpleDateFormat.format(c2.getTime());
        } else {
            // 避免防止漏票，提前一小时
            Calendar cal = Calendar.getInstance();
            try {
                int hour = cal.get(Calendar.HOUR_OF_DAY);
                Date date = simpleDateFormat.parse(lastTime);
                cal.setTime(date);
                if (hour >= 22) {
                    cal.add(Calendar.HOUR_OF_DAY, -30);
                } else {
                    cal.add(Calendar.HOUR_OF_DAY, -1);
                }
                date = cal.getTime();
                lastTime = simpleDateFormat.format(date);
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
        return lastTime;
    }

    /**
     * 获取结束时间
     *
     * @return 返回
     */
    private String getEndTime() {
        Calendar c2 = new GregorianCalendar();
        c2.set(Calendar.HOUR_OF_DAY, 23);
        c2.set(Calendar.MINUTE, 59);
        c2.set(Calendar.SECOND, 59);
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
        return simpleDateFormat.format(c2.getTime());
    }

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

    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();
            BaseQueJson bqj = new BaseQueJson();
            authorize.setAppSecId(aceId);
            authorize.setAppSec(appSec);
            bqj.setAuthorize(authorize);
            globalInfo.setAppId(appId);
            globalInfo.setDataExchangeId(dataExchangeId);
            globalInfo.setEnterpriseCode(enterpriseCode);
            globalInfo.setInterfaceCode(interfaceCode);
            globalInfo.setVersion(version);
            bqj.setGlobalInfo(globalInfo);
            bqj.setData(base64Data);
            requstData = JSONObject.toJSONString(bqj);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return requstData;
    }

    public void customsConsumer(String responseJson, TDxHttpLog httpLog, String company, String db, String taxName) {

        String total = "";
        try {

            BaseResJson gatherData = JSONObject.parseObject(responseJson, BaseResJson.class);
            log.info("返回报文：" + responseJson);
            String base64data = gatherData.getData();
            String dataJson = Base64.decodeStr(base64data);
            CustomsGatherData gather = JSONObject.parseObject(dataJson, CustomsGatherData.class);
            String lists = gather.getList().toString();
            List<CustomsInfo> list = JSONObject.parseArray(lists, CustomsInfo.class);
            total = list.size() + "";

            for (CustomsInfo info : list) {

                // 判断库里是否已经存在，存在则只更新状态更新时间，认证状态以及相关字段更新
                DynamicContextHolder.push(db + DbConstant.BUSINESS_READ);
                TDxCustomsRecordJob entity = tDxExportCustomsJobDao.getCustomsByCode(info.getCustomsNo());
                TDxExportCustomsJob export = tDxExportCustomsJobDao.getCustomsByExportNo(info.getToDivertCode(),
                    info.getCustomsNo(), info.getBuyerTaxNo());

                if (export != null) {
                    boolean flag = false;
                    if ("0".equals(export.getRzhYesorno()) && !export.getRzhYesorno().equals(info.getLegalizeState())) {
                        // 认证抵扣
                        if ("1".equals(info.getRzlx())) {
                            export.setRzhYesorno(info.getLegalizeState());
                            export.setRzhBelongDate(info.getLegalizeBelongDate());
                            export.setRzlx(info.getRzlx());
                            if (StringUtils.isNotBlank(info.getLegalizeDate())) {
                                SimpleDateFormat sim = new SimpleDateFormat("yyyyMMdd");
                                export.setRzhDate(sim.parse(info.getLegalizeDate()));
                            }
                            if ("1".equals(info.getLegalizeState())) {
                                export.setAuthStatus("4");
                            } else {
                                export.setAuthStatus("0");
                            }
                            export.setBdkStatus("1");
                            // 认证不抵扣
                        } else if ("4".equals(info.getRzlx())) {
                            export.setRzhYesorno("2");
                            export.setRzhBelongDate(info.getLegalizeBelongDate());
                            export.setRzlx(info.getRzlx());
                            if (StringUtils.isNotBlank(info.getLegalizeDate())) {
                                SimpleDateFormat sim = new SimpleDateFormat("yyyyMMdd");
                                export.setRzhDate(sim.parse(info.getLegalizeDate()));
                            }
                            if ("1".equals(info.getLegalizeState())) {
                                export.setAuthStatus("4");
                            } else {
                                export.setAuthStatus("0");
                            }
                            export.setBdkStatus("2");
                            export.setBdkMessage(info.getBdkMessage());
                        }
                        flag = true;

                    } else if (!"0".equals(export.getRzhYesorno()) && !"1".equals(info.getLegalizeState())) {
                        // 局端撤销了认证
                        export.setRzhYesorno("0");
                        export.setRzhBelongDate(null);
                        export.setRzlx("0");
                        export.setRzhType(null);
                        export.setRzhDate(null);
                        export.setAuthStatus("0");
                        export.setBdkStatus("0");
                        flag = true;
                    }
                    if (flag) {
                        DynamicContextHolder.push(db + DbConstant.BUSINESS_WRITE);
                        tDxExportCustomsJobDao.updateExportCustoms(export);
                        if (entity != null && !"1".equals(entity.getExportMark())) {
                            entity.setExportMark("1");
                            tDxExportCustomsJobDao.updateExportMark(entity);
                        }
                    }

                } else {
                    if (StringUtils.isBlank(info.getLegalizeDate())) {
                        info.setLegalizeDate(null);
                    }
                    TDxExportCustomsJob record = exchangePoToEntity(info);
                    record.setCompany(company);
                    record.setGfName(taxName);
                    DynamicContextHolder.push(db + DbConstant.BUSINESS_WRITE);
                    tDxExportCustomsJobDao.insert(record);
                    if (entity != null && !"1".equals(entity.getExportMark())) {
                        entity.setExportMark("1");
                        tDxExportCustomsJobDao.updateExportMark(entity);
                    }
                }

            }
            httpLog.setStatus("1");
            httpLog.setTotal(total);
            DynamicContextHolder.push(db + DbConstant.BUSINESS_WRITE);
            confirmDao.insert(httpLog);

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

    public void invoiceConsumer(String responseJson, TDxHttpLog httpLog, String company, String db, String taxName) {

        String total = "";
        try {
            // 根据发票类型保存不同实体
            BaseResJson gatherData = JSONObject.parseObject(responseJson, BaseResJson.class);
            log.info("返回报文：" + responseJson);
            String base64data = gatherData.getData();
            String dataJson = Base64.decodeStr(base64data);
            GatherData gather = JSONObject.parseObject(dataJson, GatherData.class);
            String invoices = gather.getInvoices().toString();
            List<InvoiceSelectInfo> invoicesList = JSONObject.parseArray(invoices, InvoiceSelectInfo.class);
            gather.setInvoices(invoicesList);
            total = invoicesList.size() + "";

            for (InvoiceSelectInfo invoiceSelectInfo : invoicesList) {
                invoiceSelectInfo.setUuid((StringUtils.isBlank(invoiceSelectInfo.getInvoiceCode())?"":invoiceSelectInfo.getInvoiceCode())
                        + invoiceSelectInfo.getInvoiceNo());

                if ("1".equals(invoiceSelectInfo.getLegalizeState())) {
                    invoiceSelectInfo.setAuthStatus("4");
                } else {
                    invoiceSelectInfo.setAuthStatus("0");
                }
                // 判断库里是否已经存在，存在则只更新发票状态，状态更新时间，认证状态以及相关字段更新
                DynamicContextHolder.push(db + DbConstant.BUSINESS_READ);
                TDxExportInvoiceJob entity = tDxExportInvoiceDao.findInvoice(invoiceSelectInfo.getToDivertCode(),
                    invoiceSelectInfo.getUuid(), invoiceSelectInfo.getBuyerTaxNo());
                TDxRecordInvoiceJobEntity invoice = tDxExportInvoiceDao.findInvoiceByUUID(invoiceSelectInfo.getUuid());
                if (entity != null) {
                    boolean flag = false;

                    if (!entity.getInvoiceStatus().equals(invoiceSelectInfo.getInvoiceStatus())) {
                        entity.setInvoiceStatus(invoiceSelectInfo.getInvoiceStatus());
                        entity.setStatusUpdateDate(new Date());
                        flag = true;
                    }
                    if ("0".equals(entity.getRzhYesorno())
                        && !entity.getRzhYesorno().equals(invoiceSelectInfo.getLegalizeState())) {
                        // 认证抵扣
                        if ("1".equals(invoiceSelectInfo.getRzlx())) {
                            entity.setRzhYesorno(invoiceSelectInfo.getLegalizeState());
                            entity.setRzhBelongDate(invoiceSelectInfo.getLegalizeBlongDate());
                            entity.setRzlx(invoiceSelectInfo.getRzlx());
                            entity.setRzhType(invoiceSelectInfo.getLegalizeType());
                            if (org.apache.commons.lang.StringUtils.isNotBlank(invoiceSelectInfo.getLegalizeDate())) {
                                SimpleDateFormat sim = new SimpleDateFormat("yyyyMMdd");
                                entity.setRzhDate(sim.parse(invoiceSelectInfo.getLegalizeDate()));
                            }
                            if ("1".equals(invoiceSelectInfo.getLegalizeState())) {
                                entity.setAuthStatus("4");
                            } else {
                                entity.setAuthStatus("0");
                            }
                            entity.setBdkStatus("1");
                        } else if ("4".equals(invoiceSelectInfo.getRzlx())) {
                            entity.setRzhYesorno("2");
                            entity.setRzhBelongDate(invoiceSelectInfo.getLegalizeBlongDate());
                            entity.setRzlx(invoiceSelectInfo.getRzlx());
                            entity.setRzhType(invoiceSelectInfo.getLegalizeType());
                            if (org.apache.commons.lang.StringUtils.isNotBlank(invoiceSelectInfo.getLegalizeDate())) {
                                SimpleDateFormat sim = new SimpleDateFormat("yyyyMMdd");
                                entity.setRzhDate(sim.parse(invoiceSelectInfo.getLegalizeDate()));
                            }
                            if ("1".equals(invoiceSelectInfo.getLegalizeState())) {
                                entity.setAuthStatus("4");
                            } else {
                                entity.setAuthStatus("0");
                            }
                            entity.setBdkMessage(invoiceSelectInfo.getBdkMessage());
                            entity.setBdkStatus("2");
                        }
                        flag = true;

                    } else if (!"0".equals(entity.getRzhYesorno())
                        && !"1".equals(invoiceSelectInfo.getLegalizeState())) {
                        // 局端撤销认证
                        entity.setRzhYesorno("0");
                        entity.setRzhBelongDate(null);
                        entity.setRzlx("0");
                        entity.setRzhType(null);
                        entity.setRzhDate(null);
                        entity.setAuthStatus("0");
                        entity.setBdkStatus("0");
                        flag = true;
                    }
                    if (flag) {
                        DynamicContextHolder.push(db + DbConstant.BUSINESS_WRITE);
                        tDxExportInvoiceDao.updateExportInvoice(entity);

                        if (invoice != null && !"1".equals(invoice.getExportMark())) {
                            invoice.setExportMark("1");
                            tDxExportInvoiceDao.updateExportMark(invoice);
                        }
                    }

                } else {
                    if (StringUtils.isBlank(invoiceSelectInfo.getLegalizeDate())) {
                        invoiceSelectInfo.setLegalizeDate(null);
                    }
                    TDxExportInvoiceJob record = exchangePo2Invoice(invoiceSelectInfo);
                    record.setCompany(company);
                    record.setGfName(taxName);
                    DynamicContextHolder.push(db + DbConstant.BUSINESS_WRITE);
                    tDxExportInvoiceDao.insert(record);
                    if (invoice != null && !"1".equals(invoice.getExportMark())) {
                        invoice.setExportMark("1");
                        tDxExportInvoiceDao.updateExportMark(invoice);
                    }
                }
            }
            httpLog.setStatus("1");
            httpLog.setTotal(total);
            DynamicContextHolder.push(db + DbConstant.BUSINESS_WRITE);
            confirmDao.insert(httpLog);

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

    private TDxExportCustomsJob exchangePoToEntity(CustomsInfo po) {

        TDxExportCustomsJob entity = new TDxExportCustomsJob();
        entity.setExportTaxAmount(po.getAmount());
        entity.setGfTaxNo(po.getBuyerTaxNo());
        entity.setCustomsCode(po.getCustomsNo());
        entity.setExportNo(po.getToDivertCode());
        try {
            if (po.getFillInDate() != null) {

                entity.setFillInDate(new SimpleDateFormat("yyyyMMdd").parse(po.getFillInDate()));
            }
        } catch (ParseException e) {
            entity.setFillInDate(null);
        }
        entity.setGxjzr(po.getLegalizeEndDate());
        entity.setGxfwq(po.getLegalizeInvoiceDateBegin());
        entity.setGxfwz(po.getLegalizeInvoiceDateEnd());
        entity.setRzlx(po.getRzlx());
        entity.setCreateDate(new Date());
        entity.setDetailYesorno("0");
        entity.setDataSources("0");
        entity.setDataType("17");
        entity.setDqskssq(po.getCurrentTaxPeriod());
        if ("1".equals(po.getLegalizeState()) && !"1".equals(po.getRzlx())) {
            entity.setRzhYesorno(po.getLegalizeState());
            entity.setAuthStatus("4");
            entity.setRzhBelongDate(po.getLegalizeBelongDate());
            try {
                if (po.getLegalizeDate() != null) {
                    entity.setRzhDate(new SimpleDateFormat("yyyyMMdd").parse(po.getLegalizeDate()));
                }
            } catch (ParseException e) {
                entity.setRzhDate(null);
            }
            entity.setBdkStatus("1");
        } else {
            entity.setRzhYesorno("0");

        }
        if ("2".equals(po.getLegalizeState()) && "4".equals(po.getRzlx())) {
            entity.setRzhYesorno("2");
            entity.setAuthStatus("4");
            entity.setRzhBelongDate(po.getLegalizeBelongDate());
            entity.setBdkStatus("2");
            if (po.getLegalizeDate() != null) {
                try {
                    entity.setRzhDate(new SimpleDateFormat("yyyyMMdd").parse(po.getLegalizeDate()));
                } catch (ParseException e) {
                    entity.setRzhDate(null);
                }
            }

        }

        entity.setGlzt(po.getGlzt());
        if (po.getYxse() != null && !"".equals(po.getYxse())) {
            entity.setYxExportTaxAmount(po.getYxse());
        } else {
            entity.setYxExportTaxAmount(po.getAmount());
        }
        return entity;
    }

    private TDxExportInvoiceJob exchangePo2Invoice(InvoiceSelectInfo po) {

        TDxExportInvoiceJob entity = new TDxExportInvoiceJob();
        entity.setInvoiceCode(po.getInvoiceCode());
        entity.setInvoiceNo(po.getInvoiceNo());
        if(StringUtils.isNotBlank(po.getElectronicInvoiceNo())){
            entity.setElectronicInvoiceNo(po.getElectronicInvoiceNo());
        }
        entity.setExportNo(po.getToDivertCode());
        entity.setInvoiceType(po.getInvoiceType());
        try {
            if (po.getInvoiceDate() != null) {
                entity.setInvoiceDate(new SimpleDateFormat("yyyyMMdd").parse(po.getInvoiceDate()));
            }
        } catch (ParseException e) {
            entity.setInvoiceDate(null);
        }
        entity.setInvoiceStatus(po.getInvoiceStatus());
        if (!"0".equals(po.getInvoiceStatus())) {
            entity.setStatusUpdateDate(new Date());
        }
        entity.setExportAmount(po.getInvoiceAmount());
        entity.setExportTaxAmount(po.getTaxAmount());
        entity.setGfTaxNo(po.getBuyerTaxNo());
        entity.setGfName(po.getBuyerName());
        entity.setXfTaxNo(po.getSalerTaxNo());
        entity.setXfName(po.getSalerName());
        entity.setRzlx(po.getRzlx());
        entity.setCreateDate(new Date());
        entity.setUuid((StringUtils.isBlank(po.getInvoiceCode())?"":po.getInvoiceCode()) + po.getInvoiceNo());
        entity.setRzhType(po.getLegalizeType());
        if ("1".equals(po.getLegalizeState()) && !"4".equals(po.getRzlx())) {
            entity.setRzhYesorno(po.getLegalizeState());
            entity.setAuthStatus("4");
            entity.setRzhBelongDate(po.getLegalizeBlongDate());
            try {
                if (po.getLegalizeDate() != null) {
                    entity.setRzhDate(new SimpleDateFormat("yyyyMMdd").parse(po.getLegalizeDate()));
                }
            } catch (ParseException e) {
                entity.setRzhDate(null);
            }
            entity.setBdkStatus("1");
        } else {
            entity.setAuthStatus("0");
            entity.setRzhYesorno("0");
        }
        if ("1".equals(po.getLegalizeState()) && "4".equals(po.getRzlx())) {
            entity.setRzhYesorno("2");
            entity.setAuthStatus("4");
            entity.setRzhBelongDate(po.getLegalizeBlongDate());
            entity.setBdkStatus("2");
            if (po.getLegalizeDate() != null) {
                try {
                    entity.setRzhDate(new SimpleDateFormat("yyyyMMdd").parse(po.getLegalizeDate()));
                } catch (ParseException e) {
                    entity.setRzhDate(null);
                }
            }

        }
        entity.setGlzt(po.getGlzt());
        if (po.getDkse() != null && !"".equals(po.getDkse())) {
            entity.setExportYxse(po.getDkse());
        } else {
            entity.setExportYxse(po.getTaxAmount());
        }
        entity.setBdkMessage(po.getBdkMessage());
        entity.setInvoiceSource(po.getInvoiceSources());
        entity.setXxly(po.getXxly());
        return entity;
    }

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

    }

    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 "当期已锁定";
            }
            if ("17".equals(failureReason)) {
                return "逾期不可勾选";
            }
            if ("18".equals(failureReason)) {
                return "发票未勾选（确认）";
            }
            if ("19".equals(failureReason)) {
                return "取消操作不匹配";
            }
            if ("98".equals(failureReason)) {
                return "管理状态异常";
            }
            if ("23".equals(failureReason)) {
                return "不抵扣原因为空或者异常";
            }
        }
        return "";
    }
}
