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

import cn.hutool.core.codec.Base64;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.dxhy.api.model.invoice.InvoiceDetailInfo;
import com.dxhy.api.model.invoice.TDxRecordEntity;
import com.dxhy.api.model.invoice.TDxRecordInvoice;
import com.dxhy.common.constant.DbConstant;
import com.dxhy.common.datasource.config.DynamicContextHolder;
import com.dxhy.common.utils.CommonUtil;
import com.dxhy.core.job.dao.*;
import com.dxhy.core.job.entity.*;
import com.dxhy.core.job.pojo.DataPlatformInvoiceDetailInfo;
import com.dxhy.core.job.pojo.DataPlatformInvoiceInfo;
import com.dxhy.core.job.pojo.DataPlatformVehicleSaleInvoiceInfos;
import com.dxhy.core.job.service.DataPlatformCollectService;
import com.dxhy.core.job.service.InvoiceInterfaceService;
import com.dxhy.core.job.service.TokenService;
import com.dxhy.core.job.utils.TransitionUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

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

public class DataPlatformCollectServiceImpl implements DataPlatformCollectService {

    @Value("${jxjk.dataPlatformCollectUrl}")
    private String collectUrl;
    @Value("${jxjk.dataPlatformCollectStateUrl}")
    private String collectStateUrl;

    @Resource
    private DataPlatformDao dataPlatformDao;
    @Resource
    private TokenService tokenService;
    @Resource
    private TDxRecordInvoiceJobDao tDxRecordInvoiceJobDao;
    @Resource
    private TDxSaleRecordInvoiceJobDao tDxSaleRecordInvoiceJobDao;
    @Resource
    private DataPlatformRecordDao dataPlatformRecordDao;
    @Resource
    private DataPlatformSaleRecordDao dataPlatformSaleRecordDao;
    @Resource
    private InvoiceInterfaceService invoiceInterfaceService;
    @Resource
    private TDxRecordInvoiceDetailJobDao tDxRecordInvoiceDetailDao;
    @Resource
    private TDxVehicleSaleInvoiceDao tDxVehicleSaleInvoiceDao;
    @Resource
    private TDxVehicleSaleInvoiceSalesDao tDxVehicleSaleInvoiceSalesDao;
    @Resource
    private DataPlatformFailRecordDao dataPlatformFailRecordDao;
    @Resource
    private DataPlatformInvoiceDetailDao dataPlatformInvoiceDetailDao;

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

    /**
     * 获取时间戳
     *
     * @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 < 11; i++) {
            sb.append(rand.nextInt(10));
        }
        String data = sb.toString();
        return simpleDateFormat.format(new Date()) + data;
    }

    /**
     * 获取进项发票数据 02 - 货运运输业增值税专用发票 04 增值税普通发票 10 增值税普通发票（电子） 11 卷式 15 二手车销售统一发票
     */
    @Override
    public void sendRequest(String type, String taxno, String db, String company, String params, String reqType,
        String aceId, String aceKey) {
        // 拼接报文，请求数据
        // 准备通用报文
        JSONObject globalParams = new JSONObject();
        // 生成数据交换流水号
        String exchangeId = getDataExchangeId();
        globalParams.put("zipCode", "0");
        globalParams.put("encryptCode", "0");
        globalParams.put("dataExchangeId", exchangeId);
        // 获取token
        String token = tokenService.getToken(aceId, aceKey);
        JSONObject content = new JSONObject();
        // 拼接业务报文
        int curr = 1;
        try {
            // 记录获取token重试次数
            int getCount = 0;
            // 默认采集配置
            content.put("page", "1");
            content.put("size", "200");
            content.put("taxNo", taxno);
            content.put("subject", reqType);
            content.put("invoiceType", type);
            // 获取开始日期-结束日期 --默认使用发票入库日期
            DynamicContextHolder.push(db + DbConstant.BUSINESS_READ);
            content.put("acquiStartDate", getBeginTimeQpm(taxno, reqType, type));
            content.put("acquiEndDate", getEndTime());

            while (true) {
                String encode = Base64.encode(content.toJSONString());
                globalParams.put("content", encode);
                TDxHttpLogDataPlatform dataLog = new TDxHttpLogDataPlatform();
                dataLog.setTaxno(taxno);
                dataLog.setType("01");
                dataLog.setReqText(content.toString());
                // 得到返回报文，解析拿出返回的数量，累加用于判断数量
                dataLog.setReqDate(new Date());
                log.info("数据平台采集请求参数-" + content.toString());
                String responseJson = HttpUtil.post(collectUrl + token, globalParams.toString(), 60000);
                log.info("数据平台采集返回报文-" + responseJson);
                dataLog.setResDate(new Date());
                dataLog.setResText(responseJson);
                dataLog.setStatus("0");
                // 判断token是否过期
                JSONObject ob = JSONObject.parseObject(responseJson);
                dataLog.setResText(responseJson);
                dataLog.setStatus("0");
                dataLog.setCompany(company);
                dataLog.setInvoiceType(type);
                dataLog.setSubject(reqType);
                DynamicContextHolder.push(db + DbConstant.BUSINESS_WRITE);
                dataPlatformDao.insert(dataLog);
                if (ob != null) {
                    String returnStateInfo = ob.getString("returnStateInfo");
                    JSONObject returnState = JSONObject.parseObject(returnStateInfo);
                    String code = returnState.getString("returnCode");
                    if ("9110".equals(code) || "9111".equals(code)) {
                        // 如果token失效或者无效，重新获取发起
                        if (getCount < 5) {
                            token = tokenService.getToken(aceId, aceKey);
                            getCount++;
                        } else {
                            break;
                        }
                    } else if ("0000".equals(code)) {
                        // 获取返回总条数判断是否需要继续请求
                        String returnContent = ob.getString("content");
                        if (returnContent != null) {

                            JSONObject invoices = JSONObject.parseObject(Base64.decodeStr(returnContent));
                            String code1 = invoices.getString("code");
                            // 判断内层报文是否成功
                            if ("0000".equals(code1)) {
                                String pages = invoices.getJSONObject("data").getString("pages");
                                String current = invoices.getJSONObject("data").getString("current");
                                curr = Integer.parseInt(current) + 1;
                                int pageTotal = Integer.parseInt(pages);
                                if (curr > pageTotal) {
                                    break;
                                } else {
                                    content.put("page", curr + "");
                                    globalParams.put("dataExchangeId", getDataExchangeId());
                                }
                            } else {
                                break;
                            }
                        }
                    } else {
                        break;
                    }
                }
            }
        } catch (Exception e) {
           log.info("业务处理异常：{}", e);
        }

    }

    private String getEndTime() {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        return simpleDateFormat.format(new Date());
    }

    private String getBeginTimeQpm(String taxno, String reqType, String type) {
        String lastTime = dataPlatformDao.selectLastInvoiceDate(taxno, reqType, type);
        if (lastTime == null || "".equals(lastTime)) {
            // 读取数据库配置
            DynamicContextHolder.push(DbConstant.BASICS_READ);
            lastTime = dataPlatformDao.getFirstCollectDate(taxno);
        } else {
            // 避免防止漏票，提前一小时
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
            try {
                Date date = simpleDateFormat.parse(lastTime);
                Calendar cal = Calendar.getInstance();
                cal.setTime(date);
                date = cal.getTime();
                lastTime = simpleDateFormat.format(date);
            } catch (ParseException e) {
               log.info("业务处理异常：{}", e);
            }
        }

        return lastTime;
    }

    /**
     * 获取待解析的日志记录
     */
    @Override
    public List<TDxHttpLogDataPlatform> getNotParseHttpLogs(String s) {

        return dataPlatformDao.getNotParseHttpLogs(s);
    }

    /**
     * 解析返回报文 发票获取
     *
     * @param tDxHttpLog,
     *            String responseJson, String linkName, TDxHttpLog tDxHttpLog
     */
    @Override
    public void subscribe(TDxHttpLogDataPlatform tDxHttpLog, String db) {
        Long logid = tDxHttpLog.getLogId();
        log.info("开始解析报文id:" + logid + "  报文内容：" + tDxHttpLog.getResText());
        String res = tDxHttpLog.getResText();
        JSONObject resJson = JSONObject.parseObject(res);
        String code = resJson.getJSONObject("returnStateInfo").getString("returnCode");
        if ("0000".equals(code)) {
            String returnContent = resJson.getString("content");
            if (returnContent != null) {
                JSONObject invoices = JSONObject.parseObject(Base64.decodeStr(returnContent));
                String code1 = invoices.getString("code");
                // 判断内层报文是否成功
                if ("0000".equals(code1)) {
                    String total = invoices.getJSONObject("data").getString("total");
                    if ("0".equals(total)) {
                        updateLog(tDxHttpLog, db);
                        return;
                    }
                    // 根据不同发票类型解进行解析
                    JSONArray records = invoices.getJSONObject("data").getJSONArray("records");
                    String invoiceType = tDxHttpLog.getInvoiceType();
                    // 普通,专用,电子,卷式
                    if ("01".equals(invoiceType) || "04".equals(invoiceType) || "10".equals(invoiceType)
                        || "11".equals(invoiceType)) {
                        parseInvoices(records, db, tDxHttpLog);
                    }
                    if ("14".equals(invoiceType)) {
                        parseInvoices(records, db, tDxHttpLog);
                    }
                    if ("03".equals(invoiceType)) {
                        parseJdcInvoice(records, db, tDxHttpLog.getCompany(), tDxHttpLog);
                    }
                    if ("15".equals(invoiceType)) {
                        parseJdcInvoice(records, db, tDxHttpLog.getCompany(), tDxHttpLog);
                    }

                } else {
                    updateLog(tDxHttpLog, db);
                }
            }
        } else {
            updateLog(tDxHttpLog, db);
        }

    }

    /**
     * 进项解析
     *
     * @param records
     * @param db
     * @param company
     * @param tDxHttpLog
     */
    private void parseJdcInvoice(JSONArray records, String db, String company, TDxHttpLogDataPlatform tDxHttpLog) {
        List<DataPlatformVehicleSaleInvoiceInfos> invoicesList =
            records.toJavaList(DataPlatformVehicleSaleInvoiceInfos.class);
        String total = invoicesList.size() + "";
        boolean flg = false;
        for (DataPlatformVehicleSaleInvoiceInfos dataPlatformInvoiceInfo : invoicesList) {
            // 解析处理
            flg = updateVehicleSaleInvoiceAndDetail(dataPlatformInvoiceInfo, db, company, tDxHttpLog);

        }
        if (flg) {
            tDxHttpLog.setStatus("2");
            tDxHttpLog.setTotal(total);
            DynamicContextHolder.push(db + DbConstant.BUSINESS_WRITE);
            dataPlatformDao.updateHttpLogById(tDxHttpLog);
        } else {
            tDxHttpLog.setStatus("1");
            tDxHttpLog.setTotal(total);
            DynamicContextHolder.push(db + DbConstant.BUSINESS_WRITE);
            dataPlatformDao.updateHttpLogById(tDxHttpLog);
        }

    }

    /**
     * 机动车发票更新
     *
     * @param dataPlatformInvoiceInfo
     *            发票信息
     * @param db
     * @param tDxHttpLog
     */
    private boolean updateVehicleSaleInvoiceAndDetail(DataPlatformVehicleSaleInvoiceInfos dataPlatformInvoiceInfo,
        String db, String company, TDxHttpLogDataPlatform tDxHttpLog) {
        boolean flg;
        try {
            dataPlatformInvoiceInfo.setInvoiceState(exchangeInvoiceStatus(dataPlatformInvoiceInfo.getInvoiceState()));
            Map<String, Object> map = getVehicleInfo(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(company);
            DynamicContextHolder.push(db + DbConstant.BUSINESS_READ);
            // 判断是否有数据
            TDxRecordInvoice record = null;
            if ("1".equals(tDxHttpLog.getSubject())) {
                record = tDxRecordInvoiceJobDao.findInvoiceByCodeAndNo(code, no);
            }
            if ("2".equals(tDxHttpLog.getSubject())) {
                record = tDxRecordInvoiceJobDao.findSaleInvoiceByCodeAndNo(code, no);
            }
            DynamicContextHolder.push(db + DbConstant.BUSINESS_WRITE);
            if (record != null) {
                if ("0".equals(record.getSourceSystem()) || "1".equals(record.getSourceSystem())
                    || !record.getInvoiceStatus().equals(invoice.getInvoiceStatus())) {
                    if ("1".equals(tDxHttpLog.getSubject())) {
                        TDxRecordInvoice tdi = new TDxRecordInvoice();
                        BeanUtils.copyProperties(invoice,tdi);
                        invoiceInterfaceService.isExistInvoice(tdi, db, "2");
                    }
                    if ("2".equals(tDxHttpLog.getSubject())) {
                        TDxSaleRecordInvoiceJobEntity tsri = new TDxSaleRecordInvoiceJobEntity();
                        BeanUtils.copyProperties(invoice,tsri);
                        invoiceInterfaceService.isExistSaleInvoice(tsri, db, "2");
                    }
                } else {
                    DataPlatformInvoiceInfo data = new DataPlatformInvoiceInfo();
                    data.setInvoiceCode(code);
                    data.setInvoiceNo(no);
                    // 不做更新，记录日志表
                    insertDataPlatformLog(data, db);
                }
            } else {
                if (!"0".equals(invoice.getInvoiceStatus())) {
                    invoice.setStatusUpdateDate(new Date());
                }
                // 第一次插入添加票池采集字段
                invoice.setCollectStatus("1");
                invoice.setCollectFrom("1");
                invoice.setCollectDate(new Date());
                invoice.setPoolStatus("0");
                //记录通道来源
                invoice.setTdly("2");
                if ("1".equals(tDxHttpLog.getSubject())) {
                    TDxRecordInvoice tdi = new TDxRecordInvoice();
                    BeanUtils.copyProperties(invoice,tdi);
                    tDxRecordInvoiceJobDao.insert(tdi);
                }
                if ("2".equals(tDxHttpLog.getSubject())) {
                    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 ("1".equals(tDxHttpLog.getSubject())) {
                // 保存发票明细
                tDxRecordInvoiceDetailDao.delDetailJd(code + no);
                InvoiceCheckVehicleDetailModel invoiceCheckVehicleDetailModel =
                    TransitionUtils.getVehicleDetaiModel(tDxVehicleSaleInvoice);
                // 由于暂时不用发票获取接口， 解放时参考查验定时任务转换实体再做插入
                tDxVehicleSaleInvoiceDao.insert(invoiceCheckVehicleDetailModel);
                countDetail = tDxRecordInvoiceDetailDao.getDetailJd(code + no);
            }
            if ("2".equals(tDxHttpLog.getSubject())) {
                // 保存发票明细
                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 ("1".equals(tDxHttpLog.getSubject())) {
                TDxRecordInvoice tri = new TDxRecordInvoice();
                BeanUtils.copyProperties(invoice, tri);
                tDxRecordInvoiceDetailDao.updateDetailYesorno(tri);
            }
            if ("2".equals(tDxHttpLog.getSubject())) {
                TDxSaleRecordInvoiceJobEntity tdsri = new TDxSaleRecordInvoiceJobEntity();
                BeanUtils.copyProperties(invoice, tdsri);
                // 销项数据更新
                tDxRecordInvoiceDetailDao.updateSaleDetailYesorno(tdsri);
            }
        } catch (ParseException e) {
           log.info("业务处理异常：{}", e);
            return true;
        }
        return false;

    }

    /**
     * 专普电卷解析 --进项
     *
     * @param records
     *            发票信息
     * @param db
     *            数据库
     * @param tDxHttpLog
     *            日志
     */
    private void parseInvoices(JSONArray records, String db, TDxHttpLogDataPlatform tDxHttpLog) {
        String total;
        try {
            List<DataPlatformInvoiceInfo> invoicesList = records.toJavaList(DataPlatformInvoiceInfo.class);
            total = invoicesList.size() + "";
            for (DataPlatformInvoiceInfo dataPlatformInvoiceInfo : invoicesList) {
                String invoiceCode = dataPlatformInvoiceInfo.getInvoiceCode();
                String invoiceNo = dataPlatformInvoiceInfo.getInvoiceNo();
                // 发票状态转义
                dataPlatformInvoiceInfo
                    .setInvoiceState(exchangeInvoiceStatus(dataPlatformInvoiceInfo.getInvoiceState()));
                // 判断库里有无 有-更新 无-插入
                DynamicContextHolder.push(db + DbConstant.BUSINESS_READ);
                TDxRecordInvoice invoice = null;
                if ("1".equals(tDxHttpLog.getSubject())) {
                    invoice = tDxRecordInvoiceJobDao.findInvoiceByCodeAndNo(invoiceCode, invoiceNo);
                }
                if ("2".equals(tDxHttpLog.getSubject())) {
                    invoice = tDxRecordInvoiceJobDao.findSaleInvoiceByCodeAndNo(invoiceCode, invoiceNo);
                }
                if (invoice != null) {
                    if ("1".equals(invoice.getSourceSystem())
                        || !invoice.getInvoiceStatus().equals(dataPlatformInvoiceInfo.getInvoiceState())) {
                        // 更新
                        if ("1".equals(invoice.getSourceSystem()) && "0".equals(invoice.getCollectStatus())) {
                            dataPlatformInvoiceInfo.setCollectStatus("1");
                            dataPlatformInvoiceInfo.setCollectFrom("1");
                            dataPlatformInvoiceInfo.setCollectDate(new Date());
                            dataPlatformInvoiceInfo.setPoolStatus("1");
                            dataPlatformInvoiceInfo.setInPoolReason("数据重复");
                        }
                        if (!invoice.getInvoiceStatus().equals(dataPlatformInvoiceInfo.getInvoiceState())) {
                            dataPlatformInvoiceInfo.setStatusUpdateDate(new Date());
                        }
                        updateInvoiceAndDetail(dataPlatformInvoiceInfo, db, tDxHttpLog);
                    } else {
                        // 不做更新，记录日志表
                        insertDataPlatformLog(dataPlatformInvoiceInfo, db);
                    }
                } else {
                    // 插入
                    dataPlatformInvoiceInfo.setCompany(tDxHttpLog.getCompany());
                    insertInvoiceAndDetail(dataPlatformInvoiceInfo, db, tDxHttpLog);
                }
            }

        } catch (Exception e) {
            tDxHttpLog.setStatus("2");
            tDxHttpLog.setTotal("0");
            DynamicContextHolder.push(db + DbConstant.BUSINESS_WRITE);
            dataPlatformDao.updateHttpLogById(tDxHttpLog);
           log.info("业务处理异常：{}", e);
            return;
        }
        tDxHttpLog.setStatus("1");
        tDxHttpLog.setTotal(total);
        DynamicContextHolder.push(db + DbConstant.BUSINESS_WRITE);
        dataPlatformDao.updateHttpLogById(tDxHttpLog);
    }



    /**
     * 插入日志表
     *
     * @param dataPlatformInvoiceInfo
     *            日志信息
     * @param db
     *            数据库 信息
     */
    private void insertDataPlatformLog(DataPlatformInvoiceInfo 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("2");
        dataPlatformFailRecordDao.insert(data);
    }

    /**
     * 插入数据
     *
     * @param dataPlatformInvoiceInfo
     *            日志信息
     * @param db
     * @param tDxHttpLog
     */
    private void insertInvoiceAndDetail(DataPlatformInvoiceInfo dataPlatformInvoiceInfo, String db,
        TDxHttpLogDataPlatform tDxHttpLog) throws ParseException {
        String invoiceCode = dataPlatformInvoiceInfo.getInvoiceCode();
        String invoiceNo = dataPlatformInvoiceInfo.getInvoiceNo();
        dataPlatformInvoiceInfo.setUuid(invoiceCode + invoiceNo);
        DynamicContextHolder.push(db + DbConstant.DETAIL_WRITE);
        // 插入明细
        List<DataPlatformInvoiceDetailInfo> detailList = dataPlatformInvoiceInfo.getDetailList();
        // 进项发票入库
        if ("1".equals(tDxHttpLog.getSubject())) {
            for (DataPlatformInvoiceDetailInfo dataPlatformInvoiceDetailInfo : detailList) {
                dataPlatformInvoiceDetailInfo.setUuid(invoiceCode + invoiceNo);
                dataPlatformInvoiceDetailInfo.setInvoiceCode(invoiceCode);
                dataPlatformInvoiceDetailInfo.setInvoiceNo(invoiceNo);
                dataPlatformDao.insertDetailIncome(dataPlatformInvoiceDetailInfo);
//                dataPlatformInvoiceDetailDao.insert(dataPlatformInvoiceDetailInfo);
            }
        }
        if ("2".equals(tDxHttpLog.getSubject())) {
            for (DataPlatformInvoiceDetailInfo dataPlatformInvoiceDetailInfo : detailList) {
                dataPlatformInvoiceDetailInfo.setUuid(invoiceCode + invoiceNo);
                dataPlatformInvoiceDetailInfo.setInvoiceCode(invoiceCode);
                dataPlatformInvoiceDetailInfo.setInvoiceNo(invoiceNo);
                dataPlatformDao.insertDetailSales(dataPlatformInvoiceDetailInfo);
            }
        }

        int countDetail = dataPlatformDao.getDetailCount(invoiceCode + invoiceNo);
        if (countDetail > 0) {
            dataPlatformInvoiceInfo.setDetailYesorno("1");
        } else {
            dataPlatformInvoiceInfo.setDetailYesorno("0");
        }
        // 进项发票入库
        if ("1".equals(tDxHttpLog.getSubject())) {
            DataPlatformRecordEntity invoice;
            invoice = (DataPlatformRecordEntity)getInvoiceInfo(dataPlatformInvoiceInfo, tDxHttpLog.getSubject());
            invoice.setCompany(dataPlatformInvoiceInfo.getCompany());
            //记录通道来源
            invoice.setTdly("2");
            DynamicContextHolder.push(db + DbConstant.BUSINESS_WRITE);
            dataPlatformRecordDao.insert(invoice);
        }
        if ("2".equals(tDxHttpLog.getSubject())) {
            DataPlatformSaleRecordEntity invoice;
            invoice = (DataPlatformSaleRecordEntity)getInvoiceInfo(dataPlatformInvoiceInfo, tDxHttpLog.getSubject());
            invoice.setCompany(dataPlatformInvoiceInfo.getCompany());
            //记录通道来源
            invoice.setTdly("2");
            if (invoice!=null&&invoice.getGfName() != null) {
                invoice.setGfName(changeBrackets(invoice.getGfName()));
            }
            DynamicContextHolder.push(db + DbConstant.BUSINESS_WRITE);
            dataPlatformSaleRecordDao.insert(invoice);
        }
    }

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

    private InvoiceDetailInfo exchangeEntity(DataPlatformInvoiceDetailInfo data) {
        InvoiceDetailInfo info = new InvoiceDetailInfo();
        info.setInvoiceCode(data.getInvoiceCode());
        info.setInvoiceNo(data.getInvoiceNo());
        info.setGoodsName(data.getIvwName());
        info.setModel(data.getIvspec());
        info.setUnit(data.getUnit());
        info.setNum(data.getWnumb());
        info.setUnitPrice(data.getWprice());
        info.setDetailAmount(data.getAmount());
        info.setTaxRate(CommonUtil.processTaxRate(data.getTaxRate()));
        info.setTaxAmount(data.getTaxAmount());
        info.setGoodsNum(data.getItemCode());
        info.setUuid(data.getUuid());
        info.setIsDiscount(data.getIsDiscount());
        info.setCph(data.getPlatNo());
        info.setLx(data.getVehicleType());
        info.setTxrqq(data.getTransitStartTime());
        info.setTxrqz(data.getTransitEndTime());
        return info;
    }

    /**
     * 更新数据库数据
     *
     * @param invoice
     *            发票信息
     * @param db
     * @param tDxHttpLog
     */
    private void updateInvoiceAndDetail(DataPlatformInvoiceInfo invoice, String db, TDxHttpLogDataPlatform tDxHttpLog) {
        String invoiceCode = invoice.getInvoiceCode();
        String invoiceNo = invoice.getInvoiceNo();
        String uuid = invoiceCode + invoiceNo;
        List<DataPlatformInvoiceDetailInfo> detailList = invoice.getDetailList();
        if (detailList != null && detailList.size() > 0) {
            DynamicContextHolder.push(db + DbConstant.DETAIL_WRITE);
            if ("1".equals(tDxHttpLog.getSubject())) {
                dataPlatformDao.delDetailIncome(invoiceCode + invoiceNo);
                for (DataPlatformInvoiceDetailInfo invoiceDetailInfo : detailList) {
                    invoiceDetailInfo.setInvoiceCode(invoiceCode);
                    invoiceDetailInfo.setInvoiceNo(invoiceNo);
                    invoiceDetailInfo.setTaxRate(CommonUtil.processTaxRate(invoiceDetailInfo.getTaxRate()));
                    invoiceDetailInfo.setUuid(uuid);
//                    dataPlatformDao.insertDetailIncome(invoiceDetailInfo);
                    dataPlatformInvoiceDetailDao.insert(invoiceDetailInfo);
                }
            }
            if ("2".equals(tDxHttpLog.getSubject())) {
                dataPlatformDao.delDetailSales(invoiceCode + invoiceNo);
                for (DataPlatformInvoiceDetailInfo invoiceDetailInfo : detailList) {
                    invoiceDetailInfo.setInvoiceCode(invoiceCode);
                    invoiceDetailInfo.setInvoiceNo(invoiceNo);
                    invoiceDetailInfo.setTaxRate(CommonUtil.processTaxRate(invoiceDetailInfo.getTaxRate()));
                    invoiceDetailInfo.setUuid(uuid);
                    dataPlatformDao.insertDetailSales(invoiceDetailInfo);
                }
            }
            DynamicContextHolder.push(db + DbConstant.DETAIL_READ);
            int countDetail = dataPlatformDao.getDetailCount(invoiceCode + invoiceNo);
            if (countDetail > 0) {
                invoice.setDetailYesorno("1");
            } else {
                invoice.setDetailYesorno("0");
            }

            if ("1".equals(tDxHttpLog.getSubject())) {
                DynamicContextHolder.push(db + DbConstant.BUSINESS_WRITE);
                dataPlatformDao.updateRecordInvoice(invoice);
            }
            if ("2".equals(tDxHttpLog.getSubject())) {
                DynamicContextHolder.push(db + DbConstant.BUSINESS_WRITE);
                if (invoice.getBuyerName() != null) {
                    invoice.setBuyerName(changeBrackets(invoice.getBuyerName()));
                }
                dataPlatformDao.updateSaleRecordInvoice(invoice);
            }

        }
    }

    private void updateLog(TDxHttpLogDataPlatform tDxHttpLog, String db) {
        tDxHttpLog.setStatus("1");
        tDxHttpLog.setTotal("0");
        DynamicContextHolder.push(db + DbConstant.BUSINESS_WRITE);
        dataPlatformDao.updateHttpLogById(tDxHttpLog);

    }

    /**
     * 转换实体
     *
     * @param info
     *            发票信息
     * @param subject
     * @return 返回
     */
    private DataPlatformEntity getInvoiceInfo(DataPlatformInvoiceInfo info, String subject) throws ParseException {
        DataPlatformEntity invoice = null;
        if ("1".equals(subject)) {
            invoice = new DataPlatformRecordEntity();
        }
        if ("2".equals(subject)) {
            invoice = new DataPlatformSaleRecordEntity();
        }
        // 发票代码
        invoice.setInvoiceCode(info.getInvoiceCode());
        // 发票号码
        invoice.setInvoiceNo(info.getInvoiceNo());
        // 发票类型
        invoice.setInvoiceType(info.getInvoiceType());
        // 购方名称
        invoice.setGfName(info.getBuyerName());
        // 购方税号
        invoice.setGfTaxNo(info.getBuyerTaxNo());
        // 购方地址、电话
        invoice.setGfAddressAndPhone(info.getBuyerAddressPhone());
        // 购方开户行及账号
        invoice.setGfBankAndNo(info.getBuyerBankAccount());
        // 销方名称
        invoice.setXfName(info.getSellerName());
        // 销方税号
        invoice.setXfTaxNo(info.getSellerTaxNo());
        // 销方地址、电话
        invoice.setXfAddressAndPhone(info.getSellerAddressPhone());
        // 销方开户行及账号
        invoice.setXfBankAndNo(info.getSellerBankAccount());
        // 开票日期
        invoice.setInvoiceDate(new SimpleDateFormat("yyyy-MM-dd").parse(info.getInvoiceDate()));

        // 备注
        invoice.setRemark(info.getRemark());
        // 发票状态
        invoice.setInvoiceStatus(info.getInvoiceState());
        // 是否代办退税
        invoice.setSfdbts(null);
        // 认证类型
        if ("1".equals(info.getLegalizeState())) {
            invoice.setRzlx("1");
        }
        if ("2".equals(info.getLegalizeState())) {
            invoice.setRzlx("4");
        }
        if ("0".equals(info.getLegalizeState())) {
            invoice.setRzlx(null);
        }

        if (info.getTotalAmount() != null && !"".equals(info.getTotalAmount())) {
            // 发票金额
            invoice.setInvoiceAmount(new BigDecimal(info.getTotalAmount()));
        }
        if (info.getTotalTaxAmount() != null && !"".equals(info.getTotalTaxAmount())) {
            // 发票税额
            invoice.setTaxAmount(new BigDecimal(info.getTotalTaxAmount()));
        }
        if (info.getAllAmount() != null && !"".equals(info.getAllAmount())) {
            // 价税合计
            invoice.setTotalAmount(new BigDecimal(info.getAllAmount()));
        }

        // 认证方式
        if (info.getLegalizeType() == null || "".equals(info.getLegalizeType())) {
            invoice.setRzhType("");
        } else {
            invoice.setRzhType(info.getLegalizeType());
        }
        // 校验码
        if (info.getCheckCode() == null || "".equals(info.getCheckCode())) {
            invoice.setCheckCode("");
        } else {
            invoice.setCheckCode(info.getCheckCode());
        }
        // 通行费标志
        if (info.getTxfbz() == null || "".equals(info.getTxfbz())) {
            invoice.setTxfbz("");
        } else {
            invoice.setTxfbz(info.getTxfbz());
        }
        // 零税率标志
        if (info.getLslbz() == null || "".equals(info.getLslbz())) {
            invoice.setLslbz("");
        } else {
            invoice.setLslbz(info.getLslbz());
        }

        invoice.setSfygx(info.getLegalizeState());
        if ("1".equals(info.getLegalizeState()) && !"4".equals(invoice.getRzlx())) {
            // 认证状态
            invoice.setRzhYesorno(info.getLegalizeState());
            // 认证日期
            if (info.getLegalizeDate() == null || "".equals(info.getLegalizeDate())) {
                invoice.setRzhDate(null);
            } else {
                invoice.setRzhDate(new SimpleDateFormat("yyyyMMdd").parse(info.getLegalizeDate()));
            }
            // 认证归属期
            if (info.getLegalizeBelongDate() == null || "".equals(info.getLegalizeBelongDate())) {
                invoice.setRzhBelongDate(null);
            } else {
                invoice.setRzhBelongDate(info.getLegalizeBelongDate());
            }
            invoice.setAuthStatus("4");
            invoice.setBdkStatus("1");
        } else {

            invoice.setAuthStatus("0");
        }
        if ("1".equals(info.getLegalizeState()) && "4".equals(invoice.getRzlx())) {
            // 认证状态
            invoice.setRzhYesorno("2");
            // 认证日期
            if (info.getLegalizeDate() == null || "".equals(info.getLegalizeDate())) {
                invoice.setRzhDate(null);
            } else {
                invoice.setRzhDate(new SimpleDateFormat("yyyyMMdd").parse(info.getLegalizeDate()));
            }
            // 认证归属期
            if (info.getLegalizeBelongDate() == null || "".equals(info.getLegalizeBelongDate())) {
                invoice.setRzhBelongDate(null);
            } else {
                invoice.setRzhBelongDate(info.getLegalizeBelongDate());
            }
            invoice.setAuthStatus("4");
            invoice.setBdkStatus("2");
        }
        invoice.setDetailYesorno(info.getDetailYesorno());
        invoice.setSourceSystem("2");
        invoice.setValid("1");
        invoice.setUuid(info.getUuid());
        invoice.setCreateDate(new Date());
        // 新增底账字段
        invoice.setPayee(info.getPayee());
        invoice.setReviewer(info.getReviewer());
        invoice.setPrintor(info.getPrintor());
        invoice.setIsSaleList(info.getIsSaleList());
        invoice.setIsRed(info.getIsRed());
        invoice.setBlueCode(info.getBlueCode());
        invoice.setBlueNo(info.getBlueNo());

        invoice.setSourceSystem("2");
        // 第一次插入添加票池采集字段
        invoice.setCollectStatus("1");
        invoice.setCollectFrom("1");
        invoice.setCollectDate(new Date());
        invoice.setPoolStatus("0");
        return invoice;
    }

    public Map<String, Object> getVehicleInfo(DataPlatformVehicleSaleInvoiceInfos info,
        TDxHttpLogDataPlatform tDxHttpLog) throws ParseException {

        TDxVehicleSaleInvoice vehicleSaleInvoice = new TDxVehicleSaleInvoice();
        TDxRecordEntity veinfo = null;
        if ("1".equals(tDxHttpLog.getSubject())) {
            veinfo = new TDxRecordEntity();
        }
        if ("2".equals(tDxHttpLog.getSubject())) {
            veinfo = new TDxSaleRecordInvoiceJobEntity();
        }
        veinfo.setInvoiceCode(info.getInvoiceCode());
        veinfo.setInvoiceNo(info.getInvoiceNo());
        veinfo.setInvoiceType(info.getInvoiceType());
        veinfo.setGfName(info.getBuyerName());
        veinfo.setInvoiceDate(new SimpleDateFormat("yyyy-MM-dd").parse(info.getInvoiceDate()));
        if (StringUtils.isBlank(info.getBuyerIdNo())) {
            vehicleSaleInvoice.setBuyerIdNum("");
        } else {
            vehicleSaleInvoice.setBuyerIdNum(info.getBuyerIdNo());
        }

        if (StringUtils.isBlank(info.getVehicleType())) {
            vehicleSaleInvoice.setVehicleType("");
        } else {
            vehicleSaleInvoice.setVehicleType(info.getVehicleType());
        }
        if (StringUtils.isBlank(info.getFactoryModel())) {
            vehicleSaleInvoice.setFactoryModel("");
        } else {
            vehicleSaleInvoice.setFactoryModel(info.getFactoryModel());
        }
        if (StringUtils.isBlank(info.getProductPlace())) {
            vehicleSaleInvoice.setProductPlace("");
        } else {
            vehicleSaleInvoice.setProductPlace(info.getProductPlace());
        }
        if (StringUtils.isBlank(info.getCertificate())) {
            vehicleSaleInvoice.setCertificate("");
        } else {
            vehicleSaleInvoice.setCertificate(info.getCertificate());
        }
        if (StringUtils.isBlank(info.getCertificateImprot())) {
            vehicleSaleInvoice.setCertificateImport("");
        } else {
            vehicleSaleInvoice.setCertificateImport(info.getCertificateImprot());
        }
        if (StringUtils.isBlank(info.getInspectionNo())) {
            vehicleSaleInvoice.setInspectionNum("");
        } else {
            vehicleSaleInvoice.setInspectionNum(info.getInspectionNo());
        }
        if (StringUtils.isBlank(info.getEngineNo())) {
            vehicleSaleInvoice.setEngineNo("");
        } else {
            vehicleSaleInvoice.setEngineNo(info.getEngineNo());
        }
        if (StringUtils.isBlank(info.getVehicleNo())) {
            vehicleSaleInvoice.setVehicleNo("");
        } else {
            vehicleSaleInvoice.setVehicleNo(info.getVehicleNo());
        }
        veinfo.setTotalAmount(new BigDecimal(info.getAllAmount()));
        veinfo.setXfName(info.getSellerName());
        if ("15".equals(info.getInvoiceType())) {
            veinfo.setXfTaxNo(info.getSellerIdNo());
            veinfo.setGfTaxNo(info.getBuyerIdNo());
        } else {
            veinfo.setXfTaxNo(info.getSellerTaxNo());
            veinfo.setGfTaxNo(info.getBuyerTaxNo());
        }
        if (StringUtils.isBlank(info.getSellerPhone())) {
            vehicleSaleInvoice.setPhone("");
        } else {
            vehicleSaleInvoice.setPhone(info.getSellerPhone());
        }
        if (StringUtils.isNotEmpty(info.getSellerAddress()) && StringUtils.isNotEmpty(info.getSellerPhone())) {
            veinfo.setXfAddressAndPhone(info.getSellerAddress() + info.getSellerPhone());
        }
        if (StringUtils.isNotEmpty(info.getSellerBank()) && StringUtils.isNotEmpty(info.getSellerAccount())) {
            veinfo.setXfBankAndNo(info.getSellerBank() + info.getSellerAccount());
        }
        vehicleSaleInvoice.setTaxRate(info.getTaxRate());
        veinfo.setTaxAmount(new BigDecimal(info.getTotalTaxAmount()));
        if (StringUtils.isBlank(info.getTaxBureauCode())) {
            vehicleSaleInvoice.setTaxBureauCode("");
        } else {
            vehicleSaleInvoice.setTaxBureauCode(info.getTaxBureauCode());
        }
        if (StringUtils.isBlank(info.getTaxBureauName())) {
            vehicleSaleInvoice.setTaxBureauName("");
        } else {
            vehicleSaleInvoice.setTaxBureauName(info.getTaxBureauName());
        }
        veinfo.setInvoiceAmount(new BigDecimal(info.getTotalAmount()));
        if (StringUtils.isBlank(info.getTaxRecords())) {
            vehicleSaleInvoice.setTaxRecords("");
        } else {
            vehicleSaleInvoice.setTaxRecords(info.getTaxRecords());
        }
        if (StringUtils.isBlank(info.getTonnage())) {
            vehicleSaleInvoice.setTonnage("");
        } else {
            vehicleSaleInvoice.setTonnage(info.getTonnage());
        }
        if (StringUtils.isBlank(info.getLimitPeople())) {
            vehicleSaleInvoice.setLimitPeople("");
        } else {
            vehicleSaleInvoice.setLimitPeople(info.getLimitPeople());
        }
        veinfo.setInvoiceStatus(info.getInvoiceState());
        veinfo.setRzhYesorno("0");
        // 认证类型
        if ("1".equals(info.getLegalizeState())) {
            veinfo.setRzlx("1");
        }
        if ("2".equals(info.getLegalizeState())) {
            veinfo.setRzlx("4");
        }
        if ("0".equals(info.getLegalizeState())) {
            veinfo.setRzlx(null);
        }
        if ("1".equals(info.getLegalizeState()) && !"4".equals(veinfo.getRzlx())) {
            veinfo.setAuthStatus("4");
            veinfo.setRzhYesorno(info.getLegalizeState());
            if ("".equals(info.getLegalizeBelongDate())) {
                veinfo.setRzhBelongDate(null);
            } else {
                veinfo.setRzhBelongDate(info.getLegalizeBelongDate());
            }
            if ("".equals(info.getLegalizeDate())) {
                veinfo.setRzhDate(null);
            } else {
                veinfo.setRzhDate(new SimpleDateFormat("yyyyMMdd").parse(info.getLegalizeDate()));
            }
            veinfo.setBdkStatus("1");
        } else {
            veinfo.setAuthStatus("0");
        }
        if ("1".equals(info.getLegalizeState()) && "4".equals(veinfo.getRzlx())) {
            veinfo.setAuthStatus("4");
            veinfo.setRzhYesorno("2");
            if ("".equals(info.getLegalizeBelongDate())) {
                veinfo.setRzhBelongDate(null);
            } else {
                veinfo.setRzhBelongDate(info.getLegalizeBelongDate());
            }
            if ("".equals(info.getLegalizeDate())) {
                veinfo.setRzhDate(null);
            } else {
                veinfo.setRzhDate(new SimpleDateFormat("yyyyMMdd").parse(info.getLegalizeDate()));
            }
            veinfo.setBdkStatus("2");
        }

        if ("".equals(info.getLegalizeType())) {
            veinfo.setRzhType(null);
        } else {
            veinfo.setRzhType(info.getLegalizeType());
        }
        veinfo.setPayee(info.getPayee());
        veinfo.setReviewer(info.getReviewer());
        veinfo.setPrintor(info.getPrintor());
        veinfo.setIsRed(info.getIsRed());
        veinfo.setBlueCode(info.getBlueCode());
        veinfo.setBlueNo(info.getBlueNo());
        veinfo.setSourceSystem("2");
        veinfo.setCreateDate(new Date());

        // 二手车明细表添加字段
        vehicleSaleInvoice.setPlateNo(info.getPlateNo());
        vehicleSaleInvoice.setRegistrationNo(info.getRegistrationNo());
        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());
        vehicleSaleInvoice.setGfPhone(info.getBuyerPhone());
        Map<String, Object> map = new HashMap<>(2);
        map.put("vehicleSaleInvoice", vehicleSaleInvoice);
        map.put("veinfo", veinfo);
        return map;
    }

    /**
     * 获取发票状态
     *
     * @param taxno
     *            书号
     * @param db
     *            数据库
     * @param type
     *            类型
     * @param params
     *            数据
     * @param company
     *            集团编码
     * @param aceId
     *            id
     * @param aceKey
     *            key
     * @param taxname
     *            名称
     *
     */
    @Override
    public void sendStateRequest(String taxno, String db, String taxname, String type, String params, String company,
        String aceId, String aceKey) {
        JSONObject globalParams = new JSONObject();
        // 生成数据交换流水号
        String exchangeId = getDataExchangeId();
        globalParams.put("zipCode", "0");
        globalParams.put("encryptCode", "0");
        globalParams.put("dataExchangeId", exchangeId);
        // 获取token
        String token = tokenService.getToken(aceId, aceKey);
        JSONObject content = new JSONObject();
        // 拼接业务报文
        try {
            // 记录获取token重试次数
            // 默认采集配置
            content.put("entName", taxname);
            content.put("taxNo", taxno);
            content.put("subject", type);
            // 获取开始日期-结束日期 --默认使用发票入库日期
            DynamicContextHolder.push(db + DbConstant.BUSINESS_READ);
            content.put("acquiStartDate", getBeginTimeState(taxno, type));
            content.put("acquiEndDate", getEndTime());
            globalParams.put("content", Base64.encode(content.toJSONString()));
            TDxHttpLogDataPlatform dataLog = new TDxHttpLogDataPlatform();
            dataLog.setTaxno(taxno);
            dataLog.setType("02");
            dataLog.setReqText(content.toString());
            // 得到返回报文，解析拿出返回的数量，累加用于判断数量
            dataLog.setReqDate(new Date());
            log.info("数据平台采集请求参数-" + content.toString());
            String responseJson = HttpUtil.post(collectStateUrl + token, globalParams.toString(), 60000);
            log.info("数据平台采集返回报文-" + responseJson);
            dataLog.setResDate(new Date());
            dataLog.setResText(responseJson);
            dataLog.setStatus("0");
            // 判断token是否过期
            JSONObject ob = JSONObject.parseObject(responseJson);
            dataLog.setResText(responseJson);
            dataLog.setStatus("0");
            dataLog.setCompany(company);
            dataLog.setSubject(type);
            DynamicContextHolder.push(db + DbConstant.BUSINESS_WRITE);
            dataPlatformDao.insert(dataLog);
            if (ob != null) {
                String returnStateInfo = ob.getString("returnStateInfo");
                JSONObject returnState = JSONObject.parseObject(returnStateInfo);
                String code = returnState.getString("returnCode");
                if ("0000".equals(code)) {
                    // 获取返回总条数判断是否需要继续请求
                    String returnContent = ob.getString("content");
                    if (returnContent != null) {
                        JSONObject invoices = JSONObject.parseObject(Base64.decodeStr(returnContent));
                        String code1 = invoices.getString("code");
                        // 判断内层报文是否成功
                        if ("0000".equals(code1)) {
                            parseState(invoices, db, dataLog);
                        }
                    }
                }
            }
        } catch (Exception e) {
           log.info("业务处理异常：{}", e);
        }
    }

    private String getBeginTimeState(String taxno, String type) {
        String lastTime = dataPlatformDao.selectLastInvoiceDateState(taxno, type);
        if (lastTime == null || "".equals(lastTime)) {
            // 读取数据库配置
            DynamicContextHolder.push(DbConstant.BASICS_READ);
            lastTime = dataPlatformDao.getFirstCollectDate(taxno);
        } else {
            // 避免防止漏票，提前一小时
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
            try {
                Date date = simpleDateFormat.parse(lastTime);
                Calendar cal = Calendar.getInstance();
                cal.setTime(date);
                date = cal.getTime();
                lastTime = simpleDateFormat.format(date);
            } catch (ParseException e) {
               log.info("业务处理异常：{}", e);
            }
        }

        return lastTime;
    }

    private void parseState(JSONObject invoices, String db, TDxHttpLogDataPlatform dataLog) {
        // 解析报文
        JSONArray arr = invoices.getJSONArray("data");
        DynamicContextHolder.push(db + DbConstant.BUSINESS_WRITE);
        if (arr.size() > 0) {
            for (int i = 0; i < arr.size(); i++) {
                JSONObject obj = arr.getJSONObject(i);
                DataPlatformInvoiceInfo info = obj.toJavaObject(DataPlatformInvoiceInfo.class);
                info.setUuid(info.getInvoiceCode() + info.getInvoiceNo());
                String rzlx = "";
                // 获取数据库状态

                TDxRecordInvoice invoice = null;
                if ("1".equals(dataLog.getSubject())) {
                    invoice = tDxRecordInvoiceJobDao.findInvoiceByCodeAndNo(info.getInvoiceCode(), info.getInvoiceNo());
                }
                if ("2".equals(dataLog.getSubject())) {
                    invoice =
                        tDxRecordInvoiceJobDao.findSaleInvoiceByCodeAndNo(info.getInvoiceCode(), info.getInvoiceNo());
                }
                if (invoice != null) {
                    info.setInvoiceState(this.exchangeInvoiceStatus(info.getInvoiceState()));
                    if (!invoice.getInvoiceStatus().equals(info.getInvoiceState())) {

                        if ("1".equals(dataLog.getSubject())) {
                            dataPlatformDao.updateState(info);
                        }
                        if ("2".equals(dataLog.getSubject())) {
                            dataPlatformDao.updateSaleState(info);
                        }
                    }
                }
            }
        } else {
            dataLog.setStatus("1");
            dataLog.setTotal("0");
            dataPlatformDao.updateHttpLogById(dataLog);
        }
    }

    @Override
    public List<String> getNeedParseTaxno() {

        return dataPlatformDao.getNeedParseTaxno();
    }

    @Override
    public List<TDxHttpLogDataPlatform> getHttpLogsByTaxno(String taxno) {
        return dataPlatformDao.getHttpLogsByTaxno(taxno);
    }
    private String exchangeInvoiceStatus(String invoiceState) {

        if (StringUtils.isNotEmpty(invoiceState)) {
            switch (invoiceState) {
                case "1":
                    return "0";
                case "8":
                    return "1";
                case "9":
                    return "4";
            }
        }
        return invoiceState;
    }
}
