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

import cn.hutool.core.codec.Base64;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.dxhy.api.model.config.CollectionControlModel;
import com.dxhy.api.model.db.*;
import com.dxhy.api.model.invoice.*;
import com.dxhy.api.model.tdys.TdysZxxMxDto;
import com.dxhy.common.constant.ConfigureConstant;
import com.dxhy.common.constant.CoreConstants;
import com.dxhy.common.constant.DbConstant;
import com.dxhy.common.datasource.config.DynamicContextHolder;
import com.dxhy.common.enums.FpztEnum;
import com.dxhy.common.service.InvoiceLogService;
import com.dxhy.common.util.JsonUtils;
import com.dxhy.common.utils.Base64Encoding;
import com.dxhy.common.utils.CommonUtil;
import com.dxhy.common.vo.InvoiceLog;
import com.dxhy.core.dao.CoreConfirmDao;
import com.dxhy.core.dao.TDxHttpZzsfpgjDao;
import com.dxhy.core.job.dao.*;
import com.dxhy.core.job.entity.*;
import com.dxhy.core.job.pojo.*;
import com.dxhy.core.job.pojo.down.RecordInvoiceDownModel;
import com.dxhy.core.job.pojo.down.UsedcarInvoiceModel;
import com.dxhy.core.job.service.*;
import com.dxhy.core.job.utils.TransitionUtils;
import com.dxhy.core.util.Dqyjkdyutil;
import com.dxhy.jxpt.baseService.dao.TdxRecordTspzKzxxDao;
import com.dxhy.jxpt.baseService.dao.TdxTdysMhxcdCoreDao;
import com.dxhy.jxpt.baseService.dao.TdxTdysMhxcdMxCoreDao;
import com.dxhy.jxpt.baseService.dao.TdxTdysTldzkpCoreDao;
import com.dxhy.jxpt.baseService.poolPush.PoolLogService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.math.BigDecimal;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 功能描述
 *
 * @author 陈刚扬
 * @date 2020/10/28
 * @return
 */

@Service("InvoiceInterfaceService")
@Slf4j
@SuppressWarnings({"AlibabaUndefineMagicConstant", "AlibabaMethodTooLong"})
public class InvoiceInterfaceServiceImpl implements InvoiceInterfaceService {

    @Resource
    private TDxHttpLogJobDao tDxHttpLogDao;
    @Resource
    private TDxRecordInvoiceJobDao tDxRecordInvoiceJobDao;
    @Resource
    private PoolLogService poolLogService;
    @Resource
    private CoreConfirmDao coreConfirmDao;
    @Resource
    private TDxVehicleSaleInvoiceSalesDao tDxVehicleSaleInvoiceSalesDao;
    @Resource
    private InvoiceInterfaceService invoiceInterfaceService;
    @Resource
    private DataPlatformFailRecordDao dataPlatformFailRecordDao;
    @Resource
    private TDxSaleRecordInvoiceJobDao tDxSaleRecordInvoiceJobDao;
    @Resource
    private TDxHttpZzsfpgjDao tDxHttpZzsfpgjDao;
    @Resource
    private TDxRecordInvoiceDetailJobDao tDxRecordInvoiceDetailDao;
    @Resource
    private TDxRecordInvoiceDetailSalesJobDao tDxRecordInvoiceDetailSalesJobDao;
    @Resource
    private TDxVehicleSaleInvoiceDao tDxVehicleSaleInvoiceDao;
    @Resource
    private TDxRecordInvoiceStatisticsJobDao tDxRecordInvoiceStatisticsDao;
    @Resource
    private TDxRecordInvoiceStatisticsService tDxRecordInvoiceStatisticsService;
    @Resource
    private TDxRecordInvoiceDetailJobService tDxRecordInvoiceDetailJobService;
    @Resource
    InvoiceLogService invoiceLogService;
    @Resource
    private TdxRecordTspzKzxxDao tdxRecordTspzKzxxDao;
    @Resource
    private TdxInvoiceFileService tdxInvoiceFileService;
    @Resource
    private TdxInvoiceFileNewService tdxInvoiceFileNewService;
    @Resource
    private TdxTdysTldzkpCoreDao tdxTdysTldzkpCoreDao;
    @Resource
    private TdxTdysMhxcdCoreDao tdxTdysMhxcdCoreDao;
    @Resource
    private TdxTdysMhxcdMxCoreDao tdxTdysMhxcdMxCoreDao;



    @Override
    public void sendRequest(String type, String taxno, String db, String aceId, String aceKey, String company) {

        // 请求通用头
        GlobalInfo globalInfo = new GlobalInfo();
        // 请求通用
        Authorize authorize = new Authorize();
        // 具体参数
        CollectData collectData = new CollectData();
        BaseQueJson bqj = new BaseQueJson();
        int totalRow = 0;
        int addRow = 0;
        log.info("-封装参数-");
        try {
            // 封装参数
            globalInfo.setAppId("JXFP");
            globalInfo.setVersion(CoreConstants.version);
            String exchangeId = getDataExchangeId();
            globalInfo.setDataExchangeId(exchangeId);
            globalInfo.setInterfaceCode(CoreConstants.invoiceGet);
            globalInfo.setEnterpriseCode(CoreConstants.enterpriseCode);
            authorize.setAppSecId(aceId);
            collectData.setBuyerTaxNo(taxno);
            collectData.setInvoiceType(type);
            // 随机生成32位批次号
            String batchNo = getBatchNo();
            collectData.setBatchNo(batchNo);
            DynamicContextHolder.push(db + DbConstant.BUSINESS_READ);
            collectData.setAcquisitionDateBegin(getBeginTimeQpm(taxno, db, type));
            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 = makeAppSec(base64Data, exchangeId, CoreConstants.invoiceGet, aceId, aceKey);
                authorize.setAppSec(appSec);
                bqj.setData(base64Data);
                bqj.setAuthorize(authorize);
                bqj.setGlobalInfo(globalInfo);
                String collectDataStr = JSONObject.toJSONString(bqj);
                log.info("url:" + CoreConstants.collectUrl);
                log.info("请求参数：" + collectDataStr);
                log.info("发送请求--");
                // 保存请求记录
                TDxHttpLog httpLog = new TDxHttpLog();
                httpLog.setTaxno(taxno);
                httpLog.setType("01");
                httpLog.setReqText(collectDataStr);
                // 得到返回报文，解析拿出返回的数量，累加用于判断数量
                httpLog.setReqDate(new Date());
                String responseJson = HttpUtil.post(CoreConstants.collectUrl, collectDataStr, 240000);
                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);
                DynamicContextHolder.push(db + DbConstant.BUSINESS_WRITE);
                coreConfirmDao.insert(httpLog);
                log.info("httplog入库完成，立马解析");
                parseSingleHttpLog(httpLog,db);
                if ("0000".equals(gatherData.getReturnStateInfo().getReturnCode())) {
                    if (gather.getInvoices() != null && gather.getInvoices().size() != 0) {
                        totalRow = gather.getTotalRows();
                        addRow += gather.getContentRows();
                    } else {
                        break;
                    }
                    if (addRow < totalRow) {
                        collectData.setStartRow(addRow);
                    } else {
                        break;
                    }
                } else {
                    break;
                }
            }

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

        }
    }

    /**
     * 获取时间戳
     *
     * @return String
     */
    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 CoreConstants.enterpriseCode + simpleDateFormat.format(new Date()) + data;
    }

    /**
     * 加密方法
     */
    public String makeAppSec(String data, String dataExchangeId, String interfaceCode, String aceId, String aceKey) {
        String srcStr =
                "POST/rest/invoice/dii?authorize={\"appSecId\":\"" + aceId + "\"}&globalInfo={\"appId\":\"" + CoreConstants.appId
                        + "\",\"version\":\"" + CoreConstants.version + "\",\"interfaceCode\":\"" + interfaceCode + "\",\"enterpriseCode\":\""
                        + CoreConstants.enterpriseCode + "\",\"dataExchangeId\":\"" + dataExchangeId + "\"}&" + "data=" + data + "";
        log.info("待加密的请求：" + srcStr);
        SecretKeySpec keySpec = null;
        keySpec = new SecretKeySpec(aceKey.getBytes(StandardCharsets.UTF_8), "HmacSHA1");
        Mac mac = null;
        try {
            mac = Mac.getInstance("HmacSHA1");
        } catch (NoSuchAlgorithmException e) {
           log.info("业务处理异常：{}", e);
        }
        try {
            mac.init(keySpec);
        } catch (InvalidKeyException e) {
           log.info("业务处理异常：{}", e);
        }
        byte[] singBytes = new byte[0];
        singBytes = mac.doFinal(srcStr.getBytes(StandardCharsets.UTF_8));
        String appSec = Base64.encode(singBytes);
        log.info("interfaceCode接口生成的加密串=appSec--");
        return appSec;
    }

    /**
     * 获取批次号
     */
    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;
    }

    /**
     * @param taxno
     * @Desc 发票状态获取接口
     */
    @Override
    public void sendStateRequest(String taxno, String db, String aceId, String aceKey) {
        // 请求通用头
        GlobalInfo globalInfo = new GlobalInfo();
        // 请求通用
        Authorize authorize = new Authorize();
        // 具体参数
        InvoiceStateData invoiceStateData = new InvoiceStateData();
        BaseQueJson bqj = new BaseQueJson();
        int totalRow = 0;
        int addRow = 0;
        log.info("-封装参数-");
        try {
            // 封装参数
            globalInfo.setAppId("JXFP");
            globalInfo.setVersion(CoreConstants.version);
            String exchangeId = getDataExchangeId();
            globalInfo.setDataExchangeId(exchangeId);
            globalInfo.setInterfaceCode(CoreConstants.invoiceState);
            globalInfo.setEnterpriseCode(CoreConstants.enterpriseCode);
            authorize.setAppSecId(aceId);
            invoiceStateData.setBuyerTaxNo(taxno);
            // 随机生成32位批次号
            String batchNo = getBatchNo();
            invoiceStateData.setBatchNo(batchNo);
            DynamicContextHolder.push(db + DbConstant.BUSINESS_READ);
            invoiceStateData.setStatusChangeDateBegin(getBeginTime(taxno, "", "02"));
            invoiceStateData.setStatusChangeDateEnd(getEndTime());
            invoiceStateData.setStartRow(1);
            invoiceStateData.setStatus("1");

            while (true) {
                String dataStr = JSONObject.toJSONString(invoiceStateData);
                String base64Data = Base64.encode(dataStr);
                String appSec = makeAppSec(base64Data, exchangeId, CoreConstants.invoiceState, aceId, aceKey);
                authorize.setAppSec(appSec);
                bqj.setData(base64Data);
                bqj.setAuthorize(authorize);
                bqj.setGlobalInfo(globalInfo);
                String invoiceStateDataStr = JSONObject.toJSONString(bqj);
                log.info("url:" + CoreConstants.collectUrl);
                log.info("请求参数：" + invoiceStateDataStr);
                log.info("发送请求--");
                // 保存请求记录
                TDxHttpLog log = new TDxHttpLog();
                log.setTaxno(taxno);
                log.setType("02");
                log.setReqText(invoiceStateDataStr);
                // 得到返回报文，解析拿出返回的数量，累加用于判断数量
                log.setReqDate(new Date());
                String responseJson = HttpUtil.post(CoreConstants.collectUrl, invoiceStateDataStr, 30000);
                log.setResDate(new Date());
                // 根据发票类型保存不同实体
                BaseResJson gatherData = JSONObject.parseObject(responseJson, BaseResJson.class);
                String base64data = gatherData.getData();
                log.setResText(responseJson);
                log.setStatus("0");
                if (base64data != null) {
                    String dataJson = Base64.decodeStr(base64data);
                    StatusInfo gather = JSONObject.parseObject(dataJson, StatusInfo.class);
                    if ("0000".equals(gatherData.getReturnStateInfo().getReturnCode())) {
                        if (gather.getInvoices() != null && gather.getInvoices().size() != 0) {
                            totalRow = gather.getTotalRows();
                            addRow += gather.getContentRows();
                            invoiceStateConsumer(responseJson, log, db, taxno);
                        } else {
                            break;
                        }
                        if (addRow < totalRow) {
                            invoiceStateData.setStartRow(addRow);
                        } else {
                            break;
                        }
                    } else {
                        break;
                    }

                } else {
                    break;
                }
            }

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

        }
    }

    /**
     * 发票状态获取接口返回报文解析
     *
     * @param db
     */
    @SuppressWarnings({"unused", "rawtypes"})
    public void invoiceStateConsumer(String responseJson, TDxHttpLog tDxHttpLog, String db, String taxno) {
        DynamicContextHolder.push(DbConstant.BASICS_READ);
        String company = tDxRecordInvoiceJobDao.findCompany(taxno);
        String total = "";
        try {
            log.info("开始解析报文  报文内容：" + responseJson);
            // 根据发票类型保存不同实体
            BaseResJson gatherData = JSONObject.parseObject(responseJson, BaseResJson.class);
            log.info(gatherData.toString());
            String base64data = gatherData.getData();
            String dataJson = Base64.decodeStr(base64data);
            StatusInfo gather = JSONObject.parseObject(dataJson, StatusInfo.class);
            List<StateInfo> list = gather.getInvoices();
            total = list.size() + "";
            List<InvoiceLog> logList = new ArrayList<>();
            //要推送票池的uuid集合
            List<String> uuids = new LinkedList();
            for (StateInfo stateInfo : list) {
                State state = TransitionUtils.getStateInfo(stateInfo);
                /**
                 * 认证类型(1-抵扣 2-退税 3-代理退税4-不抵扣 5-撤销认证 6-撤销不抵扣 发票已认证、已勾选有该标签）
                 */
                String lx = state.getLegalizeLx() + "";
                String rzFlag = "1";
                DynamicContextHolder.push(db + DbConstant.BUSINESS_READ);
                TDxRecordInvoice entity = tDxRecordInvoiceJobDao.selectOne(Wrappers
                        .<TDxRecordInvoice>query().eq("uuid", state.getInvoiceCode() + state.getInvoiceNo()));
                if (entity == null) {
                    log.info("抵账表不存在当前发票，暂不处理");
                    continue;
                }
                // 添加不同的认证类型，更新对应字段 0918
                if (StringUtils.isNotEmpty(lx)) {
                    if ("5".equals(lx) || "6".equals(lx)) {
                        continue;
                    } else {
                        switch (lx) {
                            case "1":
                                if ("1".equals(entity.getRzhYesorno())) {
                                    rzFlag = null;
                                } else {
                                    state.setBdkStatus("1");
                                }
                                break;
                            case "4":
                                if ("2".equals(entity.getRzhYesorno())) {
                                    rzFlag = null;
                                } else {
                                    state.setBdkStatus("2");
                                    state.setLegalizeState("2");
                                }
                                break;
                            case "0":
                                if ("0".equals(entity.getRzhYesorno())) {
                                    rzFlag = null;
                                } else {
                                    state.setBdkStatus("0");
                                }
                                break;
                            case "2":
                            case "3":
                                if ("0".equals(entity.getRzhYesorno())) {
                                    rzFlag = null;
                                } else {
                                    state.setBdkStatus("3");
                                    // state.setLegalizeState("3");
                                }
                                break;
                            default:
                                break;
                        }
                        DynamicContextHolder.push(db + DbConstant.BUSINESS_WRITE);
                        log.info("如果抵账库有，authStatus状态是 2已确认，3已发送认证，5认证失败，不更新rzh_yesorno,rzlx,bdk_status,cxbdk_status字段");
                        String authStatus = entity.getAuthStatus();
                        if("2".equals(authStatus)||"3".equals(authStatus)||"5".equals(authStatus)){
                            state.setLegalizeState(null);
                            //state.setRzlx(null);
                            state.setBdkStatus(null);
                            //state.setCxbdkStatus(null);
                        }
                        int result = tDxRecordInvoiceJobDao.updateInvoiceByState(state, rzFlag);
                    }
                } else {
                    if ("0".equals(entity.getRzhYesorno())) {
                        rzFlag = null;
                    } else {
                        // 更新发票数据
                        state.setBdkStatus("0");
                    }
                    DynamicContextHolder.push(db + DbConstant.BUSINESS_WRITE);
                    log.info("如果抵账库有，authStatus状态是 2已确认，3已发送认证，5认证失败，不更新rzh_yesorno,rzlx,bdk_status,cxbdk_status字段");
                    String authStatus = entity.getAuthStatus();
                    if("2".equals(authStatus)||"3".equals(authStatus)||"5".equals(authStatus)){
                        state.setLegalizeState(null);
                        //state.setRzlx(null);
                        state.setBdkStatus(null);
                        //state.setCxbdkStatus(null);
                    }
                    int result = tDxRecordInvoiceJobDao.updateInvoiceByState(state, rzFlag);
                }

                uuids.add((StringUtils.isEmpty(state.getInvoiceCode())?"":state.getInvoiceCode())+state.getInvoiceNo());
                if (!"0".equals(state.getInvoiceStatus())) {
                    InvoiceLog invoiceLog = new InvoiceLog();
                    invoiceLog.setInvoiceCode(state.getInvoiceCode());
                    invoiceLog.setInvoiceNo(state.getInvoiceNo());
                    invoiceLog.setType("6");
                    invoiceLog.setCreateDate(new Date());
                    invoiceLog.setInputStatus("19");
                    logList.add(invoiceLog);
                }
            }
            //推送新票池记录表
            poolLogService.pushChangeToPool(ConfigureConstant.POOL_SJLX_JXFP_1, uuids, ConfigureConstant.POOL_BGLX_ZTBG_2);

            tDxHttpLog.setStatus("1");
            tDxHttpLog.setTotal(total);
            DynamicContextHolder.push(db + DbConstant.BUSINESS_WRITE);
            coreConfirmDao.insert(tDxHttpLog);
            if (logList.size() > 0) {
                invoiceLogService.toInvoiceLog(logList);
            }
        } catch (Exception e) {
            tDxHttpLog.setStatus("2");
            tDxHttpLog.setTotal(total);
            DynamicContextHolder.push(db + DbConstant.BUSINESS_WRITE);
            coreConfirmDao.insert(tDxHttpLog);
           log.info("业务处理异常：{}", e);
        }
    }

    /**
     * 获取开始时间
     *
     * @return
     */
    private String getBeginTime(String taxno, String linkName, String type) {
        String lastTime = tDxRecordInvoiceJobDao.selectLastInvoiceDate(taxno, linkName, type);
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
        if (lastTime == null || "".equals(lastTime)) {
            DynamicContextHolder.push(DbConstant.BASICS_READ);
            TAcOrg org = tDxRecordInvoiceJobDao.selectOrgCollectDate(taxno);
            if (org != null && org.getFirstCollectDate() != null) {
                lastTime = simpleDateFormat.format(org.getFirstCollectDate());
            } else {
                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 {
            // 避免防止漏票，提前一小时

            try {
                Date date = simpleDateFormat.parse(lastTime);
                Calendar cal = Calendar.getInstance();
                cal.setTime(date);
                cal.add(Calendar.HOUR_OF_DAY, -1);
                date = cal.getTime();
                lastTime = simpleDateFormat.format(date);
            } catch (ParseException e) {
               log.info("业务处理异常：{}", e);
            }
        }

        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());
    }

    /**
     * @param taxno
     * @Desc 勾选发票获取接口
     */
    @Override
    public void sendSelectRequest(String taxno, String db, String aceId, String aceKey) {
        DynamicContextHolder.push(db + DbConstant.BUSINESS_READ);
        // 请求通用头
        GlobalInfo globalInfo = new GlobalInfo();
        // 请求通用
        Authorize authorize = new Authorize();
        // 具体参数
        InvoiceSelectData invoiceSelectData = new InvoiceSelectData();
        BaseQueJson bqj = new BaseQueJson();
        int totalRow = 0;
        int addRow = 0;

        log.info("-封装参数-");
        try {
            // 封装参数
            globalInfo.setAppId("JXFP");
            globalInfo.setVersion(CoreConstants.version);
            String exchangeId = getDataExchangeId();
            globalInfo.setDataExchangeId(exchangeId);
            globalInfo.setInterfaceCode(CoreConstants.invoiceSelection);
            globalInfo.setEnterpriseCode(CoreConstants.enterpriseCode);
            authorize.setAppSecId(aceId);
            invoiceSelectData.setBuyerTaxNo(taxno);
            // 随机生成32位批次号
            String batchNo = getBatchNo();
            invoiceSelectData.setBatchNo(batchNo);
            invoiceSelectData.setAcquisitionDateBegin(getBeginTime(taxno, "", "06"));
            invoiceSelectData.setAcquisitionDateEnd(getEndTime());
            invoiceSelectData.setStartRow(1);
            invoiceSelectData.setStatus("1");

            while (true) {
                String dataStr = JSONObject.toJSONString(invoiceSelectData);
                String base64Data = Base64.encode(dataStr);
                String appSec = makeAppSec(base64Data, exchangeId, CoreConstants.invoiceSelection, aceId, aceKey);
                authorize.setAppSec(appSec);
                bqj.setData(base64Data);
                bqj.setAuthorize(authorize);
                bqj.setGlobalInfo(globalInfo);
                String collectDataStr = JSONObject.toJSONString(bqj);
                log.info("url:" + CoreConstants.collectUrl);
                log.info("请求参数：" + collectDataStr);
                log.info("发送请求--");
                // 保存请求记录
                TDxHttpLog httpLog = new TDxHttpLog();
                httpLog.setTaxno(taxno);
                httpLog.setType("06");
                httpLog.setReqText(collectDataStr);
                // 得到返回报文，解析拿出返回的数量，累加用于判断数量
                httpLog.setReqDate(new Date());
                String responseJson = HttpUtil.post(CoreConstants.collectUrl, collectDataStr, 600000);
                httpLog.setResDate(new Date());
                log.info("返回参数:{}", responseJson);
                // 根据发票类型保存不同实体
                BaseResJson gatherData = JSONObject.parseObject(responseJson, BaseResJson.class);
                String base64data = gatherData.getData();
                httpLog.setResText(responseJson);
                httpLog.setStatus("0");
                if (base64data != null) {
                    String dataJson = Base64.decodeStr(base64data);
                    GatherSelectData gather = JSONObject.parseObject(dataJson, GatherSelectData.class);
                    if ("0000".equals(gatherData.getReturnStateInfo().getReturnCode())) {
                        if (gather.getInvoices() != null && gather.getInvoices().size() != 0) {
                            totalRow = gather.getTotalRows();
                            addRow += gather.getContentRows();
                            // 实现mq数据推送
                            invoiceSelectConsumer(responseJson, httpLog, taxno, db);
                        } else {
                            break;
                        }
                        if (addRow < totalRow) {
                            invoiceSelectData.setStartRow(addRow);
                        } else {
                            break;
                        }
                    } else {
                        break;
                    }
                } else {
                    break;
                }
            }

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

        }
    }

    /**
     * 勾选发票获取接口返回报文解析
     *
     * @param responseJson 入参
     * @param httpLog      日志
     * @param taxno        税号
     * @param db           数据库
     */
    public void invoiceSelectConsumer(String responseJson, TDxHttpLog httpLog, String taxno, String db) {

        String total = "";
        try {
            // 根据发票类型保存不同实体
            BaseResJson gatherData = JSONObject.parseObject(responseJson, BaseResJson.class);
//            log.info("返回报文：" + responseJson);
            String base64data = gatherData.getData();
            String dataJson = Base64.decodeStr(base64data);
            GatherSelectData gather = JSONObject.parseObject(dataJson, GatherSelectData.class);
            String invoices = gather.getInvoices().toString();
            List<InvoiceSelectInfo> invoicesList = JSONObject.parseArray(invoices, InvoiceSelectInfo.class);
            gather.setInvoices(invoicesList);
            total = invoicesList.size() + "";
            // 获取company值
            DynamicContextHolder.push(DbConstant.BASICS_READ);
            String company = tDxRecordInvoiceJobDao.findCompany(taxno);
            List<InvoiceLog> logList = new ArrayList<>();
            //要推送票池的uuid集合
            List<String> uuids = new LinkedList();
            for (InvoiceSelectInfo invoiceSelectInfo : invoicesList) {
                invoiceSelectInfo.setUuid(invoiceSelectInfo.getInvoiceCode() + invoiceSelectInfo.getInvoiceNo());
                if ("1".equals(invoiceSelectInfo.getLegalizeState())) {
                    //认证处理状态 0-未认证 1-已勾选未确认，2已确认 3 已发送认证 4 认证成功 5 认证失败
                    invoiceSelectInfo.setAuthStatus("4");
                } else {
                    invoiceSelectInfo.setAuthStatus("0");
                }


                // 判断库里是否已经存在，存在则只更新发票状态，状态更新时间，认证状态以及相关字段更新
                DynamicContextHolder.push(db + DbConstant.BUSINESS_READ);
                TDxRecordInvoice entity = tDxRecordInvoiceJobDao
                        .findInvoiceByUUid(invoiceSelectInfo.getUuid());
                if (entity != null) {
                    boolean flag = false;

                    //设置红字锁定标识
                    if(FpztEnum.HZDQR.getFpztDm().equals(invoiceSelectInfo.getInvoiceStatus())){
                        entity.setLqHzsdbs("Y");
                    }
                    //以redlock为准。如果是Y，则同步更改发票状态为80
                    if(StringUtils.isNotBlank(invoiceSelectInfo.getRedLock())){
                        entity.setLqHzsdbs(invoiceSelectInfo.getRedLock());
                        if("Y".equals(invoiceSelectInfo.getRedLock())){
                            entity.setInvoiceStatus("80");
                        }
                    }

                    if (StringUtils.isBlank(entity.getCheckCode())
                            && StringUtils.isNotBlank(invoiceSelectInfo.getCheckCode())) {
                        entity.setCheckCode(invoiceSelectInfo.getCheckCode());
                        entity.setCheckDate(new Date());
                        flag = true;
                    }
                    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());
                            entity.setSfygx("1");
                            if (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());
                            entity.setSfygx("1");
                            if (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("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");
                        entity.setSfygx("0");
                        flag = true;
                    }
                    //TODO 这块业务不理解？？
                    if ("1".equals(entity.getSourceSystem()) && "0".equals(entity.getCollectStatus())) {
                        entity.setCollectStatus("1");
                        entity.setCollectFrom("0");
                        entity.setCollectDate(new Date());
                        entity.setPoolStatus("1");
                        entity.setInPoolReason("数据重复");
                        flag = true;
                    }
                    if (flag) {
                        DynamicContextHolder.push(db + DbConstant.BUSINESS_WRITE);
                        if (StringUtils.isBlank(entity.getInvoiceCode())) {
                            entity.setInvoiceCode("");
                        }
                        log.info("采集时，如果抵账库有，authStatus状态是 2已确认，3已发送认证，5认证失败，不更新rzh_yesorno,rzlx,bdk_status,cxbdk_status字段");
                        String authStatus = entity.getAuthStatus();
                        if("2".equals(authStatus)||"3".equals(authStatus)||"5".equals(authStatus)){
                            entity.setRzhYesorno(null);
                            entity.setRzlx(null);
                            entity.setBdkStatus(null);
                            entity.setCxbdkStatus(null);
                        }
                        tDxRecordInvoiceJobDao.updateInvoice(entity, taxno);
                    }
                } else {
                    if (StringUtils.isBlank(invoiceSelectInfo.getLegalizeDate())) {
                        invoiceSelectInfo.setLegalizeDate(null);
                    }
                    TDxRecordInvoice record = exchangePo2Entity(invoiceSelectInfo);
                    record.setCompany(company);
                    record.setCollectStatus("1");
                    record.setCollectFrom("0");
                    record.setCollectDate(new Date());
                    record.setPoolStatus("0");
                    DynamicContextHolder.push(db + DbConstant.BUSINESS_WRITE);
                    tDxRecordInvoiceJobDao.insert(record);
                }
                InvoiceLog invoiceLog = new InvoiceLog();
                invoiceLog.setInvoiceCode(invoiceSelectInfo.getInvoiceCode());
                invoiceLog.setInvoiceNo(invoiceSelectInfo.getInvoiceNo());
                invoiceLog.setType("1");
                invoiceLog.setInputStatus("0");
                invoiceLog.setCreateDate(new Date());
                invoiceLog.setInputName("系统自动");
                logList.add(invoiceLog);

                uuids.add(invoiceSelectInfo.getUuid());
            }
            //推送新票池记录表
            poolLogService.pushChangeToPool(ConfigureConstant.POOL_SJLX_JXFP_1, uuids, ConfigureConstant.POOL_BGLX_SJBG_1);

            httpLog.setStatus("1");
            httpLog.setTotal(total);
            DynamicContextHolder.push(db + DbConstant.BUSINESS_WRITE);
            coreConfirmDao.insert(httpLog);
            if (logList.size() > 0) {
                invoiceLogService.toInvoiceLog(logList);
            }

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

    private TDxRecordInvoice exchangePo2Entity(InvoiceSelectInfo po) {
        TDxRecordInvoice entity = new TDxRecordInvoice();
        entity.setInvoiceCode(po.getInvoiceCode());
        entity.setInvoiceNo(po.getInvoiceNo());
        if (StringUtils.isNotBlank(po.getElectronicInvoiceNo())) {
            entity.setEleInvoiceNo(po.getElectronicInvoiceNo());
        }
        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());
        }
        //设置红字锁定标识
        if(FpztEnum.HZDQR.getFpztDm().equals(po.getInvoiceStatus())){
            entity.setLqHzsdbs("Y");
        }
        //以redlock为准。如果是Y，则同步更改发票状态为80
        if(StringUtils.isNotBlank(po.getRedLock())){
            entity.setLqHzsdbs(po.getRedLock());
            if("Y".equals(po.getRedLock())){
                entity.setInvoiceStatus("80");
            }
        }
        entity.setInvoiceAmount(new BigDecimal(po.getInvoiceAmount()));
        entity.setTaxAmount(new BigDecimal(po.getTaxAmount()));
        entity.setTotalAmount(new BigDecimal(po.getInvoiceAmount()).add(new BigDecimal(po.getTaxAmount())));
        entity.setGfTaxNo(po.getBuyerTaxNo());
        entity.setGfName(po.getBuyerName());
        entity.setXfTaxNo(po.getSalerTaxNo());
        entity.setXfName(po.getSalerName());
        entity.setGxjzr(po.getLegalizeEndDate());
        entity.setGxfwq(po.getLegalizeInvoiceDateBegin());
        entity.setGxfwz(po.getLegalizeInvoiceDateEnd());

        entity.setSfdbts(po.getSfdbts());
        entity.setRzlx(po.getRzlx());
        entity.setCreateDate(new Date());
        entity.setCheckDate(new Date());
        entity.setUuid(po.getUuid());
        entity.setDetailYesorno("0");
        entity.setSourceSystem("0");
        entity.setValid("1");
        entity.setOutStatus("0");

        entity.setDqskssq(po.getCurrentTaxPeriod());
        entity.setRzhType(po.getLegalizeType());
        if ("1".equals(po.getLegalizeState()) && !"4".equals(po.getRzlx())) {
            entity.setRzhYesorno(po.getLegalizeState());
            entity.setAuthStatus("4");
            entity.setSfygx(po.getLegalizeState());
            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");
            entity.setSfygx("0");
        }
        if ("1".equals(po.getLegalizeState()) && ("2".equals(po.getRzlx()) || "3".equals(po.getRzlx()))) {
            entity.setRzhYesorno("1");
            entity.setAuthStatus("4");
            entity.setSfygx(po.getLegalizeState());
            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("3");
        }
        if ("1".equals(po.getLegalizeState()) && "4".equals(po.getRzlx())) {
            entity.setRzhYesorno("2");
            entity.setAuthStatus("4");
            entity.setSfygx(po.getLegalizeState());
            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.setXxly(po.getXxly());
        entity.setGlzt(po.getGlzt());
        if (StringUtils.isNotBlank(po.getDkse())) {
            entity.setDkTaxAmount(new BigDecimal(po.getDkse()));
        } else {
            entity.setDkTaxAmount(new BigDecimal(po.getTaxAmount()));
        }
        if (StringUtils.isNotBlank(po.getBdkMessage())) {
            entity.setBdkMessage(po.getBdkMessage());
        }
        entity.setInvoiceSource(po.getInvoiceSources());
        entity.setYqkgxbz(po.getYqkgxbz());
        entity.setYclx(po.getYclx());
        entity.setCheckCode(po.getCheckCode());
        entity.setTdly("0");
        return entity;
    }

    /**
     * @return
     * @Desc 获取购方税号信息
     */
    @Override
    public List<TAcOrg> getOrgTaxno() {
        // 获取购方税号集合
        DynamicContextHolder.push(DbConstant.BASICS_READ);
        return coreConfirmDao.getTaxno();
    }

    /**
     * 获取开始时间 -- 全票面
     *
     * @return
     */
    private String getBeginTimeQpm(String taxno, String linkName, String type) {
        String lastTime = tDxRecordInvoiceJobDao.selectLastInvoiceDateQPM(taxno, linkName, type);
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
        if (lastTime == null || "".equals(lastTime)) {
            DynamicContextHolder.push(DbConstant.BASICS_READ);
            TAcOrg org = tDxRecordInvoiceJobDao.selectOrgCollectDate(taxno);
            if (org != null && org.getFirstCollectDate() != null) {
                lastTime = simpleDateFormat.format(org.getFirstCollectDate());
            } else {
                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) {
               log.info("业务处理异常：{}", e);
            }
        }
        return lastTime;
    }

    /**
     * 获取还没有解析的01类型日志
     *
     * @return
     */
    @Override
    public List<TDxHttpLog> getNotParseHttpLogs(String taxno, String type) {

        return tDxHttpLogDao.getNotParseHttpLogs(taxno, type);
    }

    @Override
    public List<String> getNotParseTaxnos(String type) {

        return tDxHttpLogDao.getNotParseTaxnos(type);
    }

    @Override
    public void updateNotParseHttpLogsStatus(List<TDxHttpLog> logs) {

        tDxHttpLogDao.updateNotParseHttpLogsStatus(logs);
    }

    /**
     * 解析返回报文 发票获取
     *
     * @param db 数据库
     */
    @Override
    public void subscribe(String taxno, String db) {
        // 修改采集和解析分离
        DynamicContextHolder.push(db + DbConstant.BUSINESS_READ);
        List<TDxHttpLog> logs = this.getNotParseHttpLogs(taxno, "01");
        if (logs != null && logs.size() > 0) {
            DynamicContextHolder.push(db + DbConstant.BUSINESS_WRITE);
            this.updateNotParseHttpLogsStatus(logs);
            for (TDxHttpLog tDxHttpLog : logs) {
                //解析单条数据方法
                parseSingleHttpLog(tDxHttpLog,db);
            }
        }

    }

    /**
    * @Description 解析单个httplog数据，成功返回true，失败返回false
    * @param tDxHttpLog
    * @param db
     * @Return void
    * @Author wangruwei
    * @Date 2024/12/23 9:57
    **/
    private void parseSingleHttpLog(TDxHttpLog tDxHttpLog, String db) {
        try {
            String responseJson = tDxHttpLog.getResText();
            Long logid = tDxHttpLog.getLogId();
            log.info("开始解析报文id:" + logid + "  报文内容：" + responseJson);
            // 根据发票类型保存不同实体
            BaseResJson gatherData = JSONObject.parseObject(responseJson, BaseResJson.class);
            log.info("返回报文：" + responseJson);
            log.info(gatherData.toString());
            String base64data = gatherData.getData();
            if (base64data != null) {
                String dataJson = Base64.decodeStr(base64data);
                log.info("data体：" + dataJson);
                GatherData gather = JSONObject.parseObject(dataJson, GatherData.class);
                if (gather.getContentRows() == 0) {
                    tDxHttpLog.setStatus("1");
                    tDxHttpLog.setTotal("0");
                    DynamicContextHolder.push(db + DbConstant.BUSINESS_WRITE);
                    tDxHttpLogDao.updateHttoLogById(tDxHttpLog);
                    return;
                }
                String type = gather.getInvoiceType();
                if ("01".equals(type)
                        || "08".equals(type)
                        || "14".equals(type)
                        || "31".equals(type)
                        || "185".equals(type)
                        || "183".equals(type)) {
                    parseInvoice(logid, tDxHttpLog, dataJson, db);
                }
                else if("283".equals(type)){
                    //数电票（铁路电子客票）
                    processTlkpInvoiceCj(logid, tDxHttpLog, dataJson, db);
                }
                else if("161".equals(type)){
                    //数电票（航空运输电子客票行程单）
                    processHkysKpInvoiceCj(logid, tDxHttpLog, dataJson, db);
                }
                else if ("03".equals(type) || "383".equals(type)|| "187".equals(type)) {
                    //机动车，机动车电子统一发票，数电机动车，数电纸机动车
                    parseVehicleInvoice(logid, tDxHttpLog, dataJson, db);
                }
            }else {
                tDxHttpLog.setStatus("1");
                tDxHttpLog.setTotal("0");
                DynamicContextHolder.push(db + DbConstant.BUSINESS_WRITE);
                tDxHttpLogDao.updateHttoLogById(tDxHttpLog);
            }
        } catch (Exception e) {
            log.error("解析失败，错误:{}",e);
        }
    }

    /**
    * @Description 采集-数电票（航空运输电子客票行程单）解析入库
    * @param logid
    * @param tDxHttpLog
    * @param dataJson
    * @param db
    * @Return void
    * @Author wangruwei
    * @Date 2024/4/16 16:40
    **/
    private void processHkysKpInvoiceCj(Long logid, TDxHttpLog tDxHttpLog, String dataJson, String db) {
        GatherData gather = JSONObject.parseObject(dataJson, GatherData.class);
        String invoices = gather.getInvoices().toString();
        List<InvoiceInfo> invoicesList = JSONObject.parseArray(invoices, InvoiceInfo.class);
        gather.setInvoices(invoicesList);
        String total = invoicesList.size() + "";
        boolean flg = false;
        List<InvoiceLog> logList = new ArrayList<>();
        List<String> uuids = new LinkedList();
        //进项销项类型   01进项票   02销项票
        String jxXxtype = "01";
        for (InvoiceInfo invoiceInfo : invoicesList) {
            DynamicContextHolder.push(db + DbConstant.BUSINESS_READ);
            try {
                // 构建底账表（解析接口返回的信息）     invoiceInfo-大企业返回的数据结构
                TDxRecordInvoice recordInvoices = TransitionUtils.getInvoiceInfo(invoiceInfo,"0");
                recordInvoices.setCompany(tDxHttpLog.getCompany());
                recordInvoices.setSourceSystem("0");
                recordInvoices.setCollectFrom("0");
                TDxRecordInvoice invoice =
                        tDxRecordInvoiceJobDao.findInvoiceByUUid(recordInvoices.getUuid());
                //明细赋值-航空，航空明细
                TDxRecordInvoiceTdysMhxcd tdysMhxcd = new TDxRecordInvoiceTdysMhxcd();
                //tdysMhxcd.setDeductibleAmount();
                //tdysMhxcd.setInsuranceFee();
                //tdysMhxcd.setAviationDevelopmentFund();
                //tdysMhxcd.setOtherTaxes();
                //tdysMhxcd.setPrompt();
                //tdysMhxcd.setOutletCode();
                //tdysMhxcd.setVerificationCode();
                //tdysMhxcd.setVatRate();
                //tdysMhxcd.setEndorsement();
                tdysMhxcd.setTicketPrice(invoiceInfo.getTotalAmount());
                //tdysMhxcd.setTicketIssuanceStatus();
                //tdysMhxcd.setFuelSurcharge();
                //tdysMhxcd.setIssuingEntity();
                //tdysMhxcd.setIssuingDate();
                //tdysMhxcd.setValueAddedTaxAmount();
                recordInvoices.setTdysMhxcd(tdysMhxcd);

                List<TDxRecordInvoiceTdysMhxcdItem> mhxcdlist = new LinkedList();
                for (int i = 0; i < invoiceInfo.getDetailList().size(); i++) {
                    TDxRecordInvoiceTdysMhxcdItem mhxcdItem = new TDxRecordInvoiceTdysMhxcdItem();
                    BeanUtils.copyProperties(invoiceInfo.getDetailList().get(i), mhxcdItem);
                    mhxcdlist.add(mhxcdItem);
                }
                recordInvoices.setTdysMhxcdDetailList(mhxcdlist);

                this.insertHkysKpInvoice(recordInvoices, invoice, db, jxXxtype);
                // 保存发票关联请求日志id
                InvoiceLog invoiceLog = new InvoiceLog();
                invoiceLog.setInputName("系统自动");
                invoiceLog.setInvoiceCode(recordInvoices.getInvoiceCode());
                invoiceLog.setInvoiceNo(recordInvoices.getInvoiceNo());
                invoiceLog.setType("1");
                invoiceLog.setInputStatus("0");
                invoiceLog.setCreateDate(new Date());
                logList.add(invoiceLog);

                if("01".equals(jxXxtype)){
                    uuids.add(recordInvoices.getUuid());
                }
            } catch (ParseException e) {
                log.info("业务处理异常：{}", e);
                flg = true;
                break;
            }
        }

        //推送新票池记录表
        poolLogService.pushChangeToPool(ConfigureConstant.POOL_SJLX_JXFP_1, uuids, ConfigureConstant.POOL_BGLX_SJBG_1);

        if (flg) {
            DynamicContextHolder.push(db + DbConstant.BUSINESS_WRITE);
            tDxHttpLog.setStatus("2");
            tDxHttpLog.setTotal(total);
            tDxHttpLogDao.updateHttoLogById(tDxHttpLog);
        } else {
            tDxHttpLog.setStatus("1");
            tDxHttpLog.setTotal(total);
            DynamicContextHolder.push(db + DbConstant.BUSINESS_WRITE);
            tDxHttpLogDao.updateHttoLogById(tDxHttpLog);
        }
        if (logList.size() > 0) {
            invoiceLogService.toInvoiceLog(logList);
        }
    }

    /**
    * @Description 采集-数电铁路票解析
    * @param logid
    * @param tDxHttpLog
    * @param dataObj
    * @param db
    * @Return void
    * @Author wangruwei
    * @Date 2024/4/16 16:31
    **/
    private void processTlkpInvoiceCj(Long logid, TDxHttpLog tDxHttpLog, String dataObj, String db) {
        // 数电票-铁路
        GatherData gather = JSONObject.parseObject(dataObj, GatherData.class);
        String invoices = gather.getInvoices().toString();
        List<InvoiceInfo> invoicesList = JSONObject.parseArray(invoices, InvoiceInfo.class);
        gather.setInvoices(invoicesList);
        String total = invoicesList.size() + "";
        boolean flg = false;
        List<InvoiceLog> logList = new ArrayList<>();
        List<String> uuids = new LinkedList();
        //进项销项类型   01进项票   02销项票
        String jxXxtype = "01";
        for (InvoiceInfo invoiceInfo : invoicesList) {
            DynamicContextHolder.push(db + DbConstant.BUSINESS_READ);
            try {
                // 构建底账表（解析接口返回的信息）
                TDxRecordInvoice recordInvoices = TransitionUtils.getInvoiceInfo(invoiceInfo,"0");
                recordInvoices.setCompany(tDxHttpLog.getCompany());
                recordInvoices.setSourceSystem("0");
                recordInvoices.setCollectFrom("0");
                TDxRecordInvoice invoice =
                        tDxRecordInvoiceJobDao.findInvoiceByUUid(recordInvoices.getUuid());
                //明细赋值
                List<InvoiceTlkpInfoItem> detaillist = new LinkedList();
                if(!CollectionUtils.isEmpty(invoiceInfo.getDetailList())){
                    for (int i = 0; i < invoiceInfo.getDetailList().size(); i++) {
                        InvoiceTlkpInfoItem tlkpInfoItem = new InvoiceTlkpInfoItem();
                        BeanUtils.copyProperties(invoiceInfo.getDetailList().get(i), tlkpInfoItem);
                        detaillist.add(tlkpInfoItem);
                    }
                }
                recordInvoices.setDetailList(detaillist);
                this.insertTlkpInvoice(recordInvoices, invoice, db, jxXxtype);

                // 保存发票关联请求日志id
                InvoiceLog invoiceLog = new InvoiceLog();
                invoiceLog.setInputName("系统自动");
                invoiceLog.setInvoiceCode(recordInvoices.getInvoiceCode());
                invoiceLog.setInvoiceNo(recordInvoices.getInvoiceNo());
                invoiceLog.setType("1");
                invoiceLog.setInputStatus("0");
                invoiceLog.setCreateDate(new Date());
                logList.add(invoiceLog);

                if("01".equals(jxXxtype)){
                    uuids.add(recordInvoices.getUuid());
                }
            } catch (ParseException e) {
                log.info("业务处理异常：{}", e);
                flg = true;
                break;
            }
        }
        //推送新票池记录表
        poolLogService.pushChangeToPool(ConfigureConstant.POOL_SJLX_JXFP_1, uuids, ConfigureConstant.POOL_BGLX_SJBG_1);

        if (flg) {
            DynamicContextHolder.push(db + DbConstant.BUSINESS_WRITE);
            tDxHttpLog.setStatus("2");
            tDxHttpLog.setTotal(total);
            tDxHttpLogDao.updateHttoLogById(tDxHttpLog);
        } else {
            tDxHttpLog.setStatus("1");
            tDxHttpLog.setTotal(total);
            DynamicContextHolder.push(db + DbConstant.BUSINESS_WRITE);
            tDxHttpLogDao.updateHttoLogById(tDxHttpLog);
        }
        if (logList.size() > 0) {
            invoiceLogService.toInvoiceLog(logList);
        }
    }

    @SuppressWarnings("rawtypes")
    private void parseVehicleInvoice(Long httpLogId, TDxHttpLog tDxHttpLog, String dataObj, String db) {
        // 机动车销售统一发票
        GatherData gather = JSONObject.parseObject(dataObj, GatherData.class);
        String invoices = gather.getInvoices().toString();
        List<VehicleSaleInvoiceInfos> invoicesList = JSONObject.parseArray(invoices, VehicleSaleInvoiceInfos.class);
        gather.setInvoices(invoicesList);
        String total = invoicesList.size() + "";
        List<InvoiceLog> logList = new ArrayList<>();
        List<String> uuids = new LinkedList();
        boolean flg = false;
        for (VehicleSaleInvoiceInfos veinfo : invoicesList) {
            try {
                Map map = TransitionUtils.getVehicleInfo(veinfo);
                TDxVehicleSaleInvoice tDxVehicleSaleInvoice = (TDxVehicleSaleInvoice) map.get("vehicleSaleInvoice");
                TDxRecordInvoice invoice = (TDxRecordInvoice) map.get("veinfo");
                invoice.setSourceSystem("0");
                invoice.setCollectFrom("0");
                String code = invoice.getInvoiceCode();
                String no = invoice.getInvoiceNo();
                invoice.setUuid(code + no);
                invoice.setCompany(tDxHttpLog.getCompany());
                boolean isexist = isExistInvoice(invoice, db, "0");
                DynamicContextHolder.push(db + DbConstant.BUSINESS_WRITE);
                if (!isexist) {
                    if (!"0".equals(invoice.getInvoiceStatus())) {
                        invoice.setStatusUpdateDate(new Date());
                    }
                    invoice.setCreateDate(new Date());
                    invoice.setCheckDate(new Date());
                    // 第一次插入添加票池采集字段
                    invoice.setCollectStatus("1");
                    invoice.setCollectFrom("0");
                    invoice.setCollectDate(new Date());
                    invoice.setPoolStatus("0");
                    invoice.setTdly("0");
                    tDxRecordInvoiceJobDao.insert(invoice);
                }

                // 保存发票明细
                tDxRecordInvoiceDetailDao.delDetailJd(code + no);

                String invoiceCode = invoice.getInvoiceCode();
                String invoiceNo = invoice.getInvoiceNo();
                invoice.setUuid(invoiceCode + invoiceNo);
                tDxVehicleSaleInvoice.setUuid(invoiceCode + invoiceNo);
                log.info("机动车发票购方税号：" + invoice.getGfTaxNo());
                log.info("机动车发票uuid:" + invoiceCode + invoiceNo);

                InvoiceCheckVehicleDetailModel invoiceCheckVehicleDetailModel =
                        TransitionUtils.getVehicleDetaiModel(tDxVehicleSaleInvoice);
                // 由于暂时不用发票获取接口， 解放时参考查验定时任务转换实体再做插入
                tDxVehicleSaleInvoiceDao.insert(invoiceCheckVehicleDetailModel);

                int countDetail = tDxRecordInvoiceDetailDao.getDetailJd(code + no);

                if (countDetail > 0) {
                    invoice.setDetailYesorno("1");
                } else {
                    invoice.setDetailYesorno("0");
                }
                tDxRecordInvoiceDetailDao.updateDetailYesorno(invoice);
                InvoiceLog invoiceLog = new InvoiceLog();
                invoiceLog.setInputName("系统自动");
                invoiceLog.setInvoiceCode(invoiceCode);
                invoiceLog.setInvoiceNo(invoiceNo);
                invoiceLog.setType("1");
                invoiceLog.setInputStatus("0");
                invoiceLog.setCreateDate(new Date());
                logList.add(invoiceLog);

                uuids.add(invoiceCheckVehicleDetailModel.getUuid());
            } catch (ParseException e) {
               log.info("业务处理异常：{}", e);
                flg = true;
                break;
            }
        }
        //推送新票池记录表
        poolLogService.pushChangeToPool(ConfigureConstant.POOL_SJLX_JXFP_1, uuids, ConfigureConstant.POOL_BGLX_SJBG_1);

        DynamicContextHolder.push(db + DbConstant.BUSINESS_WRITE);
        if (flg) {
            tDxHttpLog.setStatus("2");
            tDxHttpLog.setTotal(total);
            tDxHttpLogDao.updateHttoLogById(tDxHttpLog);
        } else {
            tDxHttpLog.setStatus("1");
            tDxHttpLog.setTotal(total);
            tDxHttpLogDao.updateHttoLogById(tDxHttpLog);
        }
        if (logList.size() > 0) {
            invoiceLogService.toInvoiceLog(logList);
        }
    }

    public void parseInvoice(Long httpLogId, TDxHttpLog tDxHttpLog, String dataObj, String db) {
        // 增值税专用发票
        GatherData gather = JSONObject.parseObject(dataObj, GatherData.class);
        String invoices = gather.getInvoices().toString();
        List<InvoiceInfo> invoicesList = JSONObject.parseArray(invoices, InvoiceInfo.class);
        gather.setInvoices(invoicesList);
        String total = invoicesList.size() + "";
        boolean flg = false;
        List<InvoiceLog> logList = new ArrayList<>();
        List<String> uuids = new LinkedList();
        //进项销项类型   01进项票   02销项票
        String jxXxtype = "01";
        for (InvoiceInfo invoiceInfo : invoicesList) {
            DynamicContextHolder.push(db + DbConstant.BUSINESS_READ);
            try {
                // 构建底账表（解析接口返回的信息）
                TDxRecordInvoice recordInvoices = TransitionUtils.getInvoiceInfo(invoiceInfo,"0");
                recordInvoices.setCompany(tDxHttpLog.getCompany());
                recordInvoices.setSourceSystem("0");
                recordInvoices.setCollectFrom("0");
                TDxRecordInvoice invoice =
                        tDxRecordInvoiceJobDao.findInvoiceByUUid(recordInvoices.getUuid());
                List<InvoiceDetailInfo> detailList = invoiceInfo.getDetailList();
                recordInvoices = this.insertDetail(detailList, recordInvoices, db);
                this.insertInvoice(recordInvoices, invoice, db, detailList, jxXxtype);
                // 保存发票关联请求日志id
                InvoiceLog invoiceLog = new InvoiceLog();
                invoiceLog.setInputName("系统自动");
                invoiceLog.setInvoiceCode(recordInvoices.getInvoiceCode());
                invoiceLog.setInvoiceNo(recordInvoices.getInvoiceNo());
                invoiceLog.setType("1");
                invoiceLog.setInputStatus("0");
                invoiceLog.setCreateDate(new Date());
                logList.add(invoiceLog);

                if("01".equals(jxXxtype)){
                    uuids.add(recordInvoices.getUuid());
                }
            } catch (ParseException e) {
               log.info("业务处理异常：{}", e);
                flg = true;
                break;
            }
        }
        //推送新票池记录表
        poolLogService.pushChangeToPool(ConfigureConstant.POOL_SJLX_JXFP_1, uuids, ConfigureConstant.POOL_BGLX_SJBG_1);

        if (flg) {
            DynamicContextHolder.push(db + DbConstant.BUSINESS_WRITE);
            tDxHttpLog.setStatus("2");
            tDxHttpLog.setTotal(total);
            tDxHttpLogDao.updateHttoLogById(tDxHttpLog);
        } else {
            tDxHttpLog.setStatus("1");
            tDxHttpLog.setTotal(total);
            DynamicContextHolder.push(db + DbConstant.BUSINESS_WRITE);
            tDxHttpLogDao.updateHttoLogById(tDxHttpLog);
        }
        if (logList.size() > 0) {
            invoiceLogService.toInvoiceLog(logList);
        }
    }

    /**
    * @Description TODO
    * @param recordInvoices 组装的数据
    * @param invoice        底账查出来的数据
    * @param db
    * @param detailList
    * @param jxXxtype    进项销项类型   01进项票   02销项票
     * @Return void
    * @Author wangruwei
    * @Date 2024/4/11 10:21
    **/
    private void insertInvoice(TDxRecordInvoice recordInvoices, TDxRecordInvoice invoice, String db,
                               List<InvoiceDetailInfo> detailList, String jxXxtype) {
        //底账主信息新增或修改
        recordInvoiceBaseInfo(recordInvoices,invoice,jxXxtype);

        //特殊票种，扩展信息处理。票的新增修改都是全删，然后入库
        dealTspzKzxx(recordInvoices,detailList);

        //电子源文件处理。保存
        dealSourceFile(recordInvoices,jxXxtype);

        tDxRecordInvoiceStatisticsDao.delStatistics(recordInvoices.getInvoiceCode(), recordInvoices.getInvoiceNo());
        // 税率统计表插入
        tDxRecordInvoiceStatisticsService.countTaxRate(detailList, recordInvoices.getInvoiceCode(),
                recordInvoices.getInvoiceNo());
    }

    /**
     * @Description 底账表 具体解析入库方法
     * @param recordInvoices 组建的底账实体
     * @param invoice  数据库查出来的实体
     * @param jxXxtype   01进项   02销项
     * @Return void
     * @Author wangruwei
     * @Date 2024/4/10 14:29
     **/
    private void recordInvoiceBaseInfo(TDxRecordInvoice recordInvoices, TDxRecordInvoice invoice, String jxXxtype) {
        // 判断底账是否存在 存在更新 不存在保存
        if (invoice == null) {
            if (!"0".equals(recordInvoices.getInvoiceStatus())) {
                recordInvoices.setStatusUpdateDate(new Date());
            }
            // 第一次插入添加票池采集字段
            recordInvoices.setCollectStatus("1");
            recordInvoices.setCollectFrom(recordInvoices.getCollectFrom());
            recordInvoices.setCollectDate(new Date());
            recordInvoices.setPoolStatus("0");
            recordInvoices.setCreateDate(new Date());
            recordInvoices.setCheckDate(new Date());
            if ("01".equals(jxXxtype)) {
                tDxRecordInvoiceJobDao.insert(recordInvoices);
            }
            if ("02".equals(jxXxtype)) {
                // todo 增加开票人
                recordInvoices.setPrintor(recordInvoices.getInvoicer());
                TDxSaleRecordInvoiceJobEntity tsri = new TDxSaleRecordInvoiceJobEntity();
                BeanUtils.copyProperties(recordInvoices, tsri);
                tDxSaleRecordInvoiceJobDao.insert(tsri);
            }
            //2024年4月11日10:31:26 原先
            //tDxRecordInvoiceJobDao.insert(recordInvoices);
        } else {
            if (!invoice.getInvoiceStatus().equals(recordInvoices.getInvoiceStatus())) {
                recordInvoices.setStatusUpdateDate(new Date());
            }
            if ("1".equals(invoice.getSourceSystem()) && "0".equals(invoice.getCollectStatus())) {
                recordInvoices.setCollectStatus("1");
                recordInvoices.setCollectFrom(recordInvoices.getCollectFrom());
                recordInvoices.setCollectDate(new Date());
                recordInvoices.setPoolStatus("1");
                recordInvoices.setInPoolReason("数据重复");
            }
            log.info("采集时，如果抵账库有，authStatus状态是 2已确认，3已发送认证，5认证失败，不更新rzh_yesorno,rzlx,bdk_status,cxbdk_status字段");
            String authStatus = invoice.getAuthStatus();
            if("2".equals(authStatus)||"3".equals(authStatus)||"5".equals(authStatus)){
                recordInvoices.setRzhYesorno(null);
                recordInvoices.setRzlx(null);
                recordInvoices.setBdkStatus(null);
                recordInvoices.setCxbdkStatus(null);
            }
            if ("01".equals(jxXxtype)) {
                tDxRecordInvoiceJobDao.updateRecordInvoice(recordInvoices);
            }
            if ("02".equals(jxXxtype)) {
//                tDxRecordInvoiceJobDao.updateSaleInvoice(recordInvoices,recordInvoices.getGfTaxNo());

                TDxSaleRecordInvoiceJobEntity tsri = new TDxSaleRecordInvoiceJobEntity();
                BeanUtils.copyProperties(recordInvoices, tsri);
                tDxSaleRecordInvoiceJobDao.update(tsri, new UpdateWrapper<TDxSaleRecordInvoiceJobEntity>().eq("uuid", invoice.getUuid()));
            }
            //2024年4月11日10:31:26 原先
            //tDxRecordInvoiceJobDao.updateRecordInvoice(recordInvoices);
        }
    }

    /**
    * @Description 电子源文件的下载保存处理
    * @param recordInvoice  底账表查的实体
    * @param jxXxtype    进项销项类型   01进项票   02销项票
     * @Return void
    * @Author wangruwei
    * @Date 2024/4/9 15:50
    **/
    private void dealSourceFile(TDxRecordInvoice recordInvoice, String jxXxtype) {
        if(!CollectionUtils.isEmpty(recordInvoice.getFileList())){
            log.info("电子源文件处理。保存");
            for (int i = 0; i < recordInvoice.getFileList().size(); i++) {
                TDxRecordInvoiceFileModel item = recordInvoice.getFileList().get(i);
                try {
                    TDxRecordInvoice dbRecordInvoice = new TDxRecordInvoice();
                    if("01".equals(jxXxtype)){
                        dbRecordInvoice = tDxRecordInvoiceJobDao.selectOne(new LambdaQueryWrapper<TDxRecordInvoice>().eq(TDxRecordInvoice::getUuid, recordInvoice.getUuid()));
                    }
                    if("02".equals(jxXxtype)){
                        TDxSaleRecordInvoiceJobEntity tDxSaleRecordInvoiceJobEntity = tDxSaleRecordInvoiceJobDao.selectOne(new LambdaQueryWrapper<TDxSaleRecordInvoiceJobEntity>().eq(TDxSaleRecordInvoiceJobEntity::getUuid, recordInvoice.getUuid()));
                        BeanUtils.copyProperties(tDxSaleRecordInvoiceJobEntity, dbRecordInvoice);
                    }
                    if("xml".equals(item.getFileType())){
                        tdxInvoiceFileService.dealXmlSource(dbRecordInvoice, item.getFileUrl(),jxXxtype);
                    }
                    if("pdf".equals(item.getFileType())){
                        tdxInvoiceFileService.dealPdfSource(dbRecordInvoice, item.getFileUrl(),jxXxtype);
                    }
                    if("ofd".equals(item.getFileType())){
                        tdxInvoiceFileService.dealOfdSource(dbRecordInvoice, item.getFileUrl(),jxXxtype);
                    }
                } catch (Exception e) {
                    log.info("处理电子源文件保存出错。类型:{}。错误信息:{}",item.getFileType(),e);
                }
            }
        }
    }

    /**
    * @Description 进销项票通用----特殊票种，扩展信息处理。票的新增修改都是全删，然后入库。
    * @Author wangruwei
    * @param recordInvoice    组装的主数据
    * @param detailList       组装的明细数据
    * @Date 2024/4/9 15:07
    **/
    private void dealTspzKzxx(TDxRecordInvoice recordInvoice, List<InvoiceDetailInfo> detailList) {

        if(!CollectionUtils.isEmpty(recordInvoice.getInvoiceExt())||!CollectionUtils.isEmpty(recordInvoice.getDetailExt())){
            //开始转化特定要素为统一结构
            TdysZxxMxDto tdysZxxMxDto = CommonUtil.formatTdysJxtyJsonByDqy(recordInvoice, detailList);

            log.info("删除tdxRecordTspzKzxx信息，重新插入返回的数据");
            tdxRecordTspzKzxxDao.delete(new LambdaQueryWrapper<TdxRecordTspzKzxxEntity>().eq(TdxRecordTspzKzxxEntity::getUuid, recordInvoice.getUuid()));

            TdxRecordTspzKzxxEntity insert = new TdxRecordTspzKzxxEntity();
            insert.setUuid(recordInvoice.getUuid());
            if(StringUtils.isNotBlank(tdysZxxMxDto.getZxx())){
                insert.setKzZxx(tdysZxxMxDto.getZxx());
            }
            if(StringUtils.isNotBlank(tdysZxxMxDto.getMx())){
                insert.setKzMxxx(tdysZxxMxDto.getMx());
            }
            insert.setCreateTime(new Date());
            tdxRecordTspzKzxxDao.insert(insert);
        }

    }

    private TDxRecordInvoice insertDetail(List<InvoiceDetailInfo> detailList,
                                          TDxRecordInvoice recordInvoices, String db) {
//        String invoiceCode = recordInvoices.getInvoiceCode();
//        String invoiceNo = recordInvoices.getInvoiceNo();
        String uuid = recordInvoices.getUuid();
        if (detailList != null && detailList.size() > 0) {
            for (InvoiceDetailInfo invoiceDetailInfo : detailList) {
                invoiceDetailInfo.setUuid(uuid);
                invoiceDetailInfo.setInvoiceCode(recordInvoices.getInvoiceCode());
                invoiceDetailInfo.setInvoiceNo(recordInvoices.getInvoiceNo());
                invoiceDetailInfo.setModel(invoiceDetailInfo.getSpecificationModel());
                invoiceDetailInfo.setSpecificationModel(null);
                invoiceDetailInfo.setTaxCodeName(null);
                invoiceDetailInfo.setTaxRate(CommonUtil.processTaxRate(invoiceDetailInfo.getTaxRate()));
            }
            DynamicContextHolder.push(db + DbConstant.DETAIL_WRITE);
            tDxRecordInvoiceDetailDao.delDetail(uuid);
            tDxRecordInvoiceDetailJobService.saveBatch(detailList);
            DynamicContextHolder.push(db + DbConstant.DETAIL_READ);
            int countDetail = tDxRecordInvoiceDetailDao.getDetailCount(uuid);
            if (countDetail > 0) {
                recordInvoices.setDetailYesorno("1");
            } else {
                recordInvoices.setDetailYesorno("0");
            }

        }
        return recordInvoices;
    }

    /**
     * 判断发票是否已经存在， 存在则更新发票数据， 不存在返回false -进项
     *
     * @param invoiceInfo
     * @return
     */
    @Override
    public boolean isExistInvoice(TDxRecordInvoice invoiceInfo, String db, String sourceSystem) {

        // 通过发票号码和发票代码去数据库对比
        String invoiceCode = invoiceInfo.getInvoiceCode();
        String invoiceNo = invoiceInfo.getInvoiceNo();
        DynamicContextHolder.push(db + DbConstant.BUSINESS_READ);
        TDxRecordInvoice invoice = tDxRecordInvoiceJobDao.findInvoiceByCodeAndNo(invoiceCode, invoiceNo);

        if (null != invoice) {

            if(StringUtils.isNotBlank(invoiceInfo.getGlzt())){
                invoice.setGlzt(invoiceInfo.getGlzt());
            }

            if(StringUtils.isNotBlank(invoiceInfo.getInvoiceSource())){
                invoice.setInvoiceSource(invoiceInfo.getInvoiceSource());
            }

            if (!invoice.getInvoiceStatus().equals(invoiceInfo.getInvoiceStatus())) {
                invoice.setInvoiceStatus(invoiceInfo.getInvoiceStatus());
                invoice.setStatusUpdateDate(new Date());
                //如果发票状态是 80-红字发票待确认
                if(FpztEnum.HZDQR.getFpztDm().equals(invoiceInfo.getInvoiceStatus())){
                    invoice.setLqHzsdbs("Y");
                }
            }
            if ("0".equals(invoice.getRzhYesorno()) && !invoice.getRzhYesorno().equals(invoiceInfo.getRzhYesorno())) {
                if ("1".equals(invoiceInfo.getRzlx())) {
                    invoice.setRzhYesorno(invoiceInfo.getRzhYesorno());
                    invoice.setRzhBelongDate(invoiceInfo.getRzhBelongDate());
                    invoice.setRzlx(invoiceInfo.getRzlx());
                    invoice.setRzhType(invoiceInfo.getRzhType());
                    invoice.setSfygx("1");
                    if (invoiceInfo.getRzhDate() != null) {
                        invoice.setRzhDate(invoiceInfo.getRzhDate());
                    }
                    if ("1".equals(invoiceInfo.getRzhYesorno())) {
                        invoice.setAuthStatus("4");
                    } else {
                        invoice.setAuthStatus("0");
                    }
                    invoice.setBdkStatus("1");
                } else if ("4".equals(invoiceInfo.getRzlx())) {
                    invoice.setRzhYesorno("2");
                    invoice.setRzhBelongDate(invoiceInfo.getRzhBelongDate());
                    invoice.setRzlx(invoiceInfo.getRzlx());
                    invoice.setRzhType(invoiceInfo.getRzhType());
                    invoice.setSfygx("1");
                    if (invoiceInfo.getRzhDate() != null) {
                        invoice.setRzhDate(invoiceInfo.getRzhDate());
                    }
                    if ("2".equals(invoiceInfo.getRzhYesorno())) {
                        invoice.setAuthStatus("4");
                    } else {
                        invoice.setAuthStatus("0");
                    }
                    invoice.setBdkStatus("2");
                }
            } else if (!"0".equals(invoice.getRzhYesorno()) && !"1".equals(invoiceInfo.getRzhYesorno())
                    && !"2".equals(invoiceInfo.getRzhYesorno())) {
                invoice.setRzhYesorno("0");
                invoice.setRzhBelongDate(null);
                invoice.setRzlx("0");
                invoice.setRzhType(null);
                invoice.setRzhDate(null);
                invoice.setAuthStatus("0");
                invoice.setBdkStatus("0");
                invoice.setSfygx("0");
            }
            if ("1".equals(invoice.getSourceSystem()) && "0".equals(invoice.getCollectStatus())) {
                invoice.setCollectStatus("1");
                invoice.setCollectFrom(sourceSystem);
                invoice.setCollectDate(new Date());
                invoice.setPoolStatus("1");
                invoice.setInPoolReason("数据重复");
            }

            DynamicContextHolder.push(db + DbConstant.BUSINESS_WRITE);
            tDxRecordInvoiceJobDao.updateInvoice(invoice, invoiceInfo.getGfTaxNo());
            return true;
        } else {
            return false;
        }

    }

    @Override
    public List<TAcOrg> getTaxnoForQpm() {
        DynamicContextHolder.push(DbConstant.BASICS_READ);
        return coreConfirmDao.getTaxnoForQpm();
    }

    /**
     * 判断发票是否已经存在， 存在则更新发票数据， 不存在返回false -数据平台 销项
     *
     * @param invoiceInfo
     * @return
     */
    @Override
    public boolean isExistSaleInvoice(TDxSaleRecordInvoiceJobEntity invoiceInfo, String db, String sourceSystem) {

        // 通过发票号码和发票代码去数据库对比
        String invoiceCode = invoiceInfo.getInvoiceCode();
        String invoiceNo = invoiceInfo.getInvoiceNo();
        DynamicContextHolder.push(db + DbConstant.BUSINESS_READ);
        TDxRecordInvoice invoice = tDxRecordInvoiceJobDao.findSaleInvoiceByCodeAndNo(invoiceCode, invoiceNo);
        if (null != invoice) {

            if(StringUtils.isNotBlank(invoiceInfo.getInvoiceSource())){
                invoice.setInvoiceSource(invoiceInfo.getInvoiceSource());
            }

            if(StringUtils.isNotBlank(invoiceInfo.getGlzt())){
                invoice.setGlzt(invoiceInfo.getGlzt());
            }

            if (!invoice.getInvoiceStatus().equals(invoiceInfo.getInvoiceStatus())) {
                invoice.setInvoiceStatus(invoiceInfo.getInvoiceStatus());
                invoice.setStatusUpdateDate(new Date());
                //如果发票状态是 80-红字发票待确认
                if(FpztEnum.HZDQR.getFpztDm().equals(invoiceInfo.getInvoiceStatus())){
                    invoice.setLqHzsdbs("Y");
                }
            }
            if ("0".equals(invoice.getRzhYesorno()) && !invoice.getRzhYesorno().equals(invoiceInfo.getRzhYesorno())) {
                if ("1".equals(invoiceInfo.getRzlx())) {
                    invoice.setRzhYesorno(invoiceInfo.getRzhYesorno());
                    invoice.setRzhBelongDate(invoiceInfo.getRzhBelongDate());
                    invoice.setRzlx(invoiceInfo.getRzlx());
                    invoice.setRzhType(invoiceInfo.getRzhType());
                    invoice.setSfygx("1");
                    if (invoiceInfo.getRzhDate() != null) {
                        invoice.setRzhDate(invoiceInfo.getRzhDate());
                    }
                    if ("1".equals(invoiceInfo.getRzhYesorno())) {
                        invoice.setAuthStatus("4");
                    } else {
                        invoice.setAuthStatus("0");
                    }
                    invoice.setBdkStatus("1");
                } else if ("4".equals(invoiceInfo.getRzlx())) {
                    invoice.setRzhYesorno("2");
                    invoice.setRzhBelongDate(invoiceInfo.getRzhBelongDate());
                    invoice.setRzlx(invoiceInfo.getRzlx());
                    invoice.setRzhType(invoiceInfo.getRzhType());
                    invoice.setSfygx("1");
                    if (invoiceInfo.getRzhDate() != null) {
                        invoice.setRzhDate(invoiceInfo.getRzhDate());
                    }
                    if ("2".equals(invoiceInfo.getRzhYesorno())) {
                        invoice.setAuthStatus("4");
                    } else {
                        invoice.setAuthStatus("0");
                    }
                    invoice.setBdkStatus("2");
                }
            } else if (!"0".equals(invoice.getRzhYesorno()) && !"1".equals(invoiceInfo.getRzhYesorno())
                    && !"2".equals(invoiceInfo.getRzhYesorno())) {
                invoice.setRzhYesorno("0");
                invoice.setRzhBelongDate(null);
                invoice.setRzlx("0");
                invoice.setRzhType(null);
                invoice.setRzhDate(null);
                invoice.setAuthStatus("0");
                invoice.setBdkStatus("0");
                invoice.setSfygx("0");
            }
            if ("1".equals(invoice.getSourceSystem()) && "0".equals(invoice.getCollectStatus())) {
                invoice.setCollectStatus("1");
                invoice.setCollectFrom(sourceSystem);
                invoice.setCollectDate(new Date());
                invoice.setPoolStatus("1");
                invoice.setInPoolReason("数据重复");
            }
            DynamicContextHolder.push(db + DbConstant.BUSINESS_WRITE);
            tDxRecordInvoiceJobDao.updateSaleInvoice(invoice, invoiceInfo.getGfTaxNo());
            return true;
        } else {
            return false;
        }

    }

    @Override
    public List<TAcOrg> getTaxnoForDown() {
        DynamicContextHolder.push(DbConstant.BASICS_READ);
        return coreConfirmDao.getTaxnoForDown();
    }


    /**
     * @description  数电票源文件获取
     * @author  Allen
     * @date    2023/8/15 17:33
     * @param
     * @param jxxxType   01进项  02销项
     * @return
    */
    @Override
    public void getSdpYwj(String taxno, String db, String aceId, String aceKey, String company, String jxxxType) {
        log.info("数电票源文件获取...taxNo:{}", taxno);
        DynamicContextHolder.push(db + DbConstant.BUSINESS_READ);
        try {
            //查询抵账表所有未获取源文件的31.32.161.283.383,184发票
            List<TDxRecordInvoice> tdriList = new LinkedList<>();
            if("01".equals(jxxxType)){
                tdriList = tDxRecordInvoiceJobDao.selectNoFileSdfp(taxno);
            }
            else if("02".equals(jxxxType)){
                tdriList = tDxRecordInvoiceJobDao.selectNoFileSdfpXx(taxno);
            }

            //要推送票池的uuid集合
            List<String> uuids = new LinkedList();
            for (TDxRecordInvoice tri: tdriList) {
                log.info("-封装参数-");
                Map<String, String> map = new HashMap<>();
                if("01".equals(jxxxType)){
                    map.put("buyerTaxNo",tri.getGfTaxNo());
                }else if("02".equals(jxxxType)){
                    map.put("buyerTaxNo",tri.getXfTaxNo());
                }

                boolean isHaveFile = false;
                map.put("electronicInvoiceNo",tri.getEleInvoiceNo());
                BaseResJson gatherData = Dqyjkdyutil.call(new HashMap<>(), CoreConstants.sourceFileGet,aceId,aceKey,map);
                if (gatherData != null && gatherData.getReturnStateInfo() != null && gatherData.getReturnStateInfo().getReturnCode().equals(ConfigureConstant.SECCESS_CODE)) {
                    if (StringUtils.isNotBlank(gatherData.getData())) {
                        log.info("-大企业接口返回成功，处理数据-");
                        Map<String,String> respMap = JsonUtils.getInstance().fromJson(Base64Encoding.decodeToString(gatherData.getData()), Map.class);
                        //获取xml文件
                        if (StringUtils.isNotBlank(respMap.get("xmlUrl"))) {
                            tdxInvoiceFileService.dealXmlSource(tri,respMap.get("xmlUrl"), jxxxType);
                            isHaveFile = true;
                        }
                        if (StringUtils.isNotBlank(respMap.get("pdfUrl"))) {
                            tdxInvoiceFileService.dealPdfSource(tri,respMap.get("pdfUrl"), jxxxType);
                            isHaveFile = true;
                        }
                        if (StringUtils.isNotBlank(respMap.get("ofdUrl"))) {
                            tdxInvoiceFileService.dealOfdSource(tri,respMap.get("ofdUrl"), jxxxType);
                            isHaveFile = true;
                        }
                    }
                }
                if("01".equals(jxxxType)&&isHaveFile){
                    uuids.add(tri.getUuid());
                }
            }
            //推送新票池记录表
            poolLogService.pushChangeToPool(ConfigureConstant.POOL_SJLX_JXFP_1, uuids, ConfigureConstant.POOL_BGLX_YWJBG_3);
        } catch (Exception e) {
            log.debug("数电源文件获取任务处理异常：{}",e);
        }
    }

    /**
    * @Description 处理成拥有的源文件标志
    * @param xmlFlag  123
    * @param s
    * @Return java.lang.String
    * @Author wangruwei
    * @Date 2024/4/2 15:04
    **/
    private String updateXmlFlag(String xmlFlag, String s) {
        if(xmlFlag.contains(s)){
            return xmlFlag;
        }else{
            List<String> list = new LinkedList(Arrays.asList(xmlFlag.split("")));
            list.add(s);
            List<String> collect = list.stream().sorted().collect(Collectors.toList());
            return String.join("", collect);
        }
    }

    public static void main(String[] args) {
        String xmlFlag = "13";
        String s = "2";
        List<String> list = new LinkedList(Arrays.asList(xmlFlag.split("")));
        list.add(s);
        List<String> collect = list.stream().sorted().collect(Collectors.toList());
        System.out.println(String.join("", collect));
    }

    /**
     * @description  增值税发票采集
     * @author  Allen
     * @date    2023/8/15 17:33
     * @param type 1-进项数据 2-销项数据
     * @return
     */
    @Override
    public void zzsfpcj(CollectionControlModel ccm, String type) {
        log.info("增值税发票采集...企业信息:{}", JsonUtils.getInstance().toJsonString(ccm));
        DynamicContextHolder.push(ccm.getDbName() + DbConstant.BUSINESS_READ);
        try {
            Map<String, Object> httpLogMap = new HashMap<>();
            List<String> pzList = new ArrayList<>();
            pzList.add("01");
            pzList.add("03");
            pzList.add("04");
            pzList.add("08");
            pzList.add("10");
            pzList.add("11");
            pzList.add("14");
            pzList.add("15");
            pzList.add("17");
            pzList.add("31");
            pzList.add("32");
            pzList.add("161");
            pzList.add("183");
            pzList.add("185");
            pzList.add("186");
            pzList.add("187");
            pzList.add("188");
            pzList.add("283");

            pzList.add("383");
            pzList.add("184");

            log.info("支持票种：{}",pzList);

            for (String invoiceTyp : pzList) {
                log.info("当前采集票种:{}", invoiceTyp);
                int totalRow = 0;
                int addRow = 0;
                //组装请求数据
                // 随机生成32位批次号
                String batchNo = Dqyjkdyutil.getBatchNo();
                ZzsfpcjRequestData zzsrd = new ZzsfpcjRequestData();
                zzsrd.setTaxno(ccm.getNsrsbh());
                zzsrd.setDataType(type);
                zzsrd.setInvoiceType(invoiceTyp);
                zzsrd.setBatchNo(batchNo);
                zzsrd.setStartRow(1);
                String jxxType = "";
                if("1".equals(type)){
                    jxxType = "01";
                }
                if("2".equals(type)){
                    jxxType = "02";
                }
                zzsrd.setAcquisitionDateBegin(getBeginTimeGj(ccm, jxxType, invoiceTyp));
                zzsrd.setAcquisitionDateEnd(Dqyjkdyutil.getEndTime());

                DynamicContextHolder.push(ccm.getDbName() + DbConstant.BUSINESS_WRITE);
                while (true) {
                    TDxHttpLogZzsfpgjEntity thlzf = new TDxHttpLogZzsfpgjEntity();
                    //调用大企业接口
                    BaseResJson gatherData = Dqyjkdyutil.call(httpLogMap, CoreConstants.taxInvoiceGet, ccm.getAceId(), ccm.getAcekey(), zzsrd);

                    if (gatherData != null && gatherData.getReturnStateInfo() != null && gatherData.getReturnStateInfo().getReturnCode().equals(ConfigureConstant.SECCESS_CODE)) {
                        if (StringUtils.isNotBlank(gatherData.getData())) {
                            JSONObject jsonObject = JSON.parseObject(Base64Encoding.decodeToString(gatherData.getData()));
                            if (jsonObject.getJSONArray("invoices") != null && jsonObject.getJSONArray("invoices").size() > 0) {
                                //保存增值税发票归集记录表
                                log.info("保存大企业增值税发票归集记录表");
                                thlzf.setCompany(ccm.getCompany());
                                thlzf.setBatchNo(batchNo);
                                if("1".equals(type)){
                                    thlzf.setType("01");
                                }
                                if("2".equals(type)){
                                    thlzf.setType("02");
                                }

                                thlzf.setTaxno(ccm.getNsrsbh());
                                thlzf.setInvoiceType(invoiceTyp);
                                thlzf.setStatus("0");
                                thlzf.setReqDate((Date) httpLogMap.get(CoreConstants.reqDate));
                                thlzf.setReqText((String) httpLogMap.get(CoreConstants.reqText));
                                thlzf.setResDate((Date) httpLogMap.get(CoreConstants.resDate));
                                thlzf.setResText((String) httpLogMap.get(CoreConstants.resText));
                                thlzf.setTotal(String.valueOf(jsonObject.getIntValue("contentRows")));
                                tDxHttpZzsfpgjDao.insert(thlzf);
                                log.info("在获取到结果时候立马走解析");
                                parseSingleHttpLogZzsfpgj(thlzf, ccm.getDbName());
                                totalRow = jsonObject.getIntValue("totalRows");
                                addRow += jsonObject.getIntValue("contentRows");
                            } else {
                                log.info("大企业接口返回发票数据节点为空：{}",JsonUtils.getInstance().toJsonString(gatherData));
                                break;
                            }
                            if (addRow < totalRow) {
                                zzsrd.setStartRow(addRow);
                            } else {
                                log.info("大企业接口当前批次调用完成");
                                break;
                            }
                        } else {
                            log.info("大企业接口返回data节点为空：{}",JsonUtils.getInstance().toJsonString(gatherData));
                            break;
                        }
                    } else {
                        log.info("大企业接口返回失败：{}",JsonUtils.getInstance().toJsonString(gatherData));
                        break;
                    }
                }
                log.info("---当前票种处理完成---");
            }
            log.info("---当前税号处理完成---");

        } catch (Exception e) {
            log.debug("增值税发票采集任务处理异常：{}",e);
        }
    }


    /**
     * 获取开始时间
     *
     * @return
     */
    private String getBeginTime(CollectionControlModel ccm, String type,String invoiceType) {
        DynamicContextHolder.push(ccm.getDbName() + DbConstant.BUSINESS_WRITE);
        //查询增值税发票归集上次请求时间
        String lastTime = tDxRecordInvoiceJobDao.selectZzsfpgjLastreqDate(ccm.getNsrsbh(), type,invoiceType);
        return Dqyjkdyutil.getBeginTime(lastTime, ccm.getFirstCollectDate());
    }


    /**
     * 获取开始时间--针对归集。获取到操作时间的前60天
     *
     * @return
     */
    private String getBeginTimeGj(CollectionControlModel ccm, String type,String invoiceType) {
        DynamicContextHolder.push(ccm.getDbName() + DbConstant.BUSINESS_WRITE);
        //查询增值税发票归集上次请求时间
        String lastTime = tDxRecordInvoiceJobDao.selectZzsfpgjLastreqDate(ccm.getNsrsbh(), type,invoiceType);
        return Dqyjkdyutil.getBeginTimeGj(lastTime, ccm.getFirstCollectDate());
    }


    /**
    * @Description TODO
    * @param type   01 进项增值税发票归集 02 销项增值税发票归集
    * @param taxno
    * @param dbName
    * @param aceId
    * @param aceKey
    * @param company
    * @Return void
    * @Author wangruwei
    * @Date 2024/4/10 17:36
    **/
    @Override
    public void zzsfpcjjggj(String type, String taxno, String dbName, String aceId, String aceKey, String company) {
        try {
            log.info("增值税发票归集结果解析...taxNo:{}", taxno);
            DynamicContextHolder.push(dbName + DbConstant.BUSINESS_READ);
            List<TDxHttpLogZzsfpgjEntity> zzsfpgjLogList = tDxHttpZzsfpgjDao.selectList(new QueryWrapper<TDxHttpLogZzsfpgjEntity>()
                    .eq("taxno", taxno)
                    .eq("type", type)
                    .in("status", 0,2));
            for (TDxHttpLogZzsfpgjEntity zzsfpgjlog : zzsfpgjLogList) {
                log.info("解析开始，税号：{}，批次号：{}", taxno, zzsfpgjlog.getBatchNo());
                parseSingleHttpLogZzsfpgj(zzsfpgjlog,dbName);
            }
        } catch (Exception e) {
            log.debug("数据处理异常：{}",e);
        }
    }
    /**
    * @Description 抽取归集发票后的解析方法
    * @param zzsfpgjlog
    * @param dbName
    * @Return void
    * @Author wangruwei
    * @Date 2024/12/25 10:02
    **/
    private void parseSingleHttpLogZzsfpgj(TDxHttpLogZzsfpgjEntity zzsfpgjlog, String dbName) {
        if (StringUtils.isNotBlank(zzsfpgjlog.getResText())) {
            BaseResJson baseResJson = JsonUtils.getInstance().fromJson(zzsfpgjlog.getResText(), BaseResJson.class);

            List<String> pzList = new ArrayList<>();
            pzList.add("01");
            pzList.add("04");
            pzList.add("08");
            pzList.add("10");
            pzList.add("11");
            pzList.add("14");
            pzList.add("31");
            pzList.add("32");
            pzList.add("183");
            pzList.add("185");
            pzList.add("186");
            if (pzList.contains(zzsfpgjlog.getInvoiceType())) {
                //专、普、电、卷、全电发票解析
                List<InvoiceInfo> invoice = JsonUtils.getInstance().jsonToList(JSON.parseObject(Base64Encoding.decodeToString(baseResJson.getData())).getString("invoices"), InvoiceInfo.class);
                String invoiceSource = "0";
                if ("31".equals(zzsfpgjlog.getInvoiceType())||"32".equals(zzsfpgjlog.getInvoiceType())
                        ||"185".equals(zzsfpgjlog.getInvoiceType())||"186".equals(zzsfpgjlog.getInvoiceType())
                ) {
                    invoiceSource = "1";
                }
                processZzsInvoice(dbName,invoiceSource,zzsfpgjlog,invoice);
            }

            if ("03".equals(zzsfpgjlog.getInvoiceType())||"187".equals(zzsfpgjlog.getInvoiceType())||"383".equals(zzsfpgjlog.getInvoiceType())) {
                //机动车销售电子统一发票解析
                List<VehicleSaleInvoiceInfos> vehicleInovices = JsonUtils.getInstance().jsonToList(JSON.parseObject(Base64Encoding.decodeToString(baseResJson.getData())).getString("invoices"), VehicleSaleInvoiceInfos.class);
                String invoiceSource = "0";
                if ("187".equals(zzsfpgjlog.getInvoiceType())||"383".equals(zzsfpgjlog.getInvoiceType())
                ) {
                    invoiceSource = "1";
                }
                processJdcxsInvoice(dbName, invoiceSource,zzsfpgjlog, vehicleInovices);
            }

            if ("15".equals(zzsfpgjlog.getInvoiceType())||"188".equals(zzsfpgjlog.getInvoiceType())||"184".equals(zzsfpgjlog.getInvoiceType())) {
                //二手车解析
                String invoiceSource = "0";
                if ("188".equals(zzsfpgjlog.getInvoiceType())||"184".equals(zzsfpgjlog.getInvoiceType())
                ) {
                    invoiceSource = "1";
                }
                List<UsedcarInvoiceModel> escInovices = JsonUtils.getInstance().jsonToList(JSON.parseObject(Base64Encoding.decodeToString(baseResJson.getData())).getString("invoices"), UsedcarInvoiceModel.class);
                processEscInvoice(dbName, invoiceSource,zzsfpgjlog, escInovices);
            }

            if("161".equals(zzsfpgjlog.getInvoiceType())){
                //数电票（航空运输电子客票行程单）
                List<InvoiceMhxcdInfo> hkyhsKpInvoices = JsonUtils.getInstance().jsonToList(JSON.parseObject(Base64Encoding.decodeToString(baseResJson.getData())).getString("invoices"), InvoiceMhxcdInfo.class);
                processHkysKpInvoice(dbName,zzsfpgjlog,hkyhsKpInvoices);
            }


            if("283".equals(zzsfpgjlog.getInvoiceType())){
                //数电票（铁路电子客票）
                List<InvoiceTlkpInfo> tlkpInvoices = JsonUtils.getInstance().jsonToList(JSON.parseObject(Base64Encoding.decodeToString(baseResJson.getData())).getString("invoices"), InvoiceTlkpInfo.class);
                processTlkpInvoice(dbName,zzsfpgjlog,tlkpInvoices);
            }

        }
    }

    /**
     * @Description 数电票源文件获取--全地区支持
     * @param taxno
     * @param db
     * @param aceId
     * @param aceKey
     * @param company
     * @param jxxxType
     * @Return void
     * @Author wangruwei
     * @Date 2024/8/6 9:39
     **/
    @Override
    public void getSdpYwjNew(String taxno, String db, String aceId, String aceKey, String company, String jxxxType) {
        log.info("数电票源文件获取...taxNo:{}", taxno);
        DynamicContextHolder.push(db + DbConstant.BUSINESS_READ);
        try {
            //查询抵账表所有未获取源文件的31.32.161.283.383,184发票
            List<TDxRecordInvoice> tdriList = new LinkedList<>();
            if("01".equals(jxxxType)){
                tdriList = tDxRecordInvoiceJobDao.selectNoFileSdfp(taxno);
            }
            else if("02".equals(jxxxType)){
                tdriList = tDxRecordInvoiceJobDao.selectNoFileSdfpXx(taxno);
            }
            //要推送票池的uuid集合
            List<String> uuids = new LinkedList();
            for (TDxRecordInvoice tri: tdriList) {
                log.info("-封装参数-");
                Map<String, String> map = new HashMap<>();
                map.put("batchNo",UUID.randomUUID().toString().replace("-", ""));
                if("01".equals(jxxxType)){
                    map.put("taxno",tri.getGfTaxNo());
                    map.put("dataType","1");
                }else if("02".equals(jxxxType)){
                    map.put("taxno",tri.getXfTaxNo());
                    map.put("dataType","2");
                }
                map.put("electronicInvoiceNo",tri.getEleInvoiceNo());

                if(StringUtils.isBlank(tri.getEleInvoiceNo())){
                    log.info("数电号码为空，不请求。代码:{}号码:{}票种:{}",tri.getInvoiceCode(),tri.getInvoiceNo(),tri.getInvoiceType());
                    continue;
                }

                map.put("fileType", "xml");
                //调1018新源文件获取接口获取xml
                log.info("处理xml文件获取逻辑");
                boolean xmlDownload = tdxInvoiceFileNewService.dealXmlSource(tri, map , jxxxType,aceId,aceKey);

                map.put("fileType", "pdf");
                //调1018新源文件获取接口获取Pdf
                log.info("处理pdf文件获取逻辑");
                boolean pdfDownload = tdxInvoiceFileNewService.dealPdfSource(tri, map , jxxxType,aceId,aceKey);

                map.put("fileType", "ofd");
                //调1018新源文件获取接口获取Ofd
                log.info("处理ofd文件获取逻辑");
                boolean ofdDownload = tdxInvoiceFileNewService.dealOfdSource(tri, map , jxxxType,aceId,aceKey);

                //推送票池的uuid
                if("01".equals(jxxxType)&&(xmlDownload||pdfDownload||ofdDownload)){
                    uuids.add(tri.getUuid());
                }
            }
            //推送新票池记录表
            poolLogService.pushChangeToPool(ConfigureConstant.POOL_SJLX_JXFP_1, uuids, ConfigureConstant.POOL_BGLX_YWJBG_3);
        } catch (Exception e) {
            log.debug("数电源文件获取任务处理异常：{}",e);
        }
    }

    /**
    * @Description 数电票（航空运输电子客票行程单）
    * @param dbName
    * @param zzsfpgjlog
    * @param hkyhsKpInvoices
    * @Return void
    * @Author wangruwei
    * @Date 2024/4/10 15:42
    **/
    private void processHkysKpInvoice(String dbName, TDxHttpLogZzsfpgjEntity zzsfpgjlog, List<InvoiceMhxcdInfo> hkyhsKpInvoices) {
        log.info("数电票（航空运输电子客票行程单）数据入抵账库---");
        List<InvoiceLog> logList = new ArrayList<>();
        boolean flg = false;
        //要推送票池的uuid集合
        List<String> uuids = new LinkedList();
        for (InvoiceMhxcdInfo invoiceInfo : hkyhsKpInvoices) {
            DynamicContextHolder.push(dbName + DbConstant.BUSINESS_WRITE);
            try {
                // 构建底账表（解析接口返回的信息）
                TDxRecordInvoice recordInvoice = TransitionUtils.getHkysKpInvoiceInfo(invoiceInfo,"4");
                recordInvoice.setInvoiceSource("1");
                recordInvoice.setSourceSystem("4");
                recordInvoice.setCollectFrom("4");
                recordInvoice.setCompany(zzsfpgjlog.getCompany());
                TDxRecordInvoice invoice = null;
                if ("01".equals(zzsfpgjlog.getType())) {
                    invoice = tDxRecordInvoiceJobDao.findInvoiceByCodeAndNo(recordInvoice.getInvoiceCode(), recordInvoice.getInvoiceNo());
                }
                if ("02".equals(zzsfpgjlog.getType())) {
                    invoice = tDxRecordInvoiceJobDao.findSaleInvoiceByCodeAndNo(recordInvoice.getInvoiceCode(), recordInvoice.getInvoiceNo());
                }
                //处理航空运输电子客票信息方法
                this.insertHkysKpInvoice(recordInvoice, invoice, dbName,zzsfpgjlog.getType());
                // 保存发票关联请求日志id
                InvoiceLog invoiceLog = new InvoiceLog();
                invoiceLog.setInputName("系统自动");
                invoiceLog.setInvoiceCode(recordInvoice.getInvoiceCode());
                invoiceLog.setInvoiceNo(recordInvoice.getInvoiceNo());
                invoiceLog.setType("1");
                invoiceLog.setInputStatus("0");
                invoiceLog.setCreateDate(new Date());
                logList.add(invoiceLog);

                if ("01".equals(zzsfpgjlog.getType())) {
                    uuids.add(recordInvoice.getUuid());
                }
            } catch (Exception e) {
                log.info("数电票（航空运输电子客票行程单）解析异常：{}", e);
                flg = true;
                break;
            }
        }
        //推送新票池记录表
        poolLogService.pushChangeToPool(ConfigureConstant.POOL_SJLX_JXFP_1, uuids, ConfigureConstant.POOL_BGLX_SJBG_1);

        if (flg) {
            zzsfpgjlog.setStatus("2");
        } else {
            zzsfpgjlog.setStatus("1");
        }
        DynamicContextHolder.push(dbName + DbConstant.BUSINESS_WRITE);
        tDxHttpZzsfpgjDao.updateById(zzsfpgjlog);
        if (logList.size() > 0) {
            invoiceLogService.toInvoiceLog(logList);
        }
        log.info("数电票（航空运输电子客票行程单）数据入库完成---");
    }

    /**
    * @Description 处理航空运输电子客票信息方法
    * @param recordInvoice 大企业返回后组装的数据
    * @param invoice  底账库查出来的数据
    * @param db
    * @param jxXxtype   01进项    02销项
     * @Return void
    * @Author wangruwei
    * @Date 2024/4/10 16:13
    **/
    private void insertHkysKpInvoice(TDxRecordInvoice recordInvoice, TDxRecordInvoice invoice, String db, String jxXxtype) {
        //删除并重新插入航空运输特定要素表
        TdysHkysKpInsertOrUpdate(recordInvoice);

        //底账主信息新增或修改
        recordInvoiceBaseInfo(recordInvoice,invoice,jxXxtype);

        //电子源文件处理。保存
        dealSourceFile(recordInvoice, jxXxtype);

        log.info("税率统计表是否要处理？明细里没返回金额税额");
        //tDxRecordInvoiceStatisticsDao.delStatistics(recordInvoices.getInvoiceCode(), recordInvoices.getInvoiceNo());
        //// 税率统计表插入
        //tDxRecordInvoiceStatisticsService.countTaxRate(detailList, recordInvoices.getInvoiceCode(),
        //        recordInvoices.getInvoiceNo());
    }
    /**
    * @Description 删除并重新插入航空运输特定要素表
    * @param recordInvoice
    * @Return void
    * @Author wangruwei
    * @Date 2024/4/10 16:28
    **/
    private void TdysHkysKpInsertOrUpdate(TDxRecordInvoice recordInvoice) {
        //特定要素主信息
        TDxRecordInvoiceTdysMhxcd tdysMhxcd = recordInvoice.getTdysMhxcd();
        //特定要素明细信息
        List<TDxRecordInvoiceTdysMhxcdItem> tdysMhxcdDetailList = recordInvoice.getTdysMhxcdDetailList();
        String gngjbz = "";
        String gpdh = "";
        String xm = "";
        String certificateNo = "";
        String eleTicketNo = "";
        if(!CollectionUtils.isEmpty(tdysMhxcdDetailList)){
            gngjbz = tdysMhxcdDetailList.get(0).getInternationalLogo();
            gpdh =  tdysMhxcdDetailList.get(0).getGp();
            xm =  tdysMhxcdDetailList.get(0).getFullName();
            certificateNo = tdysMhxcdDetailList.get(0).getCertificateNo();
            eleTicketNo = tdysMhxcdDetailList.get(0).getEleTicketNo();
        }
        log.info("删除t_dx_tdys_mhxcd表");
        tdxTdysMhxcdCoreDao.delete(new LambdaQueryWrapper<TdxTdysMhxcdEntity>().eq(TdxTdysMhxcdEntity::getUuid, recordInvoice.getUuid()));
        if(ObjectUtil.isNotEmpty(tdysMhxcd)){
            log.info("入库t_dx_tdys_mhxcd表");
            TdxTdysMhxcdEntity mhxcdInsert = new TdxTdysMhxcdEntity();
            mhxcdInsert.setUuid(recordInvoice.getUuid());
            //mhxcdInsert.setGmfjbr();
            mhxcdInsert.setTicketPrice(tdysMhxcd.getTicketPrice());
            mhxcdInsert.setFuelSurcharge(tdysMhxcd.getFuelSurcharge());
            mhxcdInsert.setValueAddedTaxAmount(tdysMhxcd.getValueAddedTaxAmount());
            mhxcdInsert.setVatRate(tdysMhxcd.getVatRate());
            mhxcdInsert.setAviationDevelopmentFund(tdysMhxcd.getAviationDevelopmentFund());
            mhxcdInsert.setOtherTaxes(tdysMhxcd.getOtherTaxes());
            //mhxcdInsert.setJbrsfzjhm();
            //mhxcdInsert.setJbrlxdh();
            //mhxcdInsert.setKprsrrzdzxx();
            //mhxcdInsert.setSjkpdzxx();
            //mhxcdInsert.setHtbh();
            //mhxcdInsert.setNsywfssj();
            //mhxcdInsert.setJbrsfzjzlDm();
            //mhxcdInsert.setSpsl();
            //mhxcdInsert.setSfwzzfp();
            mhxcdInsert.setFphm(recordInvoice.getInvoiceNo());
            mhxcdInsert.setGngjbz(gngjbz);
            mhxcdInsert.setGpdh(gpdh);
            //mhxcdInsert.setSflzfpbz();
            mhxcdInsert.setXm(xm);
            mhxcdInsert.setZjhm(certificateNo);
            mhxcdInsert.setQz(tdysMhxcd.getEndorsement());
            mhxcdInsert.setDzkphm(eleTicketNo);
            mhxcdInsert.setYzm(tdysMhxcd.getVerificationCode());
            mhxcdInsert.setTsxx(tdysMhxcd.getPrompt());
            mhxcdInsert.setBxf(tdysMhxcd.getInsuranceFee());
            mhxcdInsert.setXswddh(tdysMhxcd.getOutletCode());
            mhxcdInsert.setTkdw(tdysMhxcd.getIssuingEntity());
            mhxcdInsert.setKprq(DateUtil.format(recordInvoice.getInvoiceDate(),"yyyyMMdd"));
            mhxcdInsert.setXsfmc(recordInvoice.getXfName());
            mhxcdInsert.setXsfnsrsbh(recordInvoice.getXfTaxNo());
            mhxcdInsert.setGmfmc(recordInvoice.getGfName());
            mhxcdInsert.setGmfnsrsbh(recordInvoice.getGfTaxNo());
            mhxcdInsert.setCreateTime(new Date());
            tdxTdysMhxcdCoreDao.insert(mhxcdInsert);
        }else{
            log.info("没有返回航空对应字段，无需保存t_dx_tdys_mhxcd表");
        }


        log.info("删除t_dx_tdys_mhxcd_mx表");
        tdxTdysMhxcdMxCoreDao.delete(new LambdaQueryWrapper<TdxTdysMhxcdMxEntity>().eq(TdxTdysMhxcdMxEntity::getTdysId, recordInvoice.getUuid()));
        log.info("入库t_dx_tdys_mhxcd_mx表");
        for (int i = 0; i < tdysMhxcdDetailList.size(); i++) {
            TDxRecordInvoiceTdysMhxcdItem item = tdysMhxcdDetailList.get(i);
            TdxTdysMhxcdMxEntity addItem = new TdxTdysMhxcdMxEntity();
            addItem.setTdysId(recordInvoice.getUuid());
            addItem.setSfz(item.getDepartureStation());
            addItem.setMdz(item.getDestination());
            addItem.setHd(item.getLeg());
            addItem.setCyr(item.getCarrier());
            addItem.setHbh(item.getFlightNo());
            addItem.setZwdj(item.getSeatClass());
            addItem.setCyrq(item.getCarrierDate());
            addItem.setQfsj(item.getDepartureTime());
            addItem.setKpjbkplb(item.getTicketType());
            addItem.setKpsxrq(item.getTicketEffectiveDate());
            addItem.setYxjzrq(item.getExpiryDate());
            addItem.setMfxle(item.getBaggageWeight());
            addItem.setCreateTime(new Date());
            tdxTdysMhxcdMxCoreDao.insert(addItem);
        }

        //根据返回的明细设置是detailyesorno
        Long aLong = tdxTdysMhxcdMxCoreDao.selectCount(new LambdaQueryWrapper<TdxTdysMhxcdMxEntity>().eq(TdxTdysMhxcdMxEntity::getTdysId, recordInvoice.getUuid()));
        if(aLong>0){
            recordInvoice.setDetailYesorno("1");
        }else{
            recordInvoice.setDetailYesorno("0");
        }
    }

    /**
    * @Description 数电票（铁路电子客票）解析入库
    * @param dbName
    * @param zzsfpgjlog
    * @param tlkpInvoices   大企业返回的数据实体
    * @Return void
    * @Author wangruwei
    * @Date 2024/4/10 14:09
    **/
    private void processTlkpInvoice(String dbName, TDxHttpLogZzsfpgjEntity zzsfpgjlog, List<InvoiceTlkpInfo> tlkpInvoices) {
        log.info("数电票（铁路电子客票）数据入抵账库---");
        List<InvoiceLog> logList = new ArrayList<>();
        boolean flg = false;
        //要推送票池的uuid集合
        List<String> uuids = new LinkedList();
        for (InvoiceTlkpInfo invoiceInfo : tlkpInvoices) {
            DynamicContextHolder.push(dbName + DbConstant.BUSINESS_WRITE);
            try {
                // 构建底账表（解析接口返回的信息）
                TDxRecordInvoice recordInvoice = TransitionUtils.getTlkpInvoiceInfo(invoiceInfo,"4");
                recordInvoice.setInvoiceSource("1");
                recordInvoice.setSourceSystem("4");
                recordInvoice.setCollectFrom("4");
                recordInvoice.setCompany(zzsfpgjlog.getCompany());
                TDxRecordInvoice invoice = null;
                if ("01".equals(zzsfpgjlog.getType())) {
                    invoice = tDxRecordInvoiceJobDao.findInvoiceByCodeAndNo(recordInvoice.getInvoiceCode(), recordInvoice.getInvoiceNo());
                }
                if ("02".equals(zzsfpgjlog.getType())) {
                    invoice = tDxRecordInvoiceJobDao.findSaleInvoiceByCodeAndNo(recordInvoice.getInvoiceCode(), recordInvoice.getInvoiceNo());
                }
                //处理铁路客票信息方法
                this.insertTlkpInvoice(recordInvoice, invoice, dbName,zzsfpgjlog.getType());
                // 保存发票关联请求日志id
                InvoiceLog invoiceLog = new InvoiceLog();
                invoiceLog.setInputName("系统自动");
                invoiceLog.setInvoiceCode(recordInvoice.getInvoiceCode());
                invoiceLog.setInvoiceNo(recordInvoice.getInvoiceNo());
                invoiceLog.setType("1");
                invoiceLog.setInputStatus("0");
                invoiceLog.setCreateDate(new Date());
                logList.add(invoiceLog);

                if ("01".equals(zzsfpgjlog.getType())) {
                    uuids.add(recordInvoice.getUuid());
                }
            } catch (Exception e) {
                log.info("数电票（铁路电子客票）解析异常：{}", e);
                flg = true;
                break;
            }
        }
        //推送新票池记录表
        poolLogService.pushChangeToPool(ConfigureConstant.POOL_SJLX_JXFP_1, uuids, ConfigureConstant.POOL_BGLX_SJBG_1);

        if (flg) {
            zzsfpgjlog.setStatus("2");
        } else {
            zzsfpgjlog.setStatus("1");
        }
        DynamicContextHolder.push(dbName + DbConstant.BUSINESS_WRITE);
        tDxHttpZzsfpgjDao.updateById(zzsfpgjlog);
        if (logList.size() > 0) {
            invoiceLogService.toInvoiceLog(logList);
        }
        log.info("数电票（铁路电子客票）数据入库完成---");
    }

    /**
    * @Description 铁路客票 具体解析入库方法
    * @param recordInvoice 组建的底账实体
    * @param invoice  数据库查出来的实体
    * @param db
    * @param jxXxtype   01进项   02销项
     * @Return void
    * @Author wangruwei
    * @Date 2024/4/10 14:29
    **/
    private void insertTlkpInvoice(TDxRecordInvoice recordInvoice, TDxRecordInvoice invoice, String db, String jxXxtype) {
        //删除并重新插入铁路特定要素表
        TdysTldzkpInsertOrUpdate(recordInvoice);

        //底账主信息新增或修改
        recordInvoiceBaseInfo(recordInvoice,invoice,jxXxtype);

        //电子源文件处理。保存
        dealSourceFile(recordInvoice, jxXxtype);

        log.info("税率统计表是否要处理？明细里没返回金额税额");
        //tDxRecordInvoiceStatisticsDao.delStatistics(recordInvoices.getInvoiceCode(), recordInvoices.getInvoiceNo());
        //// 税率统计表插入
        //tDxRecordInvoiceStatisticsService.countTaxRate(detailList, recordInvoices.getInvoiceCode(),
        //        recordInvoices.getInvoiceNo());
    }


    /**
     * 删除并重新插入铁路特定要素表
     **/
    private void TdysTldzkpInsertOrUpdate(TDxRecordInvoice recordInvoice) {
        tdxTdysTldzkpCoreDao.delete(new LambdaQueryWrapper<TdxTdysTldzkpEntity>().eq(TdxTdysTldzkpEntity::getUuid, recordInvoice.getUuid()));
        if(!CollectionUtils.isEmpty(recordInvoice.getDetailList())){
            log.info("扩展字段处理。保存t_dx_tdys_tldzkp表");
            InvoiceTlkpInfoItem invoiceTlkpInfoItem = recordInvoice.getDetailList().get(0);
            TdxTdysTldzkpEntity tlkpInsert = new TdxTdysTldzkpEntity();
            tlkpInsert.setUuid(recordInvoice.getUuid());
            //tlkpInsert.setGmfjbr(invoiceTlkpInfoItem.getgm);
            //tlkpInsert.setJbrsfzjhm();
            //tlkpInsert.setJbrlxdh();
            //tlkpInsert.setKprsrrzdzxx();
            //tlkpInsert.setSjkpdzxx();
            //tlkpInsert.setHtbh();
            //tlkpInsert.setNsywfssj();
            //tlkpInsert.setJbrsfzjzlDm();
            //tlkpInsert.setSpsl();
            //tlkpInsert.setSfwzzfp();
            tlkpInsert.setFphm(recordInvoice.getInvoiceNo());
            tlkpInsert.setZjhm(invoiceTlkpInfoItem.getCertificateNo());
            tlkpInsert.setKprq(DateUtil.format(recordInvoice.getInvoiceDate(),"yyyyMMdd"));
            tlkpInsert.setYwlxmc(CommonUtil.changeTlkpYwlx(invoiceTlkpInfoItem.getBusinessType()));
            tlkpInsert.setCfz(invoiceTlkpInfoItem.getDepartureStation());
            tlkpInsert.setCfzpy(invoiceTlkpInfoItem.getDepartureStationChinese());
            tlkpInsert.setDdz(invoiceTlkpInfoItem.getDestination());
            tlkpInsert.setDdzpy(invoiceTlkpInfoItem.getDepartureStationChinese());
            tlkpInsert.setCccc(invoiceTlkpInfoItem.getTrainNo());
            tlkpInsert.setRq(invoiceTlkpInfoItem.getBoardeDate());
            tlkpInsert.setCfsjl(invoiceTlkpInfoItem.getDepartureTime());
            tlkpInsert.setTldzkppzmc(invoiceTlkpInfoItem.getTicketType());
            tlkpInsert.setKttz(invoiceTlkpInfoItem.getAircondition());
            tlkpInsert.setXbl(invoiceTlkpInfoItem.getFarewell());
            tlkpInsert.setCx(invoiceTlkpInfoItem.getCarriage());
            tlkpInsert.setXw(invoiceTlkpInfoItem.getSeat());
            //tlkpInsert.setZfje();
            tlkpInsert.setYtje(invoiceTlkpInfoItem.getRefundAmount());
            //tlkpInsert.setYppj();
            //tlkpInsert.setYpcfz();
            //tlkpInsert.setYpddz();
            tlkpInsert.setTaxRate(invoiceTlkpInfoItem.getTaxRate());
            tlkpInsert.setDzkph(invoiceTlkpInfoItem.getEleTicketNo());
            tlkpInsert.setXm(invoiceTlkpInfoItem.getFullName());
            //tlkpInsert.setTlkpyhlx();
            //tlkpInsert.setYfphm();
            tlkpInsert.setCreateTime(new Date());
            tdxTdysTldzkpCoreDao.insert(tlkpInsert);

            //根据返回的明细设置是detailyesorno
            Long aLong = tdxTdysTldzkpCoreDao.selectCount(new LambdaQueryWrapper<TdxTdysTldzkpEntity>().eq(TdxTdysTldzkpEntity::getUuid, recordInvoice.getUuid()));
            if(aLong>0){
                recordInvoice.setDetailYesorno("1");
            }else{
                recordInvoice.setDetailYesorno("0");
            }
        }
    }

    private void processEscInvoice(String dbName, String invoiceSource, TDxHttpLogZzsfpgjEntity zzsfpgjlog, List<UsedcarInvoiceModel> escInovices) {
        log.info("处理二手车发票数据---");

        boolean flg = false;
        //要推送票池的uuid集合
        List<String> uuids = new LinkedList();
        for (UsedcarInvoiceModel dataPlatformInvoiceInfo : escInovices) {
            // 解析处理
            flg = dealEsc(dataPlatformInvoiceInfo,invoiceSource, dbName, zzsfpgjlog);

            if("01".equals(zzsfpgjlog.getType())){
                uuids.add(CommonUtil.getUuid(dataPlatformInvoiceInfo.getInvoiceCode(), dataPlatformInvoiceInfo.getInvoiceNo()));
            }
        }
        //推送新票池记录表
        poolLogService.pushChangeToPool(ConfigureConstant.POOL_SJLX_JXFP_1, uuids, ConfigureConstant.POOL_BGLX_SJBG_1);

        DynamicContextHolder.push(dbName + DbConstant.BUSINESS_WRITE);
        if (flg) {
            zzsfpgjlog.setStatus("2");
        } else {
            zzsfpgjlog.setStatus("1");
        }
        tDxHttpZzsfpgjDao.updateById(zzsfpgjlog);

        log.info("处理二手车发票数据完成---");
    }

    private boolean dealEsc(Object dataPlatformInvoiceInfo,String invoiceSource, String db ,TDxHttpLogZzsfpgjEntity tDxHttpLog) {
        boolean flg;
        Map<String, Object> map = null;
        try {
            map = getEscInfo((UsedcarInvoiceModel)dataPlatformInvoiceInfo, tDxHttpLog);

            TDxVehicleSaleInvoice tDxVehicleSaleInvoice = (TDxVehicleSaleInvoice)map.get("vehicleSaleInvoice");
            TDxRecordEntity invoice = null;
            invoice = (TDxRecordEntity)map.get("veinfo");
            String code = invoice.getInvoiceCode();
            String no = invoice.getInvoiceNo();
            invoice.setUuid(code + no);
            invoice.setCompany(tDxHttpLog.getCompany());
            invoice.setSourceSystem("4");
            invoice.setCollectFrom("4");
            invoice.setInvoiceSource(invoiceSource);
            DynamicContextHolder.push(db + DbConstant.BUSINESS_READ);
            // 判断是否有数据
            TDxRecordInvoice record = null;
            if ("01".equals(tDxHttpLog.getType())) {
                record = tDxRecordInvoiceJobDao.findInvoiceByCodeAndNo(code, no);
            }
            if ("02".equals(tDxHttpLog.getType())) {
                record = tDxRecordInvoiceJobDao.findSaleInvoiceByCodeAndNo(code, no);
            }
            DynamicContextHolder.push(db + DbConstant.BUSINESS_WRITE);
            if (record != null) {
                if ("0".equals(record.getSourceSystem()) || "1".equals(record.getSourceSystem())
                        || "4".equals(record.getSourceSystem())
                        || !record.getInvoiceStatus().equals(invoice.getInvoiceStatus())) {
                    if ("01".equals(tDxHttpLog.getType())) {
                        TDxRecordInvoice tri = new TDxRecordInvoice();
                        BeanUtils.copyProperties(invoice, tri);
                        invoiceInterfaceService.isExistInvoice(tri, db, invoice.getSourceSystem());
                    }
                    if ("02".equals(tDxHttpLog.getType())) {
                        // todo 增加开票人字段
                        invoice.setPrintor(invoice.getInvoicer());
                        TDxSaleRecordInvoiceJobEntity tsri = new TDxSaleRecordInvoiceJobEntity();
                        BeanUtils.copyProperties(invoice, tsri);
                        invoiceInterfaceService.isExistSaleInvoice(tsri, db, invoice.getSourceSystem());
                    }
                } else {
                    RecordInvoiceDownModel data = new RecordInvoiceDownModel();
                    data.setInvoiceCode(code);
                    data.setInvoiceNo(no);
                    // 不做更新，记录日志表
                    insertDataPlatformLog(data, db);
                }
            } else {
                if (!"0".equals(invoice.getInvoiceStatus())) {
                    invoice.setStatusUpdateDate(new Date());
                }
                // 第一次插入添加票池采集字段
                invoice.setCollectStatus("1");
                invoice.setCollectFrom(invoice.getCollectFrom());
                invoice.setCollectDate(new Date());
                invoice.setPoolStatus("0");
                //记录通道来源
                invoice.setTdly("4");
                if ("01".equals(tDxHttpLog.getType())) {
                    TDxRecordInvoice tri = new TDxRecordInvoice();
                    BeanUtils.copyProperties(invoice, tri);
                    tDxRecordInvoiceJobDao.insert(tri);
                }
                if ("02".equals(tDxHttpLog.getType())) {
                    TDxSaleRecordInvoiceJobEntity tsri = new TDxSaleRecordInvoiceJobEntity();
                    BeanUtils.copyProperties(invoice, tsri);
                    tDxSaleRecordInvoiceJobDao.insert(tsri);
                }
            }

            String invoiceCode = invoice.getInvoiceCode();
            String invoiceNo = invoice.getInvoiceNo();
            invoice.setUuid(invoiceCode + invoiceNo);
            tDxVehicleSaleInvoice.setUuid(invoiceCode + invoiceNo);
            log.info("机动车发票购方税号：" + invoice.getGfTaxNo());
            log.info("机动车发票uuid:" + invoiceCode + invoiceNo);

            int countDetail = 0;
            if ("01".equals(tDxHttpLog.getType())) {
                // 保存发票明细
                tDxRecordInvoiceDetailDao.delDetailJd(code + no);
                InvoiceCheckVehicleDetailModel invoiceCheckVehicleDetailModel =
                        TransitionUtils.getVehicleDetaiModel(tDxVehicleSaleInvoice);
                // 由于暂时不用发票获取接口， 解放时参考查验定时任务转换实体再做插入
                tDxVehicleSaleInvoiceDao.insert(invoiceCheckVehicleDetailModel);
                countDetail = tDxRecordInvoiceDetailDao.getDetailJd(code + no);
            }
            if ("02".equals(tDxHttpLog.getType())) {
                // 保存发票明细
                tDxRecordInvoiceDetailDao.delDetailJdSales(code + no);
                InvoiceCheckVehicleDetailSalesModel invoiceCheckVehicleDetailSalesModel =
                        TransitionUtils.getVehicleDetaiSalesModel(tDxVehicleSaleInvoice);
                tDxVehicleSaleInvoiceSalesDao.insert(invoiceCheckVehicleDetailSalesModel);
                countDetail = tDxRecordInvoiceDetailDao.getDetailJdSales(code + no);
            }

            if (countDetail > 0) {
                invoice.setDetailYesorno("1");
            } else {
                invoice.setDetailYesorno("0");
            }
            if ("01".equals(tDxHttpLog.getType())) {
                TDxRecordInvoice tri = new TDxRecordInvoice();
                BeanUtils.copyProperties(invoice, tri);
                tDxRecordInvoiceDetailDao.updateDetailYesorno(tri);
            }
            if ("02".equals(tDxHttpLog.getType())) {
                TDxSaleRecordInvoiceJobEntity tsri = new TDxSaleRecordInvoiceJobEntity();
                BeanUtils.copyProperties(invoice, tsri);
                // 销项数据更新
                tDxRecordInvoiceDetailDao.updateSaleDetailYesorno(tsri);
            }
        } catch (ParseException e) {
            log.info("数据处理异常:{}", e);
            return true;
        }
        return false;
    }


    public String changeBrackets(String paramString) {
        return paramString.replace("（", "(").replace("(", "(").replace("）", ")").replace(")", ")");
    }

    private void insertDataPlatformLog(RecordInvoiceDownModel dataPlatformInvoiceInfo, String db) {
        // 插入日志信息
        DynamicContextHolder.push(db + DbConstant.BUSINESS_WRITE);
        DataPlatformInvoiceLog data = new DataPlatformInvoiceLog();
        data.setInvoiceCode(dataPlatformInvoiceInfo.getInvoiceCode());
        data.setInvoiceNo(dataPlatformInvoiceInfo.getInvoiceNo());
        data.setCreateDate(new Date());
        data.setMessage("数据重复");
        data.setSystemSource("0");
        dataPlatformFailRecordDao.insert(data);
    }

    private Map<String, Object> getEscInfo(UsedcarInvoiceModel info, TDxHttpLogZzsfpgjEntity tDxHttpLog)
            throws ParseException {
        TDxVehicleSaleInvoice vehicleSaleInvoice = new TDxVehicleSaleInvoice();
        TDxRecordEntity veinfo = null;
        if ("01".equals(tDxHttpLog.getType())) {
            veinfo = new TDxRecordEntity();
        }
        if ("02".equals(tDxHttpLog.getType())) {
            veinfo = new TDxSaleRecordInvoiceJobEntity();

        }

        veinfo.setInvoiceCode(info.getInvoiceCode());
        veinfo.setInvoiceNo(info.getInvoiceNo());
        veinfo.setEleInvoiceNo(info.getElectronicInvoiceNo());
        veinfo.setInvoiceType(info.getInvoiceType());
        veinfo.setGfName(info.getBuyerName());
        veinfo.setInvoiceDate(new SimpleDateFormat("yyyy-MM-dd").parse(info.getInvoiceDate()));
        if (org.apache.commons.lang3.StringUtils.isBlank(info.getBuyerIdNum())) {
            vehicleSaleInvoice.setBuyerIdNum("");
        } else {
            vehicleSaleInvoice.setBuyerIdNum(info.getBuyerIdNum());
        }

        if (org.apache.commons.lang3.StringUtils.isBlank(info.getVehicleType())) {
            vehicleSaleInvoice.setVehicleType("");
        } else {
            vehicleSaleInvoice.setVehicleType(info.getVehicleType());
        }
        if (org.apache.commons.lang3.StringUtils.isBlank(info.getFactoryModel())) {
            vehicleSaleInvoice.setFactoryModel("");
        } else {
            vehicleSaleInvoice.setFactoryModel(info.getFactoryModel());
        }

        if (org.apache.commons.lang3.StringUtils.isBlank(info.getVehicleNo())) {
            vehicleSaleInvoice.setVehicleNo("");
        } else {
            vehicleSaleInvoice.setVehicleNo(info.getVehicleNo());
        }
        veinfo.setTotalAmount(new BigDecimal(info.getTotalAmount()));
        veinfo.setXfName(info.getSellerName());
        veinfo.setXfTaxNo(info.getSellerIdNum());
        veinfo.setGfTaxNo(info.getBuyerIdNum());
        veinfo.setGfAddressAndPhone(info.getBuyerAddress());
        if (org.apache.commons.lang3.StringUtils.isBlank(info.getSellerPhone())) {
            vehicleSaleInvoice.setPhone("");
        } else {
            vehicleSaleInvoice.setPhone(info.getSellerPhone());
        }
        if (org.apache.commons.lang3.StringUtils.isNotEmpty(info.getSellerAddress()) && org.apache.commons.lang3.StringUtils.isNotEmpty(info.getSellerPhone())) {
            veinfo.setXfAddressAndPhone(info.getSellerAddress());
        }
        vehicleSaleInvoice.setGfPhone(info.getBuyerPhone());
        veinfo.setRemark(info.getRemark());
        veinfo.setDkTaxno(info.getDkTaxno());
        veinfo.setDkTaxname(info.getDkTaxname());
        veinfo.setDkStatus(info.getDkStatus());
        veinfo.setInvoiceAmount(new BigDecimal(info.getTotalAmount()));
        // 二手车明细表添加字段
        vehicleSaleInvoice.setPlateNo(info.getPlateNo());
        vehicleSaleInvoice.setRegistrationNo(info.getCertificateNo());
        vehicleSaleInvoice.setVehicleAdminOffice(info.getVehicleAdminOffice());
        vehicleSaleInvoice.setAuctionUnit(info.getAuctionUnit());
        vehicleSaleInvoice.setAuctionAddress(info.getAuctionAddress());
        vehicleSaleInvoice.setAuctionTaxNo(info.getAuctionTaxno());
        vehicleSaleInvoice.setAuctionBank(info.getAuctionBank());
        vehicleSaleInvoice.setAuctionPhone(info.getAuctionPhone());
        vehicleSaleInvoice.setCarMarket(info.getCarMarket());
        vehicleSaleInvoice.setCarMarketTaxNo(info.getCarMarketTaxno());
        vehicleSaleInvoice.setCarMarketAddress(info.getCarMarketAddress());
        vehicleSaleInvoice.setCarMarketBank(info.getCarMarketBank());
        vehicleSaleInvoice.setCarMarketPhone(info.getCarMarketPhone());
        veinfo.setInvoiceStatus(info.getInvoiceStatus());
        //如果发票状态是 80-红字发票待确认
        if(FpztEnum.HZDQR.getFpztDm().equals(info.getInvoiceStatus())){
            veinfo.setLqHzsdbs("Y");
        }
        veinfo.setRzhYesorno("0");

        veinfo.setSourceSystem("2");
        veinfo.setCreateDate(new Date());
        if(StringUtils.isNotBlank(info.getGlzt())){
            veinfo.setGlzt(info.getGlzt());
        }
        Map<String, Object> map = new HashMap<>(2);
        map.put("vehicleSaleInvoice", vehicleSaleInvoice);
        map.put("veinfo", veinfo);
        return map;
    }

    private void processJdcxsInvoice(String dbName, String invoiceSource, TDxHttpLogZzsfpgjEntity zzsfpgjlog, List<VehicleSaleInvoiceInfos> vehicleInovices) {
        log.info("处理机动车发票数据---");
        boolean flg = false;
        //要推送票池的uuid集合
        List<String> uuids = new LinkedList();
        for (VehicleSaleInvoiceInfos veinfo : vehicleInovices) {
            try {
                Map map = TransitionUtils.getVehicleInfo(veinfo);
                TDxVehicleSaleInvoice tDxVehicleSaleInvoice = (TDxVehicleSaleInvoice) map.get("vehicleSaleInvoice");
                TDxRecordInvoice invoice = (TDxRecordInvoice) map.get("veinfo");
                invoice.setSourceSystem("4");
                invoice.setCollectFrom("4");
                invoice.setInvoiceSource(invoiceSource);
                String code = invoice.getInvoiceCode();
                String no = invoice.getInvoiceNo();
                invoice.setUuid(code + no);
                tDxVehicleSaleInvoice.setUuid(invoice.getUuid());
                invoice.setCompany(zzsfpgjlog.getCompany());
                // todo 添加开票人字段
                invoice.setPrintor(invoice.getInvoicer());


                if ("01".equals(zzsfpgjlog.getType())) {
                    boolean isexist = isExistInvoice(invoice, dbName, invoice.getSourceSystem());
                    DynamicContextHolder.push(dbName + DbConstant.BUSINESS_WRITE);
                    if (!isexist) {
                        if (!"0".equals(invoice.getInvoiceStatus())) {
                            invoice.setStatusUpdateDate(new Date());
                        }
                        invoice.setCreateDate(new Date());
                        invoice.setCheckDate(new Date());
                        // 第一次插入添加票池采集字段
                        invoice.setCollectStatus("1");
                        invoice.setCollectFrom(invoice.getCollectFrom());
                        invoice.setCollectDate(new Date());
                        invoice.setPoolStatus("0");
                        invoice.setTdly("4");
                        tDxRecordInvoiceJobDao.insert(invoice);

                        if (tDxVehicleSaleInvoice != null) {
                            // 保存机动车明细
                            tDxRecordInvoiceDetailDao.delDetailJd(code + no);
                            InvoiceCheckVehicleDetailModel invoiceCheckVehicleDetailModel =
                                    TransitionUtils.getVehicleDetaiModel(tDxVehicleSaleInvoice);
                            tDxVehicleSaleInvoiceDao.insert(invoiceCheckVehicleDetailModel);
                        }
                    }
                }
                if ("02".equals(zzsfpgjlog.getType())) {
                    TDxSaleRecordInvoiceJobEntity tsri = new TDxSaleRecordInvoiceJobEntity();
                    BeanUtils.copyProperties(invoice, tsri);
                    boolean isexist = isExistSaleInvoice(tsri, dbName, invoice.getSourceSystem());
                    DynamicContextHolder.push(dbName + DbConstant.BUSINESS_WRITE);
                    if (!isexist) {
                        if (!"0".equals(invoice.getInvoiceStatus())) {
                            invoice.setStatusUpdateDate(new Date());
                        }
                        invoice.setCreateDate(new Date());
                        invoice.setCheckDate(new Date());
                        // 第一次插入添加票池采集字段
                        invoice.setCollectStatus("1");
                        invoice.setCollectFrom(invoice.getCollectFrom());
                        invoice.setCollectDate(new Date());
                        invoice.setPoolStatus("0");
                        invoice.setTdly("4");
                        BeanUtils.copyProperties(invoice, tsri);
                        tDxSaleRecordInvoiceJobDao.insert(tsri);

                        if (tDxVehicleSaleInvoice != null) {
                            // 保存机动车明细
                            tDxRecordInvoiceDetailDao.delSalesDetailJd(code + no);
                            InvoiceCheckVehicleDetailSalesModel invoiceCheckVehicleDetailModel =
                                    TransitionUtils.getVehicleDetaiSalesModel(tDxVehicleSaleInvoice);
                            tDxVehicleSaleInvoiceSalesDao.insert(invoiceCheckVehicleDetailModel);
                        }
                    }
                }

                if (tDxVehicleSaleInvoice!=null) {
                    invoice.setDetailYesorno("1");
                } else {
                    invoice.setDetailYesorno("0");
                }
                if ("01".equals(zzsfpgjlog.getType())) {
                    tDxRecordInvoiceDetailDao.updateDetailYesorno(invoice);
                }
                if ("02".equals(zzsfpgjlog.getType())) {
                    TDxSaleRecordInvoiceJobEntity updateSale = new TDxSaleRecordInvoiceJobEntity();
                    updateSale.setDetailYesorno(invoice.getDetailYesorno());
                    updateSale.setUuid(invoice.getUuid());
                    tDxRecordInvoiceDetailDao.updateSaleDetailYesorno(updateSale);
                }

                if ("01".equals(zzsfpgjlog.getType())) {
                    uuids.add(invoice.getUuid());
                }
            } catch (ParseException e) {
               log.info("业务处理异常：{}", e);
                flg = true;
                break;
            }
        }
        //推送新票池记录表
        poolLogService.pushChangeToPool(ConfigureConstant.POOL_SJLX_JXFP_1, uuids, ConfigureConstant.POOL_BGLX_SJBG_1);

        DynamicContextHolder.push(dbName + DbConstant.BUSINESS_WRITE);
        if (flg) {
            zzsfpgjlog.setStatus("2");
        } else {
            zzsfpgjlog.setStatus("1");
        }
        tDxHttpZzsfpgjDao.updateById(zzsfpgjlog);
        log.info("处理机动车发票数据完成---");
    }

    private void processZzsInvoice(String dbName,String invoiceSource,TDxHttpLogZzsfpgjEntity zzsfpgjlog, List<InvoiceInfo> invoices) {
        log.info("增值税发票数据-归集-入抵账库---");
            boolean flg = false;
            //要推送票池的uuid集合
            List<String> uuids = new LinkedList();
            for (InvoiceInfo invoiceInfo : invoices) {
                DynamicContextHolder.push(dbName + DbConstant.BUSINESS_WRITE);
                try {
                    // 构建底账表（解析接口返回的信息）
                    TDxRecordInvoice recordInvoices = TransitionUtils.getInvoiceInfo(invoiceInfo,"4");
                    recordInvoices.setInvoiceSource(invoiceSource);
                    recordInvoices.setSourceSystem("4");
                    recordInvoices.setCollectFrom("4");
                    recordInvoices.setCompany(zzsfpgjlog.getCompany());
                    // 判断是否有数据
                    TDxRecordInvoice invoice = null;
                    if ("01".equals(zzsfpgjlog.getType())) {
                        invoice = tDxRecordInvoiceJobDao.findInvoiceByCodeAndNo(recordInvoices.getInvoiceCode(), recordInvoices.getInvoiceNo());
                    }
                    if ("02".equals(zzsfpgjlog.getType())) {
                        invoice = tDxRecordInvoiceJobDao.findSaleInvoiceByCodeAndNo(recordInvoices.getInvoiceCode(), recordInvoices.getInvoiceNo());
                    }
                    List<InvoiceDetailInfo> detailList = invoiceInfo.getDetailList();
                    recordInvoices = this.insertZzsfpgjDetail(detailList, recordInvoices, dbName,zzsfpgjlog.getType());
                    //处理发票主信息方法
                    this.insertInvoice(recordInvoices, invoice, dbName, detailList,zzsfpgjlog.getType());

                    if("01".equals(zzsfpgjlog.getType())){
                        uuids.add(recordInvoices.getUuid());
                    }
                } catch (ParseException e) {
                    log.info("增值税发票解析异常：{}", e);
                    flg = true;
                    break;
                }
            }
            //推送新票池记录表
            poolLogService.pushChangeToPool(ConfigureConstant.POOL_SJLX_JXFP_1, uuids, ConfigureConstant.POOL_BGLX_SJBG_1);

            if (flg) {
                zzsfpgjlog.setStatus("2");
            } else {
                zzsfpgjlog.setStatus("1");
            }
        DynamicContextHolder.push(dbName + DbConstant.BUSINESS_WRITE);
        tDxHttpZzsfpgjDao.updateById(zzsfpgjlog);
        log.info("增值税发票数据入库完成---");
    }
    /**
    * @Description TODO
    * @param detailList
    * @param recordInvoices
    * @param db
    * @param jxXxtype   进项销项类型   01进项票   02销项票
    * @Return com.dxhy.api.model.invoice.TDxRecordInvoice
    * @Author wangruwei
    * @Date 2024/4/19 9:33
    **/
    private TDxRecordInvoice insertZzsfpgjDetail(List<InvoiceDetailInfo> detailList,
                                                 TDxRecordInvoice recordInvoices, String db, String jxXxtype) {
        String uuid = recordInvoices.getUuid();
        if (!CollectionUtils.isEmpty(detailList)) {
            if ("01".equals(jxXxtype)) {
                recordInvoices.setDetailYesorno("1");
                if (detailList != null && detailList.size() > 0) {
                    for (InvoiceDetailInfo invoiceDetailInfo : detailList) {
                        invoiceDetailInfo.setUuid(uuid);
                        invoiceDetailInfo.setInvoiceCode(recordInvoices.getInvoiceCode());
                        invoiceDetailInfo.setInvoiceNo(recordInvoices.getInvoiceNo());
                        invoiceDetailInfo.setTaxRate(CommonUtil.processTaxRate(invoiceDetailInfo.getTaxRate()));
                    }
                    DynamicContextHolder.push(db + DbConstant.DETAIL_WRITE);
                    tDxRecordInvoiceDetailDao.delDetail(uuid);
                    tDxRecordInvoiceDetailJobService.saveBatch(detailList);

                }
            } else if ("02".equals(jxXxtype)) {
                if (detailList != null && detailList.size() > 0) {
                    recordInvoices.setDetailYesorno("1");
                    tDxRecordInvoiceDetailSalesJobDao.delete(new LambdaQueryWrapper<TdxRecordInvoiceDetailSalesEntity>().eq(TdxRecordInvoiceDetailSalesEntity::getUuid, uuid));
                    for (InvoiceDetailInfo invoiceDetailInfo : detailList) {
                        invoiceDetailInfo.setUuid(uuid);
                        invoiceDetailInfo.setInvoiceCode(recordInvoices.getInvoiceCode());
                        invoiceDetailInfo.setInvoiceNo(recordInvoices.getInvoiceNo());
                        invoiceDetailInfo.setTaxRate(CommonUtil.processTaxRate(invoiceDetailInfo.getTaxRate()));
                        TdxRecordInvoiceDetailSalesEntity salesItem = new TdxRecordInvoiceDetailSalesEntity();
                        BeanUtils.copyProperties(invoiceDetailInfo, salesItem);
                        tDxRecordInvoiceDetailSalesJobDao.insert(salesItem);
                    }
                }
            }
        } else {
            recordInvoices.setDetailYesorno("0");
        }

        return recordInvoices;
    }

}
