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

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 javax.annotation.Resource;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

import com.dxhy.core.job.thread.InvoiceParseHandle;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.dxhy.common.constant.DbConstant;
import com.dxhy.common.datasource.config.DynamicContextHolder;
import com.dxhy.common.service.InvoiceLogService;
import com.dxhy.common.vo.InvoiceLog;
import com.dxhy.core.dao.ConfirmDao;
import com.dxhy.core.job.dao.*;
import com.dxhy.core.job.entity.*;
import com.dxhy.core.job.pojo.*;
import com.dxhy.core.job.service.InvoiceInterfaceService;
import com.dxhy.core.job.service.TDxRecordInvoiceDetailJobService;
import com.dxhy.core.job.service.TDxRecordInvoiceStatisticsService;
import com.dxhy.core.job.utils.TransitionUtils;
import com.dxhy.core.rabbitmq.Sender;

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

/**
 * 功能描述
 *
 * @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 ConfirmDao confirmDao;
    @Resource
    private TDxRecordInvoiceDetailJobDao tDxRecordInvoiceDetailDao;
    @Resource
    private TDxVehicleSaleInvoiceDao tDxVehicleSaleInvoiceDao;
    @Resource
    private TDxRecordInvoiceStatisticsJobDao tDxRecordInvoiceStatisticsDao;
    @Resource
    private TDxRecordInvoiceStatisticsService tDxRecordInvoiceStatisticsService;
    @Resource
    private TDxRecordInvoiceDetailJobService tDxRecordInvoiceDetailJobService;
    @Resource
    InvoiceLogService invoiceLogService;
    @Resource
    private Sender sender;

    @Value("${jxjk.collectUrl}")
    private String collectUrl;
    @Value("${jxjk.invoiceGet}")
    private String invoiceGet;
    @Value("${jxjk.invoiceSelection}")
    private String invoiceSelection;
    @Value("${jxjk.invoiceState}")
    private String invoiceState;
    @Value("${jxjk.enterpriseCode}")
    private String enterpriseCode;
    @Value("${jxjk.version}")
    private String version;
    @Value("${jxjk.appId}")
    private String appId;
    @Value("${pro.yl.company}")
    private String yLcompany;
    @Value("${dxhy.datasource.dxhy_admin:dxhy_admin}")
    private String dxhyAdmin;

    @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(version);
            String exchangeId = getDataExchangeId();
            globalInfo.setDataExchangeId(exchangeId);
            globalInfo.setInterfaceCode(invoiceGet);
            globalInfo.setEnterpriseCode(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, invoiceGet, aceId, aceKey);
                authorize.setAppSec(appSec);
                bqj.setData(base64Data);
                bqj.setAuthorize(authorize);
                bqj.setGlobalInfo(globalInfo);
                String collectDataStr = JSONObject.toJSONString(bqj);
                log.info("url:" + 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(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);
                confirmDao.insert(httpLog);
                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) {
            e.printStackTrace();

        }
    }

    /**
     * 获取时间戳
     *
     * @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 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\":\"" + appId
                        + "\",\"version\":\"" + version + "\",\"interfaceCode\":\"" + interfaceCode + "\",\"enterpriseCode\":\""
                        + 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) {
            e.printStackTrace();
        }
        try {
            mac.init(keySpec);
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        }
        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(version);
            String exchangeId = getDataExchangeId();
            globalInfo.setDataExchangeId(exchangeId);
            globalInfo.setInterfaceCode(invoiceState);
            globalInfo.setEnterpriseCode(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, invoiceState, aceId, aceKey);
                authorize.setAppSec(appSec);
                bqj.setData(base64Data);
                bqj.setAuthorize(authorize);
                bqj.setGlobalInfo(globalInfo);
                String invoiceStateDataStr = JSONObject.toJSONString(bqj);
                log.info("url:" + 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(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) {
            e.printStackTrace();

        }
    }

    /**
     * 发票状态获取接口返回报文解析
     *
     * @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<>();
            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);
                TDxRecordInvoiceJobEntity entity = tDxRecordInvoiceJobDao.selectOne(Wrappers
                        .<TDxRecordInvoiceJobEntity>query().eq("uuid", state.getInvoiceCode() + state.getInvoiceNo()));
                // 添加不同的认证类型，更新对应字段 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);
                        int result = tDxRecordInvoiceJobDao.updateInvoiceByState(state, rzFlag);
                        // 艺龙推送发票状态变更
                        if (result == 1 && yLcompany.equals(company)) {
                            DynamicContextHolder.push(db + DbConstant.BUSINESS_READ);
                            InvoiceScanEntity selectSign = tDxRecordInvoiceJobDao
                                    .selectByScan(state.getInvoiceCode() + state.getInvoiceNo(), dxhyAdmin);
                            if (selectSign != null && "1".equals(selectSign.getQsStatus())) {
                                String record = JSON.toJSONString(state);
                                sender.sendToStatus(Base64.encode(record));
                            }
                        }
                    }
                } else {
                    if ("0".equals(entity.getRzhYesorno())) {
                        rzFlag = null;
                    } else {
                        // 更新发票数据
                        state.setBdkStatus("0");
                    }
                    DynamicContextHolder.push(db + DbConstant.BUSINESS_WRITE);
                    int result = tDxRecordInvoiceJobDao.updateInvoiceByState(state, rzFlag);
                    // 艺龙推送发票状态变更
                    if (result == 1 && yLcompany.equals(company)) {
                        DynamicContextHolder.push(db + DbConstant.BUSINESS_READ);
                        InvoiceScanEntity selectSign = tDxRecordInvoiceJobDao
                                .selectByScan(state.getInvoiceCode() + state.getInvoiceNo(), dxhyAdmin);
                        if (selectSign != null && "1".equals(selectSign.getQsStatus())) {
                            String record = JSON.toJSONString(state);
                            sender.sendToStatus(Base64.encode(record));
                        }
                    }
                }
                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);
                }
            }
            tDxHttpLog.setStatus("1");
            tDxHttpLog.setTotal(total);
            DynamicContextHolder.push(db + DbConstant.BUSINESS_WRITE);
            confirmDao.insert(tDxHttpLog);
            if (logList.size() > 0) {
                invoiceLogService.toInvoiceLog(logList);
            }
        } catch (Exception e) {
            tDxHttpLog.setStatus("2");
            tDxHttpLog.setTotal(total);
            DynamicContextHolder.push(db + DbConstant.BUSINESS_WRITE);
            confirmDao.insert(tDxHttpLog);
            e.printStackTrace();
        }
    }

    /**
     * 获取开始时间
     *
     * @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) {
                e.printStackTrace();
            }
        }

        return lastTime;
    }

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

    /**
     * @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(version);
            String exchangeId = getDataExchangeId();
            globalInfo.setDataExchangeId(exchangeId);
            globalInfo.setInterfaceCode(invoiceSelection);
            globalInfo.setEnterpriseCode(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, invoiceSelection, aceId, aceKey);
                authorize.setAppSec(appSec);
                bqj.setData(base64Data);
                bqj.setAuthorize(authorize);
                bqj.setGlobalInfo(globalInfo);
                String collectDataStr = JSONObject.toJSONString(bqj);
                log.info("url:" + 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(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) {
            e.printStackTrace();

        }
    }

    /**
     * 勾选发票获取接口返回报文解析
     *
     * @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<>();
            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);
                TDxRecordInvoiceJobEntity entity = tDxRecordInvoiceJobDao
                        .findInvoiceByUUid(invoiceSelectInfo.getUuid());
                if (entity != null) {
                    boolean flag = false;
                    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("");
                        }
                        tDxRecordInvoiceJobDao.updateInvoice(entity, taxno);
                    }
                    // 艺龙推送数据
                    if (yLcompany.equals(company)) {
                        DynamicContextHolder.push(db + DbConstant.BUSINESS_READ);
                        InvoiceScanEntity selectSign = tDxRecordInvoiceJobDao
                                .selectByScan(entity.getInvoiceCode() + entity.getInvoiceNo(), dxhyAdmin);
                        if (selectSign != null && "1".equals(selectSign.getQsStatus())) {
                            String record = JSON.toJSONString(entity);
                            sender.sendToStatus(Base64.encode(record));
                        }
                    }
                } else {
                    if (StringUtils.isBlank(invoiceSelectInfo.getLegalizeDate())) {
                        invoiceSelectInfo.setLegalizeDate(null);
                    }
                    TDxRecordInvoiceJobEntity 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);
            }
            httpLog.setStatus("1");
            httpLog.setTotal(total);
            DynamicContextHolder.push(db + DbConstant.BUSINESS_WRITE);
            confirmDao.insert(httpLog);
            if (logList.size() > 0) {
                invoiceLogService.toInvoiceLog(logList);
            }

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

    private TDxRecordInvoiceJobEntity exchangePo2Entity(InvoiceSelectInfo po) {
        TDxRecordInvoiceJobEntity entity = new TDxRecordInvoiceJobEntity();
        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());
        }
        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 confirmDao.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) {
                e.printStackTrace();
            }
        }
        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) {
                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);
                        continue;
                    }
                    String type = gather.getInvoiceType();
                    if ("01".equals(type) || "08".equals(type) || "14".equals(type) || "31".equals(type)) {
                        parseInvoice(logid, tDxHttpLog, dataJson, db);
                    } else if ("03".equals(type)) {
                        parseVehicleInvoice(logid, tDxHttpLog, dataJson, db);
                    }
                } else {
                    tDxHttpLog.setStatus("1");
                    tDxHttpLog.setTotal("0");
                    DynamicContextHolder.push(db + DbConstant.BUSINESS_WRITE);
                    tDxHttpLogDao.updateHttoLogById(tDxHttpLog);
                }
            }
        }

    }

    @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<>();
        boolean flg = false;
        for (VehicleSaleInvoiceInfos veinfo : invoicesList) {
            try {
                Map map = TransitionUtils.getVehicleInfo(veinfo);
                TDxVehicleSaleInvoice tDxVehicleSaleInvoice = (TDxVehicleSaleInvoice) map.get("vehicleSaleInvoice");
                TDxRecordInvoiceJobEntity invoice = (TDxRecordInvoiceJobEntity) map.get("veinfo");
                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);
            } catch (ParseException e) {
                e.printStackTrace();
                flg = true;
                break;
            }
        }
        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<>();
        for (InvoiceInfo invoiceInfo : invoicesList) {
            DynamicContextHolder.push(db + DbConstant.BUSINESS_READ);
            try {
                // 构建底账表（解析接口返回的信息）
                TDxRecordInvoiceJobEntity recordInvoices = TransitionUtils.getInvoiceInfo(invoiceInfo);
                recordInvoices.setCompany(tDxHttpLog.getCompany());
                TDxRecordInvoiceJobEntity invoice =
                        tDxRecordInvoiceJobDao.findInvoiceByUUid(recordInvoices.getUuid());
                List<InvoiceDetailInfo> detailList = invoiceInfo.getDetailList();
                recordInvoices = this.insertDetail(detailList, recordInvoices, db);
                this.insertInvoice(recordInvoices, invoice, db, detailList);
                // 保存发票关联请求日志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);
            } catch (ParseException e) {
                e.printStackTrace();
                flg = true;
                break;
            }
        }

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

    private void insertInvoice(TDxRecordInvoiceJobEntity recordInvoices, TDxRecordInvoiceJobEntity invoice, String db,
                               List<InvoiceDetailInfo> detailList) {
        // 判断底账是否存在 存在更新 不存在保存
        DynamicContextHolder.push(db + DbConstant.BUSINESS_WRITE);
        if (invoice == null) {
            if (!"0".equals(recordInvoices.getInvoiceStatus())) {
                recordInvoices.setStatusUpdateDate(new Date());
            }
            // 第一次插入添加票池采集字段
            recordInvoices.setCollectStatus("1");
            recordInvoices.setCollectFrom("0");
            recordInvoices.setCollectDate(new Date());
            recordInvoices.setPoolStatus("0");
            recordInvoices.setCreateDate(new Date());
            recordInvoices.setCheckDate(new Date());
            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("0");
                recordInvoices.setCollectDate(new Date());
                recordInvoices.setPoolStatus("1");
                recordInvoices.setInPoolReason("数据重复");
            }
            tDxRecordInvoiceJobDao.updateRecordInvoice(recordInvoices);
        }
        tDxRecordInvoiceStatisticsDao.delStatistics(recordInvoices.getInvoiceCode(), recordInvoices.getInvoiceNo());
        // 税率统计表插入
        tDxRecordInvoiceStatisticsService.countTaxRate(detailList, recordInvoices.getInvoiceCode(),
                recordInvoices.getInvoiceNo());
    }

    private TDxRecordInvoiceJobEntity insertDetail(List<InvoiceDetailInfo> detailList,
                                                   TDxRecordInvoiceJobEntity 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);
            }
            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(TDxRecordInvoiceJobEntity invoiceInfo, String db, String sourceSystem) {

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

            if (!invoice.getInvoiceStatus().equals(invoiceInfo.getInvoiceStatus())) {
                invoice.setInvoiceStatus(invoiceInfo.getInvoiceStatus());
                invoice.setStatusUpdateDate(new Date());
            }
            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 confirmDao.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);
        TDxRecordInvoiceJobEntity invoice = tDxRecordInvoiceJobDao.findSaleInvoiceByCodeAndNo(invoiceCode, invoiceNo);
        if (null != invoice) {

            if (!invoice.getInvoiceStatus().equals(invoiceInfo.getInvoiceStatus())) {
                invoice.setInvoiceStatus(invoiceInfo.getInvoiceStatus());
                invoice.setStatusUpdateDate(new Date());
            }
            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 confirmDao.getTaxnoForDown();
    }

    @Override
    public List<TDxHttpLogInvoiceDown> getHttpLog() {

        return confirmDao.getHttpLog();
    }
}
