package com.dxhy.erp.service.impl;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.dxhy.api.model.config.sys.SysEnterpriseConfigDto;
import com.dxhy.api.model.db.*;
import com.dxhy.api.model.invoice.TDxRecordInvoice;
import com.dxhy.common.constant.DbConstant;
import com.dxhy.common.datasource.config.DynamicContextHolder;
import com.dxhy.common.enums.ReturnCodeEnum;
import com.dxhy.common.util.pojo.Authorize;
import com.dxhy.common.util.pojo.GlobalInfo;
import com.dxhy.common.utils.CommonUtil;
import com.dxhy.common.utils.DateUtils;
import com.dxhy.erp.dao.*;
import com.dxhy.erp.entity.*;
import com.dxhy.erp.model.InvoiceDetailInfo;
import com.dxhy.erp.model.ReturnStateInfo;
import com.dxhy.erp.model.State;
import com.dxhy.erp.model.VehicleSaleInvoices;
import com.dxhy.erp.model.auth.InterfaceCode;
import com.dxhy.erp.service.InvoicePoolService;
import com.dxhy.erp.utils.CheckUtils;
import com.dxhy.jxpt.baseService.dao.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author dxhy
 */
@SuppressWarnings({"AlibabaUndefineMagicConstant", "AlibabaMethodTooLong"})
@Service("invoicePoolService")
@Slf4j
public class InvoicePoolServiceImpl implements InvoicePoolService {

    @Autowired
    private InvoicePoolDao invoicePoolDao;
    @Autowired
    private TdxRecordTspzKzxxDao tdxRecordTspzKzxxDao;
    @Autowired
    private SysEnterpriseConfigErpDao enterpriseConfigErpDao;

    @Autowired
    SalesInvoiceDetailDao salesInvoiceDetailDao;

    @Autowired
    VehicleSaleInvoiceDao vehicleSaleInvoiceDao;

    @Autowired
    TdxSaleRecordInvoiceDao tdxSaleRecordInvoiceDao;

    @Autowired
    TDxInvoiceSaleDao tDxInvoiceSaleDao;

    @Resource
    private TdxTdysMhxcdCoreDao tdxTdysMhxcdCoreDao;
    @Resource
    private TdxTdysMhxcdMxCoreDao tdxTdysMhxcdMxCoreDao;
    @Resource
    private TdxTdysTldzkpCoreDao tdxTdysTldzkpCoreDao;

    @Value("${pool.collectNum}")
    private String poolCollectNum;
    @Value("${pool.stateNum}")
    private String poolStateNum;
    @Value("${pool.imageUrl}")
    private String imageUrl;

    /**
     * 入账业务
     *
     * @param globalInfo
     * @param requestParam
     * @param request
     * @param response
     * @param authorize
     * @return
     */
    @Override
    public String inAccount(GlobalInfo globalInfo, Map<String, String> requestParam, HttpServletRequest request,
        HttpServletResponse response, Authorize authorize) {
        ReturnStateInfo run = new ReturnStateInfo();
        InterfaceCode interfaceCode = new InterfaceCode();
        InAccountEntity inAccountEntity = null;
        try {
            inAccountEntity = JSONObject.parseObject(requestParam.get("data"), InAccountEntity.class);
        } catch (Exception e) {
            run.setReturnCode(ReturnCodeEnum.QQBWGSCW.getFhzDm());
            run.setReturnMessage(ReturnCodeEnum.QQBWGSCW.getFhzMc(ReturnCodeEnum.QQBWGSCW.getIndex()));
            interfaceCode.setGlobalInfo(globalInfo);
            interfaceCode.setReturnStateInfo(run);
            interfaceCode.setData("");
            return JSONObject.toJSONString(interfaceCode, SerializerFeature.WriteMapNullValue);
        }
        try {

            if (StringUtils.isBlank(inAccountEntity.getBuyerTaxNo())) {
                run.setReturnCode(ReturnCodeEnum.SHBNWK.getFhzDm());
                run.setReturnMessage(ReturnCodeEnum.SHBNWK.getFhzMc(ReturnCodeEnum.SHBNWK.getIndex()));
                interfaceCode.setGlobalInfo(globalInfo);
                interfaceCode.setReturnStateInfo(run);
                interfaceCode.setData("");
                return JSONObject.toJSONString(interfaceCode, SerializerFeature.WriteMapNullValue);
            }
            DynamicContextHolder.push(DbConstant.BASICS_READ);
            SysEnterpriseConfigDto deptEntity = enterpriseConfigErpDao.getOrg(inAccountEntity.getBuyerTaxNo());
            String dbName = null;
            if (deptEntity != null && deptEntity.getDbName() != null) {
                dbName = deptEntity.getDbName();
            } else {
                ReturnStateInfo runInfo = new ReturnStateInfo();
                runInfo.setReturnCode(ReturnCodeEnum.JTSHBF.getFhzDm());
                runInfo.setReturnMessage(ReturnCodeEnum.JTSHBF.getFhzMc(ReturnCodeEnum.JTSHBF.getIndex()));
                interfaceCode.setGlobalInfo(globalInfo);
                interfaceCode.setReturnStateInfo(runInfo);
                interfaceCode.setData("");
                return JSON.toJSONString(interfaceCode);
            }
            if (StringUtils.isBlank(inAccountEntity.getBatchNo()) || inAccountEntity.getContentRows() == null) {
                run.setReturnCode(ReturnCodeEnum.PCHBNWK.getFhzDm());
                run.setReturnMessage(ReturnCodeEnum.PCHBNWK.getFhzMc(ReturnCodeEnum.PCHBNWK.getIndex()));
                interfaceCode.setGlobalInfo(globalInfo);
                interfaceCode.setReturnStateInfo(run);
                interfaceCode.setData("");
                return JSONObject.toJSONString(interfaceCode, SerializerFeature.WriteMapNullValue);
            }
            DynamicContextHolder.push(dbName + DbConstant.BUSINESS_READ);
            // 判断批次号是否申请过
            int batChCount = invoicePoolDao.countBatChno(inAccountEntity.getBatchNo());
            if (batChCount > 0) {
                run.setReturnCode("9999");
                run.setReturnMessage("批次号已存在");
                interfaceCode.setReturnStateInfo(run);
                interfaceCode.setGlobalInfo(globalInfo);
                interfaceCode.setData("");
                return JSONObject.toJSONString(interfaceCode, SerializerFeature.WriteMapNullValue);
            }
            List<InAccountData> inAccountList = inAccountEntity.getInvoices();
            if (inAccountList.size() != inAccountEntity.getContentRows()) {
                run.setReturnCode(ReturnCodeEnum.NRYCY.getFhzDm());
                run.setReturnMessage(ReturnCodeEnum.NRYCY.getFhzMc(ReturnCodeEnum.NRYCY.getIndex()));
                interfaceCode.setReturnStateInfo(run);
                interfaceCode.setGlobalInfo(globalInfo);
                interfaceCode.setData("");
                return JSONObject.toJSONString(interfaceCode, SerializerFeature.WriteMapNullValue);
            }
            List<InAccountData> accountReturnList = new ArrayList<>();
            for (InAccountData inAccountData : inAccountList) {
//                if (StringUtils.isBlank(inAccountData.getInvoiceCode())
//                    || StringUtils.isBlank(inAccountData.getInvoiceNo())) {
//                    inAccountData.setStatus("1");
//                    inAccountData.setFailureReason("9");
//                    accountReturnList.add(inAccountData);
//                    continue;
//                }
                if (StringUtils.isBlank(inAccountData.getInvoiceNo())) {
                    inAccountData.setStatus("1");
                    inAccountData.setFailureReason("9");
                    accountReturnList.add(inAccountData);
                    continue;
                }
                if(StringUtils.isBlank(inAccountData.getInvoiceCode())){
                    inAccountData.setUuid(inAccountData.getInvoiceNo());
                }else {
                    inAccountData.setUuid(inAccountData.getInvoiceCode() + inAccountData.getInvoiceNo());
                }
                if (StringUtils.isBlank(inAccountData.getInAccountStatus())) {
                    inAccountData.setStatus("1");
                    inAccountData.setFailureReason("3");
                    accountReturnList.add(inAccountData);
                    continue;
                }
                if (!"1".equals(inAccountData.getInAccountStatus())
                    && !"0".equals(inAccountData.getInAccountStatus())) {
                    inAccountData.setStatus("1");
                    inAccountData.setFailureReason("13");
                    accountReturnList.add(inAccountData);
                    continue;
                }
                // 是否入账为1时，校验字段非空
                if ("1".equals(inAccountData.getInAccountStatus())) {
                    if (StringUtils.isBlank(inAccountData.getInAccountDate())
                        || (!CheckUtils.stringLength(inAccountData.getInAccountDate(), 14))) {
                        inAccountData.setStatus("1");
                        inAccountData.setFailureReason("4");
                        accountReturnList.add(inAccountData);
                        continue;
                    }
                    if (StringUtils.isBlank(inAccountData.getVoucherNumber())) {
                        inAccountData.setStatus("1");
                        inAccountData.setFailureReason("5");
                        accountReturnList.add(inAccountData);
                        continue;
                    }
                    if (StringUtils.isBlank(inAccountData.getDocumentNumber())) {
                        inAccountData.setStatus("1");
                        inAccountData.setFailureReason("6");
                        accountReturnList.add(inAccountData);
                        continue;
                    }
                } else {
                    inAccountData.setInAccountDate("");
                }
                // 判断抵帐表是否有票
                JSONObject recordJson = invoicePoolDao.getRecordJson(inAccountData.getUuid());
                if (recordJson == null) {
                    log.info("线程{},抵账无此票{}", Thread.currentThread().getId(), inAccountData.getUuid());
                    inAccountData.setStatus("1");
                    inAccountData.setFailureReason("2");
                } else {
                    DynamicContextHolder.push(dbName + DbConstant.BUSINESS_WRITE);
                    int updateResult = invoicePoolDao.updateRecAccount(inAccountData);
                    if (updateResult > 0) {
                        inAccountData.setStatus("0");
                        inAccountData.setFailureReason("");
                        log.info("线程{},入账完成{}", Thread.currentThread().getId(), inAccountData.getUuid());
                    } else {
                        inAccountData.setStatus("1");
                        inAccountData.setFailureReason("99");
                        log.info("线程{},入账异常{}", Thread.currentThread().getId(), inAccountData.getUuid());
                    }
                }
                accountReturnList.add(inAccountData);
            }
            invoicePoolDao.saveAccountBat(accountReturnList, inAccountEntity.getBatchNo());
            // 返回报文拼接
            String data = this.returnPar(accountReturnList, inAccountEntity);
            run.setReturnCode(ReturnCodeEnum.CLCG.getFhzDm());
            run.setReturnMessage(ReturnCodeEnum.CLCG.getFhzMc(ReturnCodeEnum.CLCG.getIndex()));
            interfaceCode.setReturnStateInfo(run);
            interfaceCode.setGlobalInfo(globalInfo);
            interfaceCode.setData(Base64.encode(data));
            return JSONObject.toJSONString(interfaceCode, SerializerFeature.WriteMapNullValue);
        } catch (Exception e) {
           log.info("业务处理异常：{}", e);
            run.setReturnCode(ReturnCodeEnum.CLSB.getFhzDm());
            run.setReturnMessage(ReturnCodeEnum.CLSB.getFhzMc(ReturnCodeEnum.CLSB.getIndex()));
            interfaceCode.setReturnStateInfo(run);
            interfaceCode.setGlobalInfo(globalInfo);
            interfaceCode.setData("");
            return JSONObject.toJSONString(interfaceCode, SerializerFeature.WriteMapNullValue);
        }
    }

    private String returnPar(List<InAccountData> inAccountList, InAccountEntity inAccountEntity) {
        InAccountEntity retEntity = new InAccountEntity();
        List<InAccountData> accList = new ArrayList<>();
        for (InAccountData inAccountData : inAccountList) {
            InAccountData accData = new InAccountData();
            accData.setInvoiceCode(inAccountData.getInvoiceCode());
            accData.setInvoiceNo(inAccountData.getInvoiceNo());
            accData.setStatus(inAccountData.getStatus());
            accData.setFailureReason(inAccountData.getFailureReason());
            accList.add(accData);
        }
        retEntity.setBatchNo(inAccountEntity.getBatchNo());
        retEntity.setBuyerTaxNo(inAccountEntity.getBuyerTaxNo());
        retEntity.setInvoices(accList);
        String data = JSON.toJSONString(retEntity);
        log.info("线程{},入账结果信息{}", Thread.currentThread().getId(), data);
        return data;
    }

    /**
     * 摊销业务
     *
     * @param globalInfo
     * @param requestParam
     * @param request
     * @param response
     * @param authorize
     * @return
     */
    @Override
    public String amortize(GlobalInfo globalInfo, Map<String, String> requestParam, HttpServletRequest request,
        HttpServletResponse response, Authorize authorize) {
        ReturnStateInfo run = new ReturnStateInfo();
        InterfaceCode interfaceCode = new InterfaceCode();
        AmortizeEntity amortizeEntity = null;
        try {
            amortizeEntity = JSONObject.parseObject(requestParam.get("data"), AmortizeEntity.class);
        } catch (Exception e) {
            run.setReturnCode(ReturnCodeEnum.QQBWGSCW.getFhzDm());
            run.setReturnMessage(ReturnCodeEnum.QQBWGSCW.getFhzMc(ReturnCodeEnum.QQBWGSCW.getIndex()));
            interfaceCode.setGlobalInfo(globalInfo);
            interfaceCode.setReturnStateInfo(run);
            interfaceCode.setData("");
            return JSONObject.toJSONString(interfaceCode, SerializerFeature.WriteMapNullValue);
        }
        try {

            if (StringUtils.isBlank(amortizeEntity.getBuyerTaxNo())) {
                run.setReturnCode(ReturnCodeEnum.SHBNWK.getFhzDm());
                run.setReturnMessage(ReturnCodeEnum.SHBNWK.getFhzMc(ReturnCodeEnum.SHBNWK.getIndex()));
                interfaceCode.setGlobalInfo(globalInfo);
                interfaceCode.setReturnStateInfo(run);
                interfaceCode.setData("");
                return JSONObject.toJSONString(interfaceCode, SerializerFeature.WriteMapNullValue);
            }
            DynamicContextHolder.push(DbConstant.BASICS_READ);
            SysEnterpriseConfigDto deptEntity = enterpriseConfigErpDao.getOrg(amortizeEntity.getBuyerTaxNo());
            String dbName = null;
            if (deptEntity != null && deptEntity.getDbName() != null) {
                dbName = deptEntity.getDbName();
            } else {
                ReturnStateInfo runInfo = new ReturnStateInfo();
                runInfo.setReturnCode(ReturnCodeEnum.JTSHBF.getFhzDm());
                runInfo.setReturnMessage(ReturnCodeEnum.JTSHBF.getFhzMc(ReturnCodeEnum.JTSHBF.getIndex()));
                interfaceCode.setGlobalInfo(globalInfo);
                interfaceCode.setReturnStateInfo(runInfo);
                interfaceCode.setData("");
                return JSON.toJSONString(interfaceCode);
            }
            if (StringUtils.isBlank(amortizeEntity.getBatchNo()) || amortizeEntity.getContentRows() == null) {
                run.setReturnCode(ReturnCodeEnum.PCHBNWK.getFhzDm());
                run.setReturnMessage(ReturnCodeEnum.PCHBNWK.getFhzMc(ReturnCodeEnum.PCHBNWK.getIndex()));
                interfaceCode.setGlobalInfo(globalInfo);
                interfaceCode.setReturnStateInfo(run);
                interfaceCode.setData("");
                return JSONObject.toJSONString(interfaceCode, SerializerFeature.WriteMapNullValue);
            }
            DynamicContextHolder.push(dbName + DbConstant.BUSINESS_READ);
            // 判断批次号是否申请过
            int batChCount = invoicePoolDao.countAmortizeBatChno(amortizeEntity.getBatchNo());
            if (batChCount > 0) {
                run.setReturnCode("9999");
                run.setReturnMessage("批次号已存在");
                interfaceCode.setReturnStateInfo(run);
                interfaceCode.setGlobalInfo(globalInfo);
                interfaceCode.setData("");
                return JSONObject.toJSONString(interfaceCode, SerializerFeature.WriteMapNullValue);
            }
            List<AmortizeData> inAccountList = amortizeEntity.getInvoices();
            if (inAccountList.size() != amortizeEntity.getContentRows()) {
                run.setReturnCode(ReturnCodeEnum.NRYCY.getFhzDm());
                run.setReturnMessage(ReturnCodeEnum.NRYCY.getFhzMc(ReturnCodeEnum.NRYCY.getIndex()));
                interfaceCode.setReturnStateInfo(run);
                interfaceCode.setGlobalInfo(globalInfo);
                interfaceCode.setData("");
                return JSONObject.toJSONString(interfaceCode, SerializerFeature.WriteMapNullValue);
            }
            List<AmortizeData> amortizeReturnList = new ArrayList<>();
            for (AmortizeData amortizeData : inAccountList) {
                BigDecimal remAmortizeAmount = null;
//                if (StringUtils.isBlank(amortizeData.getInvoiceCode())
//                    || StringUtils.isBlank(amortizeData.getInvoiceNo())) {
//                    amortizeData.setStatus("1");
//                    amortizeData.setFailureReason("9");
//                    amortizeReturnList.add(amortizeData);
//                    continue;
//                }
                if (StringUtils.isBlank(amortizeData.getInvoiceNo())) {
                    amortizeData.setStatus("1");
                    amortizeData.setFailureReason("9");
                    amortizeReturnList.add(amortizeData);
                    continue;
                }
                if(StringUtils.isBlank(amortizeData.getInvoiceCode())){
                    amortizeData.setUuid(amortizeData.getInvoiceNo());
                }else {
                    amortizeData.setUuid(amortizeData.getInvoiceCode() + amortizeData.getInvoiceNo());
                }
                if (StringUtils.isBlank(amortizeData.getAmortizeStatus())) {
                    amortizeData.setStatus("1");
                    amortizeData.setFailureReason("7");
                    amortizeReturnList.add(amortizeData);
                    continue;
                }
                if (!"0".equals(amortizeData.getAmortizeStatus()) && !"1".equals(amortizeData.getAmortizeStatus())) {
                    amortizeData.setStatus("1");
                    amortizeData.setFailureReason("14");
                    amortizeReturnList.add(amortizeData);
                    continue;
                }
                if (StringUtils.isBlank(amortizeData.getDocumentNumber())) {
                    amortizeData.setStatus("1");
                    amortizeData.setFailureReason("6");
                    amortizeReturnList.add(amortizeData);
                    continue;
                }
//                int documentNoCount = invoicePoolDao.countDocumentNo(
//                    amortizeData.getInvoiceCode() + amortizeData.getInvoiceNo(), amortizeData.getDocumentNumber());
                int documentNoCount = invoicePoolDao.countDocumentNo(amortizeData.getUuid(), amortizeData.getDocumentNumber());
                if (documentNoCount > 0) {
                    amortizeData.setStatus("1");
                    amortizeData.setFailureReason("15");
                    amortizeReturnList.add(amortizeData);
                    continue;
                }
                if (StringUtils.isBlank(amortizeData.getAmortizeAmount())) {
                    amortizeData.setStatus("1");
                    amortizeData.setFailureReason("8");
                    amortizeReturnList.add(amortizeData);
                    continue;
                }
                try {
                    if (new BigDecimal(amortizeData.getAmortizeAmount()).compareTo(new BigDecimal(0)) == -1) {
                        amortizeData.setStatus("1");
                        amortizeData.setFailureReason("17");
                        amortizeReturnList.add(amortizeData);
                        continue;
                    }
                } catch (Exception e) {
                    amortizeData.setStatus("1");
                    amortizeData.setFailureReason("17");
                    amortizeReturnList.add(amortizeData);
                    continue;
                }

                if (StringUtils.isBlank(amortizeData.getAmortizeUser())) {
                    amortizeData.setStatus("1");
                    amortizeData.setFailureReason("16");
                    amortizeReturnList.add(amortizeData);
                    continue;
                }

                // 判断抵帐表是否有票
                JSONObject recordJson = invoicePoolDao.getRecordJson(amortizeData.getUuid());
                if (recordJson == null) {
                    log.info("线程{},抵账无此票{}", Thread.currentThread().getId(), amortizeData.getUuid());
                    amortizeData.setStatus("1");
                    amortizeData.setFailureReason("2");
                } else {
                    // 末次摊销完成，再次摊销返回失败 该票已末次摊销完成。
                    if ("1".equals(recordJson.getString("amortize_status"))) {
                        amortizeData.setStatus("1");
                        amortizeData.setFailureReason("10");
                        amortizeReturnList.add(amortizeData);
                        continue;
                    }
                    // 计算摊销剩余金额
                    if (recordJson.getString("remain_amortize_amount") == null) {
                        remAmortizeAmount = new BigDecimal(recordJson.getString("invoice_amount"))
                            .subtract(new BigDecimal(amortizeData.getAmortizeAmount()));
                    } else {
                        remAmortizeAmount = new BigDecimal(recordJson.getString("remain_amortize_amount"))
                            .subtract(new BigDecimal(amortizeData.getAmortizeAmount()));
                    }
                    if (remAmortizeAmount.compareTo(new BigDecimal(0)) == -1) {
                        log.info("线程{},发票{},剩余摊销金额{}", Thread.currentThread().getId(), amortizeData.getUuid(),
                            remAmortizeAmount);
                        amortizeData.setStatus("1");
                        amortizeData.setFailureReason("11");
                        amortizeReturnList.add(amortizeData);
                        continue;
                    } else {
                        amortizeData.setRemainAmortizeAmount(remAmortizeAmount.toString());
                        if (remAmortizeAmount.compareTo(new BigDecimal(0)) == 0) {
                            amortizeData.setOverStatus("1");
                        }
                    }
                    String documentNo = amortizeData.getDocumentNumber();
                    if (recordJson.getString("amortize_document_number") != null) {
                        amortizeData.setDocumentNumber(
                            recordJson.getString("amortize_document_number") + "," + amortizeData.getDocumentNumber());
                    }
                    DynamicContextHolder.push(dbName + DbConstant.BUSINESS_WRITE);
                    int updateResult = invoicePoolDao.updateRecAmortize(amortizeData);
                    amortizeData.setDocumentNumber(documentNo);
                    if (updateResult > 0) {
                        amortizeData.setStatus("0");
                        amortizeData.setFailureReason("");
                        log.info("线程{},摊销完成{}", Thread.currentThread().getId(), amortizeData.getUuid());
                    } else {
                        amortizeData.setStatus("1");
                        amortizeData.setFailureReason("99");
                        log.info("线程{},摊销异常{}", Thread.currentThread().getId(), amortizeData.getUuid());
                    }
                }
                amortizeReturnList.add(amortizeData);
            }
            invoicePoolDao.saveAmortizeBat(amortizeReturnList, amortizeEntity.getBatchNo());
            // 返回报文拼接
            String data = this.returnAmortizePar(amortizeReturnList, amortizeEntity);
            run.setReturnCode(ReturnCodeEnum.CLCG.getFhzDm());
            run.setReturnMessage(ReturnCodeEnum.CLCG.getFhzMc(ReturnCodeEnum.CLCG.getIndex()));
            interfaceCode.setReturnStateInfo(run);
            interfaceCode.setGlobalInfo(globalInfo);
            interfaceCode.setData(Base64.encode(data));
            return JSONObject.toJSONString(interfaceCode, SerializerFeature.WriteMapNullValue);
        } catch (Exception e) {
           log.info("业务处理异常：{}", e);
            run.setReturnCode(ReturnCodeEnum.CLSB.getFhzDm());
            run.setReturnMessage(ReturnCodeEnum.CLSB.getFhzMc(ReturnCodeEnum.CLSB.getIndex()));
            interfaceCode.setReturnStateInfo(run);
            interfaceCode.setGlobalInfo(globalInfo);
            interfaceCode.setData("");
            return JSONObject.toJSONString(interfaceCode, SerializerFeature.WriteMapNullValue);
        }
    }

    private String returnAmortizePar(List<AmortizeData> amortizeReturnList, AmortizeEntity amortizeEntity) {
        AmortizeEntity retEntity = new AmortizeEntity();
        List<AmortizeData> amorList = new ArrayList<>();
        for (AmortizeData amorData : amortizeReturnList) {
            AmortizeData amortizeData = new AmortizeData();
            amortizeData.setInvoiceCode(amorData.getInvoiceCode());
            amortizeData.setInvoiceNo(amorData.getInvoiceNo());
            amortizeData.setStatus(amorData.getStatus());
            amortizeData.setFailureReason(amorData.getFailureReason());
            amorList.add(amortizeData);
        }
        retEntity.setBatchNo(amortizeEntity.getBatchNo());
        retEntity.setBuyerTaxNo(amortizeEntity.getBuyerTaxNo());
        retEntity.setInvoices(amorList);
        String data = JSON.toJSONString(retEntity);
        log.info("线程{},摊销结果信息{}", Thread.currentThread().getId(), data);
        return data;
    }

    /**
     * 票池采集业务
     *
     * @param globalInfo
     * @param map
     * @param request
     * @param response
     * @param authorize
     * @return
     */
    @Override
    public String listInvoice(GlobalInfo globalInfo, Map<String, String> map, HttpServletRequest request,
        HttpServletResponse response, Authorize authorize) {
        ReturnStateInfo run = new ReturnStateInfo();
        InterfaceCode interfaceCode = new InterfaceCode();
        PoolCollectPo data = null;
        List<TDxRecordInvoice> list = null;
        List<InvoiceDetailInfo> detailList = null;
        List<VehicleSaleInvoices> vehicleList = null;

        // 01回传信息
        List<InvoicePoolInfo> invoices = new ArrayList<>();
        // 03机动车回传信息
        List<VehicleSaleInvoicePoolInfos> vehicleInvoiceInfos = new ArrayList<>();
        // 15二手车回传
        List<UserdCarEntity> userdCar = new ArrayList<>();
        try {
            data = JSON.parseObject(map.get("data"), PoolCollectPo.class);
        } catch (Exception e) {
            run.setReturnCode(ReturnCodeEnum.QQBWGSCW.getFhzDm());
            run.setReturnMessage(ReturnCodeEnum.QQBWGSCW.getFhzMc(ReturnCodeEnum.QQBWGSCW.getIndex()));
            interfaceCode.setGlobalInfo(globalInfo);
            interfaceCode.setReturnStateInfo(run);
            return JSON.toJSONString(interfaceCode);
        }
        try {
            run = getCheck(data);
            if (run.getReturnCode() != null || run.getReturnMessage() != null) {
                interfaceCode.setGlobalInfo(globalInfo);
                interfaceCode.setReturnStateInfo(run);
                return JSON.toJSONString(interfaceCode);
            }
            DynamicContextHolder.push(DbConstant.BASICS_READ);
            SysEnterpriseConfigDto deptEntity = enterpriseConfigErpDao.getOrg(data.getTaxNo());
            String dbName = null;
            if (deptEntity != null && deptEntity.getDbName() != null) {
                dbName = deptEntity.getDbName();
            } else {
                run.setReturnCode(ReturnCodeEnum.JTSHBF.getFhzDm());
                run.setReturnMessage(ReturnCodeEnum.JTSHBF.getFhzMc(ReturnCodeEnum.JTSHBF.getIndex()));
                interfaceCode.setGlobalInfo(globalInfo);
                interfaceCode.setReturnStateInfo(run);
                return JSON.toJSONString(interfaceCode);
            }
            Integer total = null;
            // 数据类型 1-进项 2-进项
            if ("1".equals(data.getDataType()) || "2".equals(data.getDataType())) {
                DynamicContextHolder.push(dbName + DbConstant.BUSINESS_READ);
                total = invoicePoolDao.countBuyerInvoice(data);
                log.info("线程{},请求参数{},采集总数{}", Thread.currentThread().getId(), data, total);
                int mxsize = 0;
                int startRow = data.getStartRow();

                boolean continueQuery = true;
                while (continueQuery && mxsize < Integer.parseInt(poolCollectNum) && invoices.size() < total
                    && startRow <= total) {
                    DynamicContextHolder.push(dbName + DbConstant.BUSINESS_READ);
                    list = invoicePoolDao.listBuyerInvoice(data, startRow - 1, 100);
                    log.info("线程{},发票数据获取完成{},{}", Thread.currentThread().getId(), data.getTaxNo(), startRow);
                    startRow += 100;
                    for (TDxRecordInvoice info : list) {
                        String uuid = (StringUtils.isBlank(info.getInvoiceCode())?"":info.getInvoiceCode()) + info.getInvoiceNo();
                        if ("03".equals(info.getInvoiceType())||"187".equals(info.getInvoiceType())||"383".equals(info.getInvoiceType())) {
                            //机动车
                            vehicleList = invoicePoolDao.selectVehicle(data.getDataType(), uuid);
                            if (vehicleList != null && vehicleList.size() > 0) {
                                mxsize += vehicleList.size();
                                for (VehicleSaleInvoices vehicle : vehicleList) {
                                    VehicleSaleInvoicePoolInfos vehicleInfo = getVehicleInfo(vehicle, info);
                                    vehicleInvoiceInfos.add(vehicleInfo);
                                }
                                if (mxsize > Integer.parseInt(poolCollectNum)) {
                                    continueQuery = false;
                                    break;
                                }
                            }
                        } else if ("15".equals(info.getInvoiceType())||"188".equals(info.getInvoiceType())||"184".equals(info.getInvoiceType())) {
                            //二手车
                            vehicleList = invoicePoolDao.selectVehicle(data.getDataType(), uuid);
                            if (vehicleList != null && vehicleList.size() > 0) {
                                mxsize += vehicleList.size();
                                for (VehicleSaleInvoices vehicle : vehicleList) {
                                    UserdCarEntity userdCarEntity = getUserdCarInfo(vehicle, info);
                                    userdCar.add(userdCarEntity);
                                }
                                if (mxsize > Integer.parseInt(poolCollectNum)) {
                                    continueQuery = false;
                                    break;
                                }
                            }
                        } else if ("161".equals(info.getInvoiceType()))  {
                            //数电票，航空客运
                            // 转换发票实体
                            InvoicePoolInfo invoiceInfo = this.getInvoiceInfo(info);

                            TdxTdysMhxcdEntity tdxTdysMhxcdEntity = tdxTdysMhxcdCoreDao.selectOne(new LambdaQueryWrapper<TdxTdysMhxcdEntity>().eq(TdxTdysMhxcdEntity::getUuid, uuid));
                            if(ObjectUtil.isNotEmpty(tdxTdysMhxcdEntity)){
                                tdxTdysMhxcdEntity.setCreateTime(null);
                                tdxTdysMhxcdEntity.setId(null);
                                tdxTdysMhxcdEntity.setUuid(null);
                                invoiceInfo.setMhxcd(tdxTdysMhxcdEntity);
                            }
                            List<TdxTdysMhxcdMxEntity> tdxTdysMhxcdMxEntities = tdxTdysMhxcdMxCoreDao.selectList(new LambdaQueryWrapper<TdxTdysMhxcdMxEntity>().eq(TdxTdysMhxcdMxEntity::getTdysId, uuid));
                            if(!CollectionUtils.isEmpty(tdxTdysMhxcdMxEntities)){
                                for (TdxTdysMhxcdMxEntity tdxTdysMhxcdMxEntity : tdxTdysMhxcdMxEntities) {
                                    tdxTdysMhxcdMxEntity.setCreateTime(null);
                                    tdxTdysMhxcdMxEntity.setId(null);
                                    tdxTdysMhxcdMxEntity.setTdysId(null);
                                }
                                invoiceInfo.setMhxcdMx(tdxTdysMhxcdMxEntities);
                            }
                            invoices.add(invoiceInfo);

                            if (mxsize >= Integer.parseInt(poolCollectNum)) {
                                continueQuery = false;
                                break;
                            }
                        } else if ("283".equals(info.getInvoiceType()))  {
                            //数电票，铁路
                            // 转换发票实体
                            InvoicePoolInfo invoiceInfo = this.getInvoiceInfo(info);
                            TdxTdysTldzkpEntity tdxTdysTldzkpEntity = tdxTdysTldzkpCoreDao.selectOne(new LambdaQueryWrapper<TdxTdysTldzkpEntity>().eq(TdxTdysTldzkpEntity::getUuid, uuid));
                            if(ObjectUtil.isNotEmpty(tdxTdysTldzkpEntity)){
                                tdxTdysTldzkpEntity.setCreateTime(null);
                                tdxTdysTldzkpEntity.setId(null);
                                tdxTdysTldzkpEntity.setUuid(null);
                                invoiceInfo.setTldzkp(tdxTdysTldzkpEntity);
                            }
                            invoices.add(invoiceInfo);

                            if (mxsize >= Integer.parseInt(poolCollectNum)) {
                                continueQuery = false;
                                break;
                            }
                        }

                        else {
                            DynamicContextHolder.push(dbName + DbConstant.DETAIL_READ);
                            detailList = invoicePoolDao.listInvoiceDetail(data.getDataType(), uuid);
                            List<InvoicePoolDetailInfo> listInfo = new ArrayList<>();
                            if (detailList != null) {
                                mxsize += detailList.size();
                                for (InvoiceDetailInfo record : detailList) {
                                    // 转换明细实体
                                    InvoicePoolDetailInfo detailInfo = this.getInvoiceDetailInfo(record);
                                    listInfo.add(detailInfo);
                                }

                            }
                            // 转换发票实体
                            InvoicePoolInfo invoiceInfo = this.getInvoiceInfo(info);
                            invoiceInfo.setDetailList(listInfo);
                            //查特定要素信息
                            TdxRecordTspzKzxxEntity tdxRecordTspzKzxxEntity = tdxRecordTspzKzxxDao.selectOne(new LambdaQueryWrapper<TdxRecordTspzKzxxEntity>().eq(TdxRecordTspzKzxxEntity::getUuid, uuid));
                            if(ObjectUtil.isNotEmpty(tdxRecordTspzKzxxEntity)){
                                if(StringUtils.isNotBlank(tdxRecordTspzKzxxEntity.getKzZxx())){
                                    invoiceInfo.setTdysZxx(tdxRecordTspzKzxxEntity.getKzZxx());
                                }else{
                                    invoiceInfo.setTdysZxx("");
                                }
                                if(StringUtils.isNotBlank(tdxRecordTspzKzxxEntity.getKzMxxx())){
                                    invoiceInfo.setTdysMxxx(tdxRecordTspzKzxxEntity.getKzMxxx());
                                }else{
                                    invoiceInfo.setTdysMxxx("");
                                }
                            }
                            invoices.add(invoiceInfo);

                            if (mxsize >= Integer.parseInt(poolCollectNum)) {
                                continueQuery = false;
                                break;
                            }
                        }
                    }
                }
            } else {
                run.setReturnCode("2036");
                run.setReturnMessage("数据类型不存在");
                interfaceCode.setGlobalInfo(globalInfo);
                interfaceCode.setReturnStateInfo(run);
                return JSON.toJSONString(interfaceCode);
            }
            PoolGatherData gather = new PoolGatherData();
            gather.setInvoiceType(data.getInvoiceType());
            gather.setStartRow(data.getStartRow());
            gather.setTotalRows(total);
            if ("03".equals(data.getInvoiceType())||"187".equals(data.getInvoiceType())||"383".equals(data.getInvoiceType())) {
                gather.setContentRows(vehicleInvoiceInfos.size());
                gather.setInvoices(vehicleInvoiceInfos);
            } else if ("15".equals(data.getInvoiceType())||"188".equals(data.getInvoiceType())||"184".equals(data.getInvoiceType())) {
                gather.setContentRows(userdCar.size());
                gather.setInvoices(userdCar);
            } else {
                gather.setContentRows(invoices.size());
                gather.setInvoices(invoices);
            }
            String bs = Base64.encode(JSONObject.toJSONString(gather));
            run.setReturnCode(ReturnCodeEnum.CLCG.getFhzDm());
            run.setReturnMessage(ReturnCodeEnum.CLCG.getFhzMc(ReturnCodeEnum.CLCG.getIndex()));
            interfaceCode.setReturnStateInfo(run);
            interfaceCode.setGlobalInfo(globalInfo);
//            interfaceCode.setData(GzipUtil.compress(bs));
            interfaceCode.setData(bs);
            return JSONObject.toJSONString(interfaceCode, SerializerFeature.WriteMapNullValue);
        } catch (Exception e) {
           log.info("业务处理异常：{}", e);
            run.setReturnCode(ReturnCodeEnum.CLSB.getFhzDm());
            run.setReturnMessage(ReturnCodeEnum.CLSB.getFhzMc(ReturnCodeEnum.CLSB.getIndex()));
            interfaceCode.setReturnStateInfo(run);
            interfaceCode.setGlobalInfo(globalInfo);
            interfaceCode.setData("");
            return JSONObject.toJSONString(interfaceCode, SerializerFeature.WriteMapNullValue);
        }
    }

    private UserdCarEntity getUserdCarInfo(VehicleSaleInvoices vehicle, TDxRecordInvoice veinfo) {
        DecimalFormat df = new DecimalFormat("#0.00"); 
        UserdCarEntity info = new UserdCarEntity();
        if(StringUtils.isBlank(veinfo.getInvoiceCode())){
            info.setInvoiceCode("");
        }else {
            info.setInvoiceCode(veinfo.getInvoiceCode());
        }

        info.setInvoiceNo(veinfo.getInvoiceNo());
        if(StringUtils.isNotBlank(veinfo.getEleInvoiceNo())){
            info.setEleInvoiceNo(veinfo.getEleInvoiceNo());
        }
        info.setInvoiceType(veinfo.getInvoiceType());
        if (StringUtils.isBlank(veinfo.getDqskssq())) {
            info.setCurrentTaxPeriod("");
        } else {
            info.setCurrentTaxPeriod(veinfo.getDqskssq());
        }
        if (StringUtils.isBlank(veinfo.getGxjzr())) {
            info.setLegalizeEndDate("");
        } else {
            info.setLegalizeEndDate(veinfo.getGxjzr());
        }
        if (StringUtils.isBlank(veinfo.getGxfwq())) {
            info.setLegalizeInvoiceDateBegin("");
        } else {
            info.setLegalizeInvoiceDateBegin(veinfo.getGxfwq());
        }
        if (StringUtils.isBlank(veinfo.getGxfwz())) {
            info.setLegalizeInvoiceDateEnd("");
        } else {
            info.setLegalizeInvoiceDateEnd(veinfo.getGxfwz());
        }
        if (StringUtils.isBlank(veinfo.getInvoiceStatus())) {
            info.setInvoiceStatus("");
        } else {
            info.setInvoiceStatus(veinfo.getInvoiceStatus());
        }
        info.setInvoiceDate(new SimpleDateFormat("yyyyMMdd").format(veinfo.getInvoiceDate()));
        if (StringUtils.isBlank(vehicle.getBuyerIdNum())) {
            info.setBuyerIdNum("");
        } else {
            info.setBuyerIdNum(vehicle.getBuyerIdNum());
        }


        info.setBuyerTaxNo(veinfo.getGfTaxNo());
        if (StringUtils.isBlank(veinfo.getGfName())) {
            info.setBuyerName("");
        } else {
            info.setBuyerName(veinfo.getGfName());
        }
        if (StringUtils.isBlank(veinfo.getXfName())) {
            info.setSellerName("");
        } else {
            info.setSellerName(veinfo.getXfName());
        }
        if (StringUtils.isBlank(veinfo.getXfAddressAndPhone())) {
            info.setSellerAddress("");
        } else {
            info.setSellerAddress(veinfo.getXfAddressAndPhone());
        }
        if (StringUtils.isBlank(veinfo.getGfAddressAndPhone())) {
            info.setBuyerAddress("");
        } else {
            info.setBuyerAddress(veinfo.getGfAddressAndPhone());
        }
        /*if (StringUtils.isBlank(vehicle.getGfPhone())) {
            info.setBuyerPhone("");
        } else {
            info.setBuyerPhone(vehicle.getGfPhone());
        }*/
        if (StringUtils.isBlank(veinfo.getRemark())) {
            info.setRemark("");
        } else {
            info.setRemark(veinfo.getRemark());
        }
        if (StringUtils.isBlank(vehicle.getPlateNo())) {
            info.setPlateNo("");
        } else {
            info.setPlateNo(vehicle.getPlateNo());
        }
        if (StringUtils.isBlank(vehicle.getRegistrationNo())) {
            info.setCertificateNo("");
        } else {
            info.setCertificateNo(vehicle.getRegistrationNo());
        }
        if (StringUtils.isBlank(vehicle.getVehicleType())) {
            info.setVehicleType("");
        } else {
            info.setVehicleType(vehicle.getVehicleType());
        }
        if (StringUtils.isBlank(vehicle.getVehicleNo())) {
            info.setVehicleNo("");
        } else {
            info.setVehicleNo(vehicle.getVehicleNo());
        }
        if (StringUtils.isBlank(vehicle.getFactoryModel())) {
            info.setFactoryModel("");
        } else {
            info.setFactoryModel(vehicle.getFactoryModel());
        }
        if (StringUtils.isBlank(vehicle.getVehicleAdminOffice())) {
            info.setVehicleAdminOffice("");
        } else {
            info.setVehicleAdminOffice(vehicle.getVehicleAdminOffice());
        }
        if (veinfo.getTotalAmount() == null) {
            info.setTotalAmount("");
        } else {
            info.setTotalAmount(df.format(veinfo.getTotalAmount()));
        }
        if (StringUtils.isBlank(vehicle.getAuctionUnit())) {
            info.setAuctionUnit("");
        } else {
            info.setAuctionUnit(vehicle.getAuctionUnit());
        }
        if (StringUtils.isBlank(vehicle.getAuctionAddress())) {
            info.setAuctionAddress("");
        } else {
            info.setAuctionAddress(vehicle.getAuctionAddress());
        }
        if (StringUtils.isBlank(vehicle.getAuctionTaxNo())) {
            info.setAuctionTaxno("");
        } else {
            info.setAuctionTaxno(vehicle.getAuctionTaxNo());
        }
        if (StringUtils.isBlank(vehicle.getAuctionBank())) {
            info.setAuctionBank("");
        } else {
            info.setAuctionBank(vehicle.getAuctionBank());
        }
        if (StringUtils.isBlank(vehicle.getAuctionPhone())) {
            info.setAuctionPhone("");
        } else {
            info.setAuctionPhone(vehicle.getAuctionPhone());
        }
        if (StringUtils.isBlank(vehicle.getCarMarket())) {
            info.setCarMarket("");
        } else {
            info.setCarMarket(vehicle.getCarMarket());
        }
        if (StringUtils.isBlank(vehicle.getCarMarketTaxNo())) {
            info.setCarMarketTaxno("");
        } else {
            info.setCarMarketTaxno(vehicle.getCarMarketTaxNo());
        }
        if (StringUtils.isBlank(vehicle.getCarMarketAddress())) {
            info.setCarMarketAddress("");
        } else {
            info.setCarMarketAddress(vehicle.getCarMarketAddress());
        }
        if (StringUtils.isBlank(vehicle.getCarMarketBank())) {
            info.setCarMarketBank("");
        } else {
            info.setCarMarketBank(vehicle.getCarMarketBank());
        }
        if (StringUtils.isBlank(vehicle.getCarMarketPhone())) {
            info.setCarMarketPhone("");
        } else {
            info.setCarMarketPhone(vehicle.getCarMarketPhone());
        }
        if (StringUtils.isBlank(veinfo.getPrintor())) {
            info.setInvoicer("");
        } else {
            info.setInvoicer(veinfo.getPrintor());
        }

        if(StringUtils.isBlank(vehicle.getSellerUnitCode())){
            info.setSellerIdNum("");
        }else{
            info.setSellerIdNum(vehicle.getSellerUnitCode());
        }
        if(StringUtils.isBlank(vehicle.getSellerPhone())){
            info.setSellerPhone("");
        }else{
            info.setSellerPhone(vehicle.getSellerPhone());
        }
        if(StringUtils.isBlank(vehicle.getBuyerPhone())){
            info.setBuyerPhone("");
        }else{
            info.setBuyerPhone(vehicle.getBuyerPhone());
        }

        if (StringUtils.isBlank(veinfo.getScanId())) {
            info.setImageUrl("");
        } else {
            String url = this.maekUrl(veinfo.getScanId(), veinfo.getGfTaxNo());
            info.setImageUrl(url);
        }
        return info;
    }

    public ReturnStateInfo getCheck(PoolCollectPo data) {
        ReturnStateInfo run = new ReturnStateInfo();
        DateFormat fmt = new SimpleDateFormat("yyyyMMddHHmmss");
        try {
            if (CheckUtils.isNullOrEmpty(data.getBatchNo()) || (!CheckUtils.stringLength(data.getBatchNo(), 32))) {
                run.setReturnCode(ReturnCodeEnum.PCHBNWK.getFhzDm());
                run.setReturnMessage(ReturnCodeEnum.PCHBNWK.getFhzMc(ReturnCodeEnum.PCHBNWK.getIndex()));
                return run;
            }
            if (CheckUtils.isNullOrEmpty(data.getTaxNo())) {
                run.setReturnCode(ReturnCodeEnum.SHBNWK.getFhzDm());
                run.setReturnMessage(ReturnCodeEnum.SHBNWK.getFhzMc(ReturnCodeEnum.SHBNWK.getIndex()));
                return run;
            }

            if (CheckUtils.isNullOrEmpty(data.getAcquisitionDateBegin())
                || (!CheckUtils.stringLength(data.getAcquisitionDateBegin(), 14))) {
                run.setReturnCode(ReturnCodeEnum.QSRQBNWK.getFhzDm());
                run.setReturnMessage(ReturnCodeEnum.QSRQBNWK.getFhzMc(ReturnCodeEnum.QSRQBNWK.getIndex()));
                return run;
            }
            if (CheckUtils.isNullOrEmpty(data.getAcquisitionDateEnd())
                || (!CheckUtils.stringLength(data.getAcquisitionDateEnd(), 14))) {
                run.setReturnCode(ReturnCodeEnum.JSRQBNWK.getFhzDm());
                run.setReturnMessage(ReturnCodeEnum.JSRQBNWK.getFhzMc(ReturnCodeEnum.JSRQBNWK.getIndex()));
                return run;
            }
            if (fmt.parse(data.getAcquisitionDateBegin()).compareTo(fmt.parse(data.getAcquisitionDateEnd())) == 1) {
                run.setReturnCode("2038");
                run.setReturnMessage("开始日期不可大于结束日期");
                return run;
            }
            if (data.getStartRow() == null || "".equals(data.getStartRow())) {
                run.setReturnCode(ReturnCodeEnum.KSHSCW.getFhzDm());
                run.setReturnMessage("开始行数为数字且大于0");
                return run;
            }
            if (!CheckUtils.checkNum(data.getStartRow()) || data.getStartRow() <= 0) {
                run.setReturnCode(ReturnCodeEnum.KSHSCW.getFhzDm());
                run.setReturnMessage("开始行数为数字且大于0");
                return run;
            }
            if (CheckUtils.isNullOrEmpty(data.getInvoiceType())) {
                run.setReturnCode(ReturnCodeEnum.FPLXWK.getFhzDm());
                run.setReturnMessage(ReturnCodeEnum.FPLXWK.getFhzMc(ReturnCodeEnum.FPLXWK.getIndex()));
                return run;
            }
            if (!"01".equals(data.getInvoiceType()) && !"03".equals(data.getInvoiceType())
                && !"14".equals(data.getInvoiceType()) && !"04".equals(data.getInvoiceType())
                && !"10".equals(data.getInvoiceType()) && !"11".equals(data.getInvoiceType())
                && !"15".equals(data.getInvoiceType()) && !"08".equals(data.getInvoiceType())

                && !"31".equals(data.getInvoiceType()) && !"32".equals(data.getInvoiceType())&& !"161".equals(data.getInvoiceType())
                && !"183".equals(data.getInvoiceType()) && !"185".equals(data.getInvoiceType()) && !"186".equals(data.getInvoiceType())
                && !"187".equals(data.getInvoiceType()) && !"188".equals(data.getInvoiceType()) && !"283".equals(data.getInvoiceType())
                && !"383".equals(data.getInvoiceType()) && !"184".equals(data.getInvoiceType())
            ) {
                run.setReturnCode("2037");
                run.setReturnMessage("发票类型不存在");
                return run;
            }
            if (CheckUtils.isNullOrEmpty(data.getDataType())) {
                run.setReturnCode("2035");
                run.setReturnMessage("数据类型不可为空");
            }
        } catch (Exception e) {
           log.info("业务处理异常：{}", e);
            run.setReturnCode(ReturnCodeEnum.CLSB.getFhzDm());
            run.setReturnMessage(ReturnCodeEnum.CLSB.getFhzMc(ReturnCodeEnum.CLSB.getIndex()));
        }

        return run;
    }

    private VehicleSaleInvoicePoolInfos getVehicleInfo(VehicleSaleInvoices vehicleSaleInvoice,
        TDxRecordInvoice veinfo) {
        DecimalFormat df = new DecimalFormat("#0.00");
        VehicleSaleInvoicePoolInfos info = new VehicleSaleInvoicePoolInfos();
        if(StringUtils.isBlank(veinfo.getInvoiceCode())){
            info.setInvoiceCode("");
        }else {
            info.setInvoiceCode(veinfo.getInvoiceCode());
        }

        info.setInvoiceNo(veinfo.getInvoiceNo());
        if(StringUtils.isNotBlank(veinfo.getEleInvoiceNo())){
            info.setEleInvoiceNo(veinfo.getEleInvoiceNo());
        }
        if (StringUtils.isBlank(veinfo.getDqskssq())) {
            info.setCurrentTaxPeriod("");
        } else {
            info.setCurrentTaxPeriod(veinfo.getDqskssq());
        }
        if (StringUtils.isBlank(veinfo.getGxjzr())) {
            info.setLegalizeEndDate("");
        } else {
            info.setLegalizeEndDate(veinfo.getGxjzr());
        }
        if (StringUtils.isBlank(veinfo.getGxfwq())) {
            info.setLegalizeInvoiceDateBegin("");
        } else {
            info.setLegalizeInvoiceDateBegin(veinfo.getGxfwq());
        }
        if (StringUtils.isBlank(veinfo.getGxfwz())) {
            info.setLegalizeInvoiceDateEnd("");
        } else {
            info.setLegalizeInvoiceDateEnd(veinfo.getGxfwz());
        }
        info.setInvoiceType(veinfo.getInvoiceType());
        if (StringUtils.isBlank(veinfo.getGfName())) {
            info.setBuyerName("");
        } else {
            info.setBuyerName(veinfo.getGfName());
        }
        info.setInvoiceDate(new SimpleDateFormat("yyyyMMdd").format(veinfo.getInvoiceDate()));
        if (StringUtils.isBlank(vehicleSaleInvoice.getBuyerIdNum())) {
            info.setBuyerIdNum("");
        } else {
            info.setBuyerIdNum(vehicleSaleInvoice.getBuyerIdNum());
        }
        info.setBuyerTaxNo(veinfo.getGfTaxNo());
        if (StringUtils.isBlank(vehicleSaleInvoice.getVehicleType())) {
            info.setVehicleType("");
        } else {
            info.setVehicleType(vehicleSaleInvoice.getVehicleType());
        }
        if (StringUtils.isBlank(vehicleSaleInvoice.getFactoryModel())) {
            info.setFactoryModel("");
        } else {
            info.setFactoryModel(vehicleSaleInvoice.getFactoryModel());
        }
        if (StringUtils.isBlank(vehicleSaleInvoice.getProductPlace())) {
            info.setProductPlace("");
        } else {
            info.setProductPlace(vehicleSaleInvoice.getProductPlace());
        }
        if (StringUtils.isBlank(vehicleSaleInvoice.getCertificate())) {
            info.setCertificate("");
        } else {
            info.setCertificate(vehicleSaleInvoice.getCertificate());
        }
        if (StringUtils.isBlank(vehicleSaleInvoice.getCertificateImport())) {
            info.setCertificateImport("");
        } else {
            info.setCertificateImport(vehicleSaleInvoice.getCertificateImport());
        }
        if (StringUtils.isBlank(vehicleSaleInvoice.getInspectionNum())) {
            info.setInspectionNum("");
        } else {
            info.setInspectionNum(vehicleSaleInvoice.getInspectionNum());
        }
        if (StringUtils.isBlank(vehicleSaleInvoice.getEngineNo())) {
            info.setEngineNo("");
        } else {
            info.setEngineNo(vehicleSaleInvoice.getEngineNo());
        }
        if (StringUtils.isBlank(vehicleSaleInvoice.getVehicleNo())) {
            info.setVehicleNo("");
        } else {
            info.setVehicleNo(vehicleSaleInvoice.getVehicleNo());
        }
        if (veinfo.getTotalAmount() == null) {
            info.setTotalAmount("0.00");
        } else {
            info.setTotalAmount(veinfo.getTotalAmount().toString());
        }
        if (StringUtils.isBlank(veinfo.getXfName())) {
            info.setSalerName("");
        } else {
            info.setSalerName(veinfo.getXfName());
        }
        info.setTaxNum(veinfo.getXfTaxNo());
        if (StringUtils.isBlank(vehicleSaleInvoice.getPhone())) {
            info.setPhone("");
        } else {
            info.setPhone(vehicleSaleInvoice.getPhone());
        }
        if (StringUtils.isBlank(vehicleSaleInvoice.getBuyerBank())) {
            info.setSalerBank("");
        } else {
            info.setSalerBank(vehicleSaleInvoice.getBuyerBank());
        }
        if (StringUtils.isBlank(veinfo.getXfBankAndNo())) {
            info.setSalerAccount("");
        } else {
            info.setSalerAccount(veinfo.getXfBankAndNo());
        }
        if (StringUtils.isBlank(veinfo.getXfAddressAndPhone())) {
            info.setSalerAddressPhone("");
        } else {
            info.setSalerAddressPhone(veinfo.getXfAddressAndPhone());
        }
        if (StringUtils.isBlank(vehicleSaleInvoice.getTaxRate())) {
            info.setTaxRate("");
        } else {
            if ("不征税".equals(vehicleSaleInvoice.getTaxRate()) || "免税".equals(vehicleSaleInvoice.getTaxRate())
                || "*".equals(vehicleSaleInvoice.getTaxRate())) {
                info.setTaxRate("");
            } else {
                info.setTaxRate(Double.valueOf(vehicleSaleInvoice.getTaxRate().replace("%", "")).intValue() + "");
                double rate = Double.parseDouble(vehicleSaleInvoice.getTaxRate());
                if (rate < 1) {
                    rate = rate * 100;
                    int r = (int)rate;
                    info.setTaxRate(r + "");
                } else {
                    info.setTaxRate(vehicleSaleInvoice.getTaxRate().replace("%", ""));
                }
            }
        }

        info.setTaxAmount(df.format(veinfo.getTaxAmount()));
        if (StringUtils.isBlank(vehicleSaleInvoice.getTaxBureauCode())) {
            info.setTaxBureauCode("");
        } else {
            info.setTaxBureauCode(vehicleSaleInvoice.getTaxBureauCode());
        }
        if (StringUtils.isBlank(vehicleSaleInvoice.getTaxBureauName())) {
            info.setTaxBureauName("");
        } else {
            info.setTaxBureauName(vehicleSaleInvoice.getTaxBureauName());
        }
        info.setInvoiceAmount(df.format(veinfo.getInvoiceAmount()));
        if (StringUtils.isBlank(vehicleSaleInvoice.getTaxRecords())) {
            info.setTaxRecords("");
        } else {
            info.setTaxRecords(vehicleSaleInvoice.getTaxRecords());
        }
        if (StringUtils.isBlank(vehicleSaleInvoice.getTonnage())) {
            info.setTonnage("");
        } else {
            info.setTonnage(vehicleSaleInvoice.getTonnage());
        }
        if (StringUtils.isBlank(vehicleSaleInvoice.getLimitPeople())) {
            info.setLimitPeople("");
        } else {
            info.setLimitPeople(vehicleSaleInvoice.getLimitPeople());
        }
        info.setInvoiceStatus(veinfo.getInvoiceStatus());
        info.setCheckStatus(veinfo.getSfygx());
        info.setLegalizeState(veinfo.getRzhYesorno());
        if (veinfo.getConfirmDate() == null) {
            info.setLegalizeDate("");
        } else {
            info.setLegalizeDate(new SimpleDateFormat("yyyyMMdd").format(veinfo.getConfirmDate()));
        }
        if (veinfo.getRzhBelongDate() == null) {
            info.setTaxPeriod("");
        } else {
            info.setTaxPeriod(veinfo.getRzhBelongDate());
        }
        /*  if (veinfo.getRzhType() == null) {
            info.setLegalizeType("");
        } else {
            info.setLegalizeType(veinfo.getRzhType());
        }*/
        if (veinfo.getSfdbts() == null) {
            info.setSfdbts("");
        } else {
            info.setSfdbts(veinfo.getSfdbts());
        }
        if (StringUtils.isBlank(veinfo.getRzlx())) {
            info.setRzlx("0");
        } else {
            info.setRzlx(veinfo.getRzlx());
        }
        if (veinfo.getGlzt() == null) {
            info.setGlzt("");
        } else {
            info.setGlzt(veinfo.getGlzt());
        }
        if (veinfo.getDkTaxAmount() == null) {
            info.setYxse("");
        } else {
            info.setYxse(veinfo.getDkTaxAmount().toPlainString());
        }
        if (veinfo.getYqkgxbz() == null) {
            info.setYqkgxbz("");
        } else {
            info.setYqkgxbz(veinfo.getYqkgxbz());
        }
        if (veinfo.getXxly() == null) {
            info.setXxly("");
        } else {
            info.setXxly(veinfo.getXxly());
        }
        if (veinfo.getScanId() == null) {
            info.setImageUrl("");
        } else {
            String url = this.maekUrl(veinfo.getScanId(), veinfo.getGfTaxNo());
            info.setImageUrl(url);
        }

        return info;
    }

    private InvoicePoolDetailInfo getInvoiceDetailInfo(InvoiceDetailInfo detail) {
        DecimalFormat df = new DecimalFormat("#0.00");
        InvoicePoolDetailInfo detailInfo = new InvoicePoolDetailInfo();
        detailInfo.setDetailNo(detail.getDetailNo() + "");
        detailInfo.setGoodsName(detail.getGoodsName());
        if (StringUtils.isBlank(detail.getTaxCodeName())) {
            detailInfo.setTaxCodeName("");
        } else {
            detailInfo.setTaxCodeName(detail.getTaxCodeName());
        }
        if (StringUtils.isBlank(detail.getModel())) {
            detailInfo.setSpecificationModel("");
        } else {
            detailInfo.setSpecificationModel(detail.getModel());
        }
        if (StringUtils.isBlank(detail.getGoodsNum())) {
            detailInfo.setGoodsNum("");
        } else {
            detailInfo.setGoodsNum(detail.getGoodsNum());
        }
        if (detail.getNum() == null || "".equals(detail.getNum())) {
            detailInfo.setNum("0");
        } else {
            detailInfo.setNum(detail.getNum() + "");
        }
        if (StringUtils.isBlank(detail.getUnit())) {
            detailInfo.setUnit("");
        } else {
            detailInfo.setUnit(detail.getUnit());
        }
        if (detail.getUnitPrice() == null) {
            detailInfo.setUnitPrice("");
        } else {
            detailInfo.setUnitPrice(detail.getUnitPrice());
        }
        if (detail.getDetailAmount() == null) {
            detailInfo.setDetailAmount("");
        } else {
            detailInfo.setDetailAmount(detail.getDetailAmount());
        }
        if (detail.getTaxRate() == null) {
            detailInfo.setTaxRate("");
        } else {
            if ("不征税".equals(detail.getTaxRate()) || "免税".equals(detail.getTaxRate())
                || "*".equals(detail.getTaxRate())) {
                detailInfo.setTaxRate("");
            } else {
                double rate = Double.parseDouble(detail.getTaxRate().replace("%", ""));
                if (rate < 1) {
                    rate = rate * 100;
                    int r = (int)rate;
                    detailInfo.setTaxRate(r + "");
                } else {
                    detailInfo.setTaxRate(detail.getTaxRate().replace("%", ""));
                }
            }

        }
        if (detail.getTaxAmount() == null) {
            detailInfo.setTaxAmount("");
        } else {
            detailInfo.setTaxAmount(detail.getTaxAmount());
        }
        if (StringUtils.isBlank(detail.getCph())) {
            detailInfo.setCph("");
        } else {
            detailInfo.setCph(detail.getCph());
        }
        if (StringUtils.isBlank(detail.getLx())) {
            detailInfo.setLx("");
        } else {
            detailInfo.setLx(detail.getLx());
        }
        if (StringUtils.isBlank(detail.getTxrqq())) {
            detailInfo.setTxrqq("");
        } else {
            detailInfo.setTxrqq(detail.getTxrqq());
        }
        if (StringUtils.isBlank(detail.getTxrqz())) {
            detailInfo.setTxrqz("");
        } else {
            detailInfo.setTxrqz(detail.getTxrqz());
        }
        return detailInfo;
    }

    public InvoicePoolInfo getInvoiceInfo(TDxRecordInvoice invoice) {
        DecimalFormat df = new DecimalFormat("#0.00");
        InvoicePoolInfo info = new InvoicePoolInfo();
        if(StringUtils.isBlank(invoice.getInvoiceCode())){
            info.setInvoiceCode("");
        }else {
            info.setInvoiceCode(invoice.getInvoiceCode());
        }

        info.setInvoiceNo(invoice.getInvoiceNo());
        if(StringUtils.isNotBlank(invoice.getEleInvoiceNo())){
            info.setEleInvoiceNo(invoice.getEleInvoiceNo());
        }
        if (invoice.getInvoiceDate() != null) {
            info.setInvoiceDate(new SimpleDateFormat("yyyyMMdd").format(invoice.getInvoiceDate()));
        }
        info.setTdyslxDm(invoice.getLqTdyslxDm());
        info.setBuyerAccount(invoice.getGfBankAndNo());
        info.setBuyerAddressPhone(invoice.getGfAddressAndPhone());
        info.setBuyerName(invoice.getGfName());
        info.setBuyerTaxNo(invoice.getGfTaxNo());
        info.setSalerAccount(invoice.getXfBankAndNo());
        info.setSalerAddressPhone(invoice.getXfAddressAndPhone());
        info.setSalerName(invoice.getXfName());
        info.setSalerTaxNo(invoice.getXfTaxNo());
        if (invoice.getInvoiceAmount() != null) {
            info.setInvoiceAmount(df.format(invoice.getInvoiceAmount()));
        } else {
            info.setInvoiceAmount("0");
        }
        if (invoice.getTaxAmount() != null) {
            info.setTaxAmount(df.format(invoice.getTaxAmount()));
        } else {
            info.setTaxAmount("0");
        }
        if (invoice.getTotalAmount() != null) {
            info.setTotalAmount(df.format(invoice.getTotalAmount()));
        } else {
            Double total = Double.parseDouble(info.getTaxAmount()) + Double.parseDouble(info.getInvoiceAmount());
            info.setTotalAmount(String.format("%.2f", total));
        }
        if (StringUtils.isBlank(invoice.getRemark())) {
            info.setRemark("");
        } else {
            info.setRemark(invoice.getRemark());
        }
        if (StringUtils.isBlank(invoice.getDqskssq())) {
            info.setCurrentTaxPeriod("");
        } else {
            info.setCurrentTaxPeriod(invoice.getDqskssq());
        }
        if (StringUtils.isBlank(invoice.getGxjzr())) {
            info.setLegalizeEndDate("");
        } else {
            info.setLegalizeEndDate(invoice.getGxjzr());
        }
        if (StringUtils.isBlank(invoice.getGxfwq())) {
            info.setLegalizeInvoiceDateBegin("");
        } else {
            info.setLegalizeInvoiceDateBegin(invoice.getGxfwq());
        }
        if (StringUtils.isBlank(invoice.getGxfwz())) {
            info.setLegalizeInvoiceDateEnd("");
        } else {
            info.setLegalizeInvoiceDateEnd(invoice.getGxfwz());
        }

        if (invoice.getConfirmDate() == null) {
            info.setLegalizeDate("");
        } else {
            info.setLegalizeDate(new SimpleDateFormat("yyyyMMdd").format(invoice.getConfirmDate()));
        }
        info.setLegalizeState(invoice.getRzhYesorno() + "");
        info.setInvoiceStatus(invoice.getInvoiceStatus() + "");
        info.setInvoiceType(invoice.getInvoiceType());
        if (invoice.getRzhBelongDate() == null) {
            info.setLegalizeBlongDate("");
        } else {
            info.setLegalizeBlongDate(invoice.getRzhBelongDate());
        }
        if (invoice.getSfdbts() == null) {
            info.setSfdbts("");
        } else {
            info.setSfdbts(invoice.getSfdbts() + "");
        }
        if (StringUtils.isBlank(invoice.getRzlx())) {
            info.setRzlx("0");
        } else {
            info.setRzlx(invoice.getRzlx());
        }
        if (StringUtils.isBlank(invoice.getCheckCode())) {
            info.setCheckCode("");
        } else {
            info.setCheckCode(invoice.getCheckCode());
        }
        if (StringUtils.isBlank(invoice.getTxfbz())) {
            info.setTxfbz("");
        } else {
            info.setTxfbz(invoice.getTxfbz());
        }
        if (StringUtils.isBlank(invoice.getLslbz())) {
            info.setLslbz("");
        } else {
            info.setLslbz(invoice.getLslbz());
        }
        // 三期新加字段
        if (StringUtils.isBlank(invoice.getXxly())) {
            info.setXxly("");
        } else {
            info.setXxly(invoice.getXxly());
        }
        if (invoice.getDkTaxAmount() == null) {
            info.setYxse(df.format(invoice.getTaxAmount()));
        } else {
            info.setYxse(df.format(invoice.getDkTaxAmount()));
        }
        if (StringUtils.isBlank(invoice.getYqkgxbz())) {
            info.setYqkgxbz("");
        } else {
            info.setYqkgxbz(invoice.getYqkgxbz());
        }
        if (StringUtils.isBlank(invoice.getGlzt())) {
            info.setGlzt("");
        } else {
            info.setGlzt(invoice.getGlzt());
        }
        if (StringUtils.isBlank(invoice.getScanId())) {
            info.setImageUrl("");
        } else {
            String url = this.maekUrl(invoice.getScanId(), invoice.getGfTaxNo());
            info.setImageUrl(url);
        }
        return info;
    }

    /**
     * 票池状态采集业务
     *
     * @param globalInfo
     * @param request
     * @param response
     * @param authorize
     * @return
     */
    @Override
    public String listState(GlobalInfo globalInfo, Map<String, String> map, HttpServletRequest request,
        HttpServletResponse response, Authorize authorize) {
        ReturnStateInfo run = new ReturnStateInfo();
        InterfaceCode interfaceCode = new InterfaceCode();
        PoolStatePo data = null;
        List<State> list = null;

        try {
            data = JSON.parseObject(map.get("data"), PoolStatePo.class);
        } catch (Exception e) {
            run.setReturnCode(ReturnCodeEnum.QQBWGSCW.getFhzDm());
            run.setReturnMessage(ReturnCodeEnum.QQBWGSCW.getFhzMc(ReturnCodeEnum.QQBWGSCW.getIndex()));
            interfaceCode.setGlobalInfo(globalInfo);
            interfaceCode.setReturnStateInfo(run);
            return JSON.toJSONString(interfaceCode);
        }

        try {
            run = getCheckState(data);
            if (run.getReturnCode() != null || run.getReturnMessage() != null) {
                interfaceCode.setGlobalInfo(globalInfo);
                interfaceCode.setReturnStateInfo(run);
                return JSON.toJSONString(interfaceCode);
            }
            DynamicContextHolder.push(DbConstant.BASICS_READ);
            SysEnterpriseConfigDto deptEntity = enterpriseConfigErpDao.getOrg(data.getTaxNo());
            String dbName = null;
            if (deptEntity != null && deptEntity.getDbName() != null) {
                dbName = deptEntity.getDbName();
            } else {
                ReturnStateInfo runInfo = new ReturnStateInfo();
                runInfo.setReturnCode(ReturnCodeEnum.JTSHBF.getFhzDm());
                runInfo.setReturnMessage(ReturnCodeEnum.JTSHBF.getFhzMc(ReturnCodeEnum.JTSHBF.getIndex()));
                interfaceCode.setGlobalInfo(globalInfo);
                interfaceCode.setReturnStateInfo(runInfo);
                return JSON.toJSONString(interfaceCode);
            }
            Integer total = null;
            // 数据类型 1-进项 2-进项
            if ("1".equals(data.getDataType()) || "2".equals(data.getDataType())) {
                DynamicContextHolder.push(dbName + DbConstant.BUSINESS_READ);
                total = invoicePoolDao.countState(data);
                log.info("线程{},请求参数{},状态采集总数{}", Thread.currentThread().getId(), data, total);
                int startRow = data.getStartRow();
                List<InvoicePoolState> infos = new ArrayList<>();
                boolean continueQuery = true;
                while (continueQuery && infos.size() < Integer.parseInt(poolStateNum) && infos.size() < total
                    && startRow <= total) {
                    list = invoicePoolDao.listInvoiceState(data, startRow - 1, 1000);
                    startRow += 1000;
                    for (State ss : list) {
                        InvoicePoolState stateInfo = this.getStateInfo(ss);
                        infos.add(stateInfo);
                        if (infos.size() >= Integer.parseInt(poolStateNum)) {
                            continueQuery = false;
                            break;
                        }
                    }

                }
                PoolGatherData status = new PoolGatherData();
                status.setContentRows(infos.size());
                status.setStartRow(data.getStartRow());
                status.setInvoiceType(data.getInvoiceType());
                status.setTotalRows(total);
                status.setInvoices(infos);
                String bs = Base64.encode(JSONObject.toJSONString(status, SerializerFeature.WriteMapNullValue));
                run.setReturnCode(ReturnCodeEnum.CLCG.getFhzDm());
                run.setReturnMessage(ReturnCodeEnum.CLCG.getFhzMc(ReturnCodeEnum.CLCG.getIndex()));
                interfaceCode.setReturnStateInfo(run);
                interfaceCode.setGlobalInfo(globalInfo);
//                interfaceCode.setData(GzipUtil.compress(bs));
                interfaceCode.setData(bs);
                return JSONObject.toJSONString(interfaceCode, SerializerFeature.WriteMapNullValue);
            } else {
                run.setReturnCode("2036");
                run.setReturnMessage("数据类型不存在");
                interfaceCode.setGlobalInfo(globalInfo);
                interfaceCode.setReturnStateInfo(run);
                return JSON.toJSONString(interfaceCode);
            }
        } catch (Exception e) {
           log.info("业务处理异常：{}", e);
            run.setReturnCode(ReturnCodeEnum.CLSB.getFhzDm());
            run.setReturnMessage(ReturnCodeEnum.CLSB.getFhzMc(ReturnCodeEnum.CLSB.getIndex()));
            interfaceCode.setReturnStateInfo(run);
            interfaceCode.setGlobalInfo(globalInfo);
            interfaceCode.setData("");
            return JSONObject.toJSONString(interfaceCode, SerializerFeature.WriteMapNullValue);
        }
    }

    private InvoicePoolState getStateInfo(State state) {
        DecimalFormat df = new DecimalFormat("#0.00");
        InvoicePoolState info = new InvoicePoolState();
        if(StringUtils.isBlank(state.getInvoiceCode())){
            info.setInvoiceCode("");
        }else {
            info.setInvoiceCode(state.getInvoiceCode());
        }

        info.setInvoiceNo(state.getInvoiceNo());
        info.setInvoiceStatus(state.getInvoiceStatus());
        if (state.getQsStatus() == null) {
            info.setQsStatus("");
        } else {
            info.setQsStatus(state.getQsStatus());
        }
        if (state.getQsUser() == null) {
            info.setQsUser("");
        } else {
            info.setQsUser(state.getQsUser());
        }
        if (state.getQsDate() == null) {
            info.setQsDate("");
        } else {
            info.setQsDate(state.getQsDate());
        }
        if (state.getLegalizeState() == null) {
            info.setLegalizeState("");
        } else {
            info.setLegalizeState(state.getLegalizeState());
        }
        if (state.getLegalizeDate() == null) {
            info.setLegalizeDate("");
        } else {
            info.setLegalizeDate(state.getLegalizeDate());
        }
        if (state.getLegalizeBelongDate() == null) {
            info.setLegalizeBelongDate("");
        } else {
            info.setLegalizeBelongDate(state.getLegalizeBelongDate());
        }
        if (state.getRzlx() == null) {
            info.setRzlx("");
        } else {
            info.setRzlx(state.getRzlx());
        }
        if (state.getManagementStatus() == null) {
            info.setGlzt("");
        } else {
            info.setGlzt(state.getManagementStatus());
        }
        if (state.getInformationSources() == null) {
            info.setXxly("");
        } else {
            info.setXxly(state.getInformationSources());
        }
        if (StringUtils.isBlank(state.getTaxCredit())) {
            info.setYxse("");
        } else {
            info.setYxse(df.format(new BigDecimal(state.getTaxCredit())));
        }
        if (state.getOverdueCheckMark() == null) {
            info.setYqkgxbz("");
        } else {
            info.setYqkgxbz(state.getOverdueCheckMark());
        }
        return info;
    }

    private ReturnStateInfo getCheckState(PoolStatePo data) throws ParseException {
        ReturnStateInfo run = new ReturnStateInfo();
        DateFormat fmt = new SimpleDateFormat("yyyyMMddHHmmss");
        boolean r = !(CheckUtils.stringLength(data.getTaxNo(), 15) || CheckUtils.stringLength(data.getTaxNo(), 18));
        if (CheckUtils.isNullOrEmpty(data.getTaxNo()) || r) {
            run.setReturnCode(ReturnCodeEnum.SHBNWK.getFhzDm());
            run.setReturnMessage(ReturnCodeEnum.SHBNWK.getFhzMc(ReturnCodeEnum.SHBNWK.getIndex()));
            return run;
        }
        if (CheckUtils.isNullOrEmpty(data.getBatchNo()) || (!CheckUtils.stringLength(data.getBatchNo(), 32))) {
            run.setReturnCode(ReturnCodeEnum.PCHBNWK.getFhzDm());
            run.setReturnMessage(ReturnCodeEnum.PCHBNWK.getFhzMc(ReturnCodeEnum.PCHBNWK.getIndex()));
            return run;
        }
        if (CheckUtils.isNullOrEmpty(data.getStatusChangeDateBegin())
            || (!CheckUtils.stringLength(data.getStatusChangeDateBegin(), 14))) {
            run.setReturnCode(ReturnCodeEnum.QSRQBNWK.getFhzDm());
            run.setReturnMessage(ReturnCodeEnum.QSRQBNWK.getFhzMc(ReturnCodeEnum.QSRQBNWK.getIndex()));
            return run;
        }
        if (CheckUtils.isNullOrEmpty(data.getStatusChangeDateEnd())
            || (!CheckUtils.stringLength(data.getStatusChangeDateEnd(), 14))) {
            run.setReturnCode(ReturnCodeEnum.JSRQBNWK.getFhzDm());
            run.setReturnMessage(ReturnCodeEnum.JSRQBNWK.getFhzMc(ReturnCodeEnum.JSRQBNWK.getIndex()));
            return run;
        }
        if (fmt.parse(data.getStatusChangeDateBegin()).compareTo(fmt.parse(data.getStatusChangeDateEnd())) == 1) {
            run.setReturnCode("2038");
            run.setReturnMessage("开始日期不可大于结束日期");
            return run;
        }
        if (data.getStartRow() == null) {
            run.setReturnCode(ReturnCodeEnum.KSHSCW.getFhzDm());
            run.setReturnMessage("开始行数为数字且大于0");
            return run;
        }
        if (!CheckUtils.checkNum(data.getStartRow()) || data.getStartRow() <= 0) {
            run.setReturnCode(ReturnCodeEnum.KSHSCW.getFhzDm());
            run.setReturnMessage("开始行数为数字且大于0");
            return run;
        }
        if (CheckUtils.isNullOrEmpty(data.getInvoiceType())) {
            run.setReturnCode(ReturnCodeEnum.FPLXWK.getFhzDm());
            run.setReturnMessage(ReturnCodeEnum.FPLXWK.getFhzMc(ReturnCodeEnum.FPLXWK.getIndex()));
            return run;
        }
        if (!"01".equals(data.getInvoiceType()) && !"03".equals(data.getInvoiceType())
            && !"14".equals(data.getInvoiceType()) && !"04".equals(data.getInvoiceType())
            && !"10".equals(data.getInvoiceType()) && !"11".equals(data.getInvoiceType())
            && !"15".equals(data.getInvoiceType()) && !"08".equals(data.getInvoiceType())

            && !"31".equals(data.getInvoiceType()) && !"32".equals(data.getInvoiceType())&& !"161".equals(data.getInvoiceType())
            && !"183".equals(data.getInvoiceType()) && !"185".equals(data.getInvoiceType()) && !"186".equals(data.getInvoiceType())
            && !"187".equals(data.getInvoiceType()) && !"188".equals(data.getInvoiceType()) && !"283".equals(data.getInvoiceType())
            && !"383".equals(data.getInvoiceType()) && !"184".equals(data.getInvoiceType())
        ) {
            run.setReturnCode("2037");
            run.setReturnMessage("发票类型不存在");
            return run;
        }
        if (CheckUtils.isNullOrEmpty(data.getDataType())) {
            run.setReturnCode("2035");
            run.setReturnMessage("数据类型不可为空");
            return run;
        }
        return run;
    }

    public String maekUrl(String scanId, String taxno) {
        return imageUrl + "&scanId=" + scanId + "&taxno=" + taxno;

    }

    @Override
    public String salsePush(GlobalInfo globalInfo, Map<String, String> requestParam, HttpServletRequest request,
        HttpServletResponse response, Authorize authorize) {
        ReturnStateInfo run = new ReturnStateInfo();
        InterfaceCode interfaceCode = new InterfaceCode();
        SalesInvoicePushInfos infos = null;
        try {
            infos = JSONObject.parseObject(requestParam.get("data"), SalesInvoicePushInfos.class);
        } catch (Exception e) {
            run.setReturnCode(ReturnCodeEnum.QQBWGSCW.getFhzDm());
            run.setReturnMessage(ReturnCodeEnum.QQBWGSCW.getFhzMc(ReturnCodeEnum.QQBWGSCW.getIndex()));
            interfaceCode.setGlobalInfo(globalInfo);
            interfaceCode.setReturnStateInfo(run);
            interfaceCode.setData("");
            return JSONObject.toJSONString(interfaceCode, SerializerFeature.WriteMapNullValue);
        }
        run = getCheckData(infos);
        if (run.getReturnCode() != null || run.getReturnMessage() != null) {
            interfaceCode.setReturnStateInfo(run);
            interfaceCode.setGlobalInfo(globalInfo);
            return JSON.toJSONString(interfaceCode);
        }
        try {

            String dbName = null;
            String company = null;
            String buyerTaxNo = null;
            if ("15".equals(infos.getInvoiceType())||"184".equals(infos.getInvoiceType())||"188".equals(infos.getInvoiceType())
                ||"03".equals(infos.getInvoiceType()) ||"383".equals(infos.getInvoiceType())||"187".equals(infos.getInvoiceType())
            ) {
                buyerTaxNo = infos.getSalerTaxNo();
            } else {
                buyerTaxNo = infos.getSalerTaxNo();
            }
            if (StringUtils.isBlank(buyerTaxNo)) {
                dbName = "business";
            } else {
                DynamicContextHolder.push(DbConstant.BASICS_READ);
                SysEnterpriseConfigDto deptEntity = enterpriseConfigErpDao.getOrg(buyerTaxNo);
                if (deptEntity != null && deptEntity.getDbName() != null) {
                    dbName = deptEntity.getDbName();
                    company = deptEntity.getCompany();
                } else {
                    ReturnStateInfo runInfo = new ReturnStateInfo();
                    runInfo.setReturnCode(ReturnCodeEnum.JTSHBF.getFhzDm());
                    runInfo.setReturnMessage(ReturnCodeEnum.JTSHBF.getFhzMc(ReturnCodeEnum.JTSHBF.getIndex()));
                    interfaceCode.setGlobalInfo(globalInfo);
                    interfaceCode.setReturnStateInfo(runInfo);
                    interfaceCode.setData("");
                    return JSON.toJSONString(interfaceCode);
                }
            }

            DynamicContextHolder.push(dbName + DbConstant.BUSINESS_READ);
            String invoiceCode = infos.getInvoiceCode();
            String invoiceNo = infos.getInvoiceNo();
            String invoiceType = infos.getInvoiceType();
            TdxSaleRecordInvoiceEntity saleRecordInvoice = tdxSaleRecordInvoiceDao
                .selectOne(new QueryWrapper<TdxSaleRecordInvoiceEntity>().eq("uuid", invoiceCode + invoiceNo));
            if (saleRecordInvoice != null) {
                TdxSaleRecordInvoiceEntity update = new TdxSaleRecordInvoiceEntity();
                update.setId(saleRecordInvoice.getId());
                update.setQsDate(new Date());
                if (!saleRecordInvoice.getInvoiceStatus().equals(infos.getInvoiceStatus())) {
                    update.setInvoiceStatus(infos.getInvoiceStatus());
                    update.setStatusUpdateDate(new Date());
                }
                TDxInvoiceSales tDxInvoiceSales = new TDxInvoiceSales();
                tDxInvoiceSales.setQsDate(new Date());
                DynamicContextHolder.push(dbName + DbConstant.BUSINESS_WRITE);
                // 更新抵账表发票状态、签收时间
                tdxSaleRecordInvoiceDao.updateById(update);
                tDxInvoiceSaleDao.update(tDxInvoiceSales,
                    new UpdateWrapper<TDxInvoiceSales>().eq("uuid", saleRecordInvoice.getUuid()));

                run.setReturnCode(ReturnCodeEnum.CLCG.getFhzDm());
                run.setReturnMessage(ReturnCodeEnum.CLCG.getFhzMc(ReturnCodeEnum.CLCG.getIndex()));
                interfaceCode.setReturnStateInfo(run);
                interfaceCode.setGlobalInfo(globalInfo);
                return JSONObject.toJSONString(interfaceCode, SerializerFeature.WriteMapNullValue);

            } else {
                //插入
                //底账-销项表组装
                TdxSaleRecordInvoiceEntity invoiceInfo = getSaleInvoiceInfo(infos);
                invoiceInfo.setUuid(invoiceCode + invoiceNo);
                invoiceInfo.setCompany(company);
                //签收表
                TDxInvoiceSales saleInvoice = getSaleInvoice(infos);
                saleInvoice.setUuid(invoiceCode + invoiceNo);
                DynamicContextHolder.push(dbName + DbConstant.BUSINESS_WRITE);

                // 入签收表
                String uuid = saleInvoice.getUuid();
                //如果签收表有，则更新，否则再插入
                TDxInvoiceSales tDxInvoiceSales = tDxInvoiceSaleDao.selectOne(new LambdaQueryWrapper<TDxInvoiceSales>().eq(TDxInvoiceSales::getUuid, uuid));
                if(ObjectUtil.isEmpty(tDxInvoiceSales)){
                    tDxInvoiceSaleDao.insert(saleInvoice);
                }else{
                    tDxInvoiceSaleDao.update(saleInvoice, new LambdaUpdateWrapper<TDxInvoiceSales>().eq(TDxInvoiceSales::getUuid, uuid));
                }
                Set set = new HashSet();
                if ("03".equals(invoiceType) ||"383".equals(invoiceType)||"187".equals(invoiceType)
                        || "15".equals(invoiceType)||"184".equals(invoiceType)||"188".equals(invoiceType)
                ) {
                    //机动车表
                    VehicleSaleInvoices vehicle = getVehicle(infos);
                    set.add(vehicle.getYhzcbs().trim());
                    vehicle.setUuid(invoiceCode + invoiceNo);
                    vehicleSaleInvoiceDao.insert(vehicle);
                }
                else {
                    if("161".equals(invoiceType)){
                        updateTdysMhInfo(invoiceCode + invoiceNo, infos.getMhxcd(),infos.getMhxcdMx());
                    }
                    if("283".equals(invoiceType)){
                        updateTdysTldzkyInfo(invoiceCode + invoiceNo, infos.getTldzkp());
                    }
                    DynamicContextHolder.push(dbName + DbConstant.DETAIL_WRITE);
                    salesInvoiceDetailDao
                        .delete(new UpdateWrapper<InvoiceDetailInfo>().eq("uuid", invoiceCode + invoiceNo));
                    List<InvoiceDetailInfo> details = infos.getDetailList();
                    if (details != null && details.size() > 0) {

                        for (InvoiceDetailInfo detailInfo : details) {
                            if (StringUtils.isNotBlank(detailInfo.getGoodsName())
                                && detailInfo.getGoodsName().indexOf("详见") >= 0) {
                                detailInfo.setGoodsName(changeBrackets(detailInfo.getGoodsName()));
                            }
                            set.add(detailInfo.getYhzcbs().trim());
                            detailInfo.setInvoiceCode(invoiceCode);
                            detailInfo.setInvoiceNo(invoiceNo);
                            detailInfo.setTaxRate(CommonUtil.processTaxRate(detailInfo.getTaxRate()));
                            detailInfo.setUuid(invoiceCode + invoiceNo);
                            salesInvoiceDetailDao.insert(detailInfo);
                        }
                    }

                }
                StringBuilder sb = new StringBuilder();
                Iterator iter = set.iterator();
                while (iter.hasNext()) {
                    sb.append(iter.next() + ",");
                }
                if (StringUtils.isNotEmpty(sb.toString())) {
                    invoiceInfo.setIncentiveFlag(sb.substring(0, sb.lastIndexOf(",")));
                }
                DynamicContextHolder.push(dbName + DbConstant.BUSINESS_WRITE);
                // 入底账表
                tdxSaleRecordInvoiceDao.insert(invoiceInfo);

            }

            run.setReturnCode(ReturnCodeEnum.CLCG.getFhzDm());
            run.setReturnMessage(ReturnCodeEnum.CLCG.getFhzMc(ReturnCodeEnum.CLCG.getIndex()));
            interfaceCode.setReturnStateInfo(run);
            interfaceCode.setGlobalInfo(globalInfo);
            return JSONObject.toJSONString(interfaceCode, SerializerFeature.WriteMapNullValue);
        } catch (Exception e) {
           log.info("业务处理异常：{}", e);
            run.setReturnCode(ReturnCodeEnum.CLSB.getFhzDm());
            run.setReturnMessage(ReturnCodeEnum.CLSB.getFhzMc(ReturnCodeEnum.CLSB.getIndex()));
            interfaceCode.setReturnStateInfo(run);
            interfaceCode.setGlobalInfo(globalInfo);
            interfaceCode.setData("");
            return JSONObject.toJSONString(interfaceCode, SerializerFeature.WriteMapNullValue);
        }
    }

    /**
     * @Description 更新特定要素-铁路两个表的信息
     * @param uuid
     * @param tldzkp
     * @Return void
     * @Author wangruwei
     * @Date 2024/5/10 16:30
     **/
    private void updateTdysTldzkyInfo(String uuid, TdxTdysTldzkpEntity tldzkp) {
        log.info("删除t_dx_tdys_tldzkp表关联数据");
        tdxTdysTldzkpCoreDao.delete(new LambdaQueryWrapper<TdxTdysTldzkpEntity>().eq(TdxTdysTldzkpEntity::getUuid, uuid));
        log.info("扩展字段处理。保存t_dx_tdys_tldzkp表");
        tldzkp.setUuid(uuid);
        tldzkp.setCreateTime(new Date());
        tdxTdysTldzkpCoreDao.insert(tldzkp);
    }

    /**
     * @Description 更新特定要素-民航两个表的信息
     * @param uuid
     * @param mhxcdMx  开放平台查验返回的结构实体
     * @Return void
     * @Author wangruwei
     * @Date 2024/5/10 16:29
     **/
    private void updateTdysMhInfo(String uuid, TdxTdysMhxcdEntity mhxcd,List<TdxTdysMhxcdMxEntity> mhxcdMx) {
        log.info("删除t_dx_tdys_mhxcd表");
        tdxTdysMhxcdCoreDao.delete(new LambdaQueryWrapper<TdxTdysMhxcdEntity>().eq(TdxTdysMhxcdEntity::getUuid, uuid));
        log.info("入库t_dx_tdys_mhxcd表");
        mhxcd.setUuid(uuid);
        mhxcd.setCreateTime(new Date());

        tdxTdysMhxcdCoreDao.insert(mhxcd);


        log.info("删除t_dx_tdys_mhxcd_mx表");
        tdxTdysMhxcdMxCoreDao.delete(new LambdaQueryWrapper<TdxTdysMhxcdMxEntity>().eq(TdxTdysMhxcdMxEntity::getTdysId, uuid));
        if(!CollectionUtils.isEmpty(mhxcdMx)){
            log.info("入库t_dx_tdys_mhxcd_mx表");
            for (int i = 0; i < mhxcdMx.size(); i++) {
                TdxTdysMhxcdMxEntity addItem = mhxcdMx.get(i);

                addItem.setTdysId(uuid);
                addItem.setCreateTime(new Date());
                tdxTdysMhxcdMxCoreDao.insert(addItem);
            }
        }
    }



    public TdxSaleRecordInvoiceEntity getSaleInvoiceInfo(SalesInvoicePushInfos info) throws ParseException {
        TdxSaleRecordInvoiceEntity invoice = new TdxSaleRecordInvoiceEntity();
        // 发票代码
        invoice.setInvoiceCode(info.getInvoiceCode());
        // 发票号码
        invoice.setInvoiceNo(info.getInvoiceNo());
        // 数电号码
        invoice.setEleInvoiceNo(info.getEleInvoiceNo());
        // 发票类型
        invoice.setInvoiceType(info.getInvoiceType());
        // 发票来源 0-税控发票 1-全电发票
        invoice.setInvoiceSource(CommonUtil.isSdfp(info.getInvoiceType())?"1":"0");

        // 购方名称
        invoice.setGfName(info.getBuyerName());
        // 购方税号
        invoice.setGfTaxNo(info.getBuyerTaxNo());
        // 购方地址、电话
        invoice.setGfAddressAndPhone(CommonUtil.appendAll(info.getBuyerAddress(),info.getBuyerAddress()));
        // 购方开户行及账号
        invoice.setGfBankAndNo(CommonUtil.appendAll(info.getBuyerBank(),info.getBuyerAccount()));

        // 销方名称
        invoice.setXfName(info.getSalerName());
        // 销方税号
        invoice.setXfTaxNo(info.getSalerTaxNo());
        // 销方开户行及账号
        invoice.setXfBankAndNo(CommonUtil.appendAll(info.getSalerBank(),info.getSalerAccount()));
        // 销方地址、电话
        invoice.setXfAddressAndPhone(CommonUtil.appendAll(info.getSalerAddress(),info.getSalerPhone()));

        // 开票日期
        if (info.getInvoiceDate() != null && !"".equals(info.getInvoiceDate())) {

            invoice.setInvoiceDate(DateUtils.strToDate(info.getInvoiceDate()));
        } else {
            invoice.setInvoiceDate(new Date());
        }
        // 发票金额
        if (info.getInvoiceAmount() != null && !"".equals(info.getInvoiceAmount())) {

            invoice.setInvoiceAmount(new BigDecimal(info.getInvoiceAmount()));
        } else {
            invoice.setInvoiceAmount(new BigDecimal("0"));
        }
        // 发票税额
        if (info.getTaxAmount() != null && !"".equals(info.getTaxAmount())) {

            invoice.setTaxAmount(new BigDecimal(info.getTaxAmount()));
        } else {
            invoice.setTaxAmount(new BigDecimal("0"));
        }
        // 价税合计
        if (info.getTotalAmount() != null && !"".equals(info.getTotalAmount())) {

            invoice.setTotalAmount(new BigDecimal(info.getTotalAmount()));
        } else {
            invoice.setTotalAmount(new BigDecimal("0"));
        }
        // 备注
        invoice.setRemark(info.getRemark());
        // 发票状态
        invoice.setInvoiceStatus(info.getInvoiceStatus());

        // 校验码
        if (info.getCheckCode() == null || "".equals(info.getCheckCode())) {
            invoice.setCheckCode("");
        } else {
            invoice.setCheckCode(info.getCheckCode());
        }

        invoice.setSourceSystem("1");
        invoice.setValid("1");
        invoice.setQsDate(new Date());
        invoice.setQsType("6");
        invoice.setQsStatus("1");
        invoice.setDetailYesorno("1");
        invoice.setMachinecode(info.getJqbm());
        invoice.setPayee(info.getPayee());
        invoice.setReviewer(info.getReviewer());
        invoice.setCreateDate(new Date());
        invoice.setPrintor(info.getInvoicer());
        invoice.setListStatus(info.getListStatus());
        invoice.setSystemName(info.getSystemName());
        //优惠政策
        invoice.setIncentiveFlag(info.getIncentiveFlag());
        //零税率
        invoice.setLslbz(info.getZeroTaxrateFlag());
        return invoice;
    }

    public TDxInvoiceSales getSaleInvoice(SalesInvoicePushInfos info) throws ParseException {
        TDxInvoiceSales invoice = new TDxInvoiceSales();
        // 发票代码
        invoice.setInvoiceCode(info.getInvoiceCode());
        // 发票号码
        invoice.setInvoiceNo(info.getInvoiceNo());
        //数电号码
        invoice.setEleInvoiceNo(info.getEleInvoiceNo());
        // 发票类型
        invoice.setInvoiceType(info.getInvoiceType());
        // 购方名称
        invoice.setGfName(info.getBuyerName());
        // 购方税号
        invoice.setGfTaxNo(info.getBuyerTaxNo());
        // 销方名称
        invoice.setXfName(info.getSalerName());
        // 销方税号
        invoice.setXfTaxNo(info.getSalerTaxNo());
        // 开票日期
        if (info.getInvoiceDate() != null && !"".equals(info.getInvoiceDate())) {

            invoice.setInvoiceDate(DateUtils.strToDate(info.getInvoiceDate()));
        } else {
            invoice.setInvoiceDate(new Date());
        }
        // 发票金额
        if (info.getInvoiceAmount() != null && !"".equals(info.getInvoiceAmount())) {

            invoice.setInvoiceAmount(new BigDecimal(info.getInvoiceAmount()));
        } else {
            invoice.setInvoiceAmount(new BigDecimal("0"));
        }
        // 发票税额
        if (info.getTaxAmount() != null && !"".equals(info.getTaxAmount())) {

            invoice.setTaxAmount(new BigDecimal(info.getTaxAmount()));
        } else {
            invoice.setTaxAmount(new BigDecimal("0"));
        }
        // 价税合计
        if (info.getTotalAmount() != null && !"".equals(info.getTotalAmount())) {

            invoice.setTotalAmount(new BigDecimal(info.getTotalAmount()));
        } else {
            invoice.setTotalAmount(new BigDecimal("0"));
        }
        // 备注
        invoice.setRemark(info.getRemark());
        // 发票状态
        invoice.setInvoiceStatus(info.getInvoiceStatus());

        // 校验码
        if (info.getCheckCode() == null || "".equals(info.getCheckCode())) {
            invoice.setCheckCode("");
        } else {
            invoice.setCheckCode(info.getCheckCode());
        }
        invoice.setValid("1");
        invoice.setQsDate(new Date());
        invoice.setQsType("6");
        invoice.setQsStatus("1");
        invoice.setCreateDate(new Date());
        invoice.setSystemName(info.getSystemName());
        return invoice;
    }

    public VehicleSaleInvoices getVehicle(SalesInvoicePushInfos info) {
        VehicleSaleInvoices vehicleSaleInvoice = new VehicleSaleInvoices();

        vehicleSaleInvoice.setVehicleType(info.getVehicleType());
        vehicleSaleInvoice.setFactoryModel(info.getFactoryModel());
        vehicleSaleInvoice.setProductPlace(info.getProductPlace());
        vehicleSaleInvoice.setCertificate(info.getCertificate());
        vehicleSaleInvoice.setCertificateImport(info.getCertificateImport());
        vehicleSaleInvoice.setInspectionNum(info.getInspectionNum());
        vehicleSaleInvoice.setEngineNo(info.getEngineNo());
        vehicleSaleInvoice.setVehicleNo(info.getVehicleNo());
        vehicleSaleInvoice.setPhone(info.getPhone());
        vehicleSaleInvoice.setBuyerBank(info.getBuyerBank());
        vehicleSaleInvoice.setTaxRate(info.getTaxRate());
        vehicleSaleInvoice.setTaxBureauCode(info.getTaxBureauCode());
        vehicleSaleInvoice.setTaxBureauName(info.getTaxBureauName());
        vehicleSaleInvoice.setTaxRecords(info.getTaxRecords());
        vehicleSaleInvoice.setTonnage(info.getTonnage());
        vehicleSaleInvoice.setLimitPeople(info.getLimitPeople());
        vehicleSaleInvoice.setPlateNo(info.getPlateNo());
        vehicleSaleInvoice.setRegistrationNo(info.getCertificateNo());
        vehicleSaleInvoice.setVehicleAdminOffice(info.getVehicleAdminOffice());
        vehicleSaleInvoice.setAuctionUnit(info.getAuctionUnit());
        vehicleSaleInvoice.setAuctionAddress(info.getAuctionAddress());
        vehicleSaleInvoice.setAuctionBank(info.getAuctionBank());
        vehicleSaleInvoice.setAuctionPhone(info.getAuctionPhone());
        vehicleSaleInvoice.setAuctionTaxNo(info.getAuctionTaxno());
        vehicleSaleInvoice.setCarMarket(info.getCarMarket());
        vehicleSaleInvoice.setCarMarketTaxNo(info.getCarMarketTaxno());
        vehicleSaleInvoice.setCarMarketAddress(info.getCarMarketAddress());
        vehicleSaleInvoice.setCarMarketBank(info.getCarMarketBank());
        vehicleSaleInvoice.setCarMarketPhone(info.getCarMarketPhone());
        vehicleSaleInvoice.setGfPhone(info.getBuyerPhone());

        vehicleSaleInvoice.setYhzcbs(info.getIncentiveFlag());
        vehicleSaleInvoice.setLslbs(info.getZeroTaxrateFlag());
        vehicleSaleInvoice.setZzstsgl(info.getAddedTaxSpecial());

        vehicleSaleInvoice.setBuyerIdNum(info.getBuyerTaxNo());
        //购方
        vehicleSaleInvoice.setBuyerUnitCode(info.getBuyerTaxNo());
        vehicleSaleInvoice.setBuyerUnit(info.getBuyerName());
        vehicleSaleInvoice.setBuyerUnitAddress(info.getBuyerAddress());
        vehicleSaleInvoice.setBuyerPhone(info.getBuyerPhone());

        //销方
        vehicleSaleInvoice.setSellerUnit(info.getSalerName());
        vehicleSaleInvoice.setSellerUnitCode(info.getSalerTaxNo());
        vehicleSaleInvoice.setSellerUnitAddress(info.getSalerAddress());
        vehicleSaleInvoice.setSellerPhone(info.getSalerPhone());

        //二手车市场-销方
        vehicleSaleInvoice.setCarMarket(info.getSalerName());
        vehicleSaleInvoice.setCarMarketTaxNo(info.getSalerTaxNo());
        vehicleSaleInvoice.setCarMarketAddress(info.getSalerAddress());
        vehicleSaleInvoice.setCarMarketBank(info.getSalerBank());
        vehicleSaleInvoice.setCarMarketPhone(info.getSalerPhone());

        //二手车购方电话
        vehicleSaleInvoice.setGfPhone(info.getBuyerPhone());

        return vehicleSaleInvoice;
    }

    /**
     * 统一中英文括号
     *
     * @param paramString
     *            参数
     * @return 返回结果
     */
    public static String changeBrackets(String paramString) {
        return paramString.replace("（", "(").replace("(", "(").replace("）", ")").replace(")", ")");
    }

    public ReturnStateInfo getCheckData(SalesInvoicePushInfos info) {
        ReturnStateInfo run = new ReturnStateInfo();

        if (StringUtils.isBlank(info.getInvoiceCode())) {
            run.setReturnCode(ReturnCodeEnum.FPDMBNWK.getFhzDm());
            run.setReturnMessage(ReturnCodeEnum.FPDMBNWK.getFhzMc(ReturnCodeEnum.FPDMBNWK.getIndex()));
            return run;
        }
        if (StringUtils.isBlank(info.getInvoiceNo())) {
            run.setReturnCode(ReturnCodeEnum.FPHMBNWK.getFhzDm());
            run.setReturnMessage(ReturnCodeEnum.FPHMBNWK.getFhzMc(ReturnCodeEnum.FPHMBNWK.getIndex()));
            return run;
        }
        if (StringUtils.isBlank(info.getInvoiceDate())) {
            run.setReturnCode(ReturnCodeEnum.KPRQBNWK.getFhzDm());
            run.setReturnMessage(ReturnCodeEnum.KPRQBNWK.getFhzMc(ReturnCodeEnum.KPRQBNWK.getIndex()));
            return run;
        }
        if (StringUtils.isBlank(info.getInvoiceType())) {
            run.setReturnCode("3001");
            run.setReturnMessage("发票类型不能为空");
            return run;
        }
        if (StringUtils.isBlank(info.getInvoiceStatus())) {
            run.setReturnCode("3006");
            run.setReturnMessage("发票状态不能为空");
            return run;
        }
        if (!"03".equals(info.getInvoiceType())&& !"187".equals(info.getInvoiceType())&& !"383".equals(info.getInvoiceType())
                && !"15".equals(info.getInvoiceType())&& !"188".equals(info.getInvoiceType())&& !"184".equals(info.getInvoiceType())

        ) {
            if (StringUtils.isBlank(info.getBuyerTaxNo())) {
                run.setReturnCode("3002");
                run.setReturnMessage("购方税号不能为空");
                return run;
            }
            if (StringUtils.isBlank(info.getBuyerName())) {
                run.setReturnCode("3003");
                run.setReturnMessage("购方名称不能为空");
                return run;
            }
            if (StringUtils.isBlank(info.getSalerAccount())) {
                run.setReturnCode("3004");
                run.setReturnMessage("销方税号不能为空");
                return run;
            }
            if (StringUtils.isBlank(info.getSalerName())) {
                run.setReturnCode("3005");
                run.setReturnMessage("销方名称不能为空");
                return run;
            }
            // 数电纸票（增值税专用发票）、数电纸票（普通发票）、增值税专用发票、增值税普通发票 校验清单标识不能为空，其他票种不做限制
            if("185".equals(info.getInvoiceType())||"186".equals(info.getInvoiceType())||"01".equals(info.getInvoiceType())||"04".equals(info.getInvoiceType())){
                if (StringUtils.isBlank(info.getListStatus())) {
                    run.setReturnCode("3007");
                    run.setReturnMessage("销货清单标识不能为空");
                    return run;
                }
            }


            List<InvoiceDetailInfo> details = info.getDetailList();
            if (details != null && details.size() > 0) {

                for (InvoiceDetailInfo detailInfo : details) {
                    if (StringUtils.isBlank(detailInfo.getGoodsName())) {
                        run.setReturnCode("3008");
                        run.setReturnMessage("税收分类编码不能为空");
                        return run;
                    }
                    if (StringUtils.isBlank(detailInfo.getDetailAmount())) {
                        run.setReturnCode("3009");
                        run.setReturnMessage("明细金额不能为空");
                        return run;
                    }

                    if (StringUtils.isBlank(detailInfo.getTaxRate())) {
                        run.setReturnCode("3010");
                        run.setReturnMessage("税率不能为空");
                        return run;
                    }

                    if (StringUtils.isBlank(detailInfo.getTaxAmount())) {
                        run.setReturnCode("3011");
                        run.setReturnMessage("明细税额不能为空");
                        return run;
                    }

                }
            }
        } else if ("03".equals(info.getInvoiceType())||"187".equals(info.getInvoiceType())||"383".equals(info.getInvoiceType())) {
            if (StringUtils.isBlank(info.getInvoiceAmount())) {
                run.setReturnCode("3012");
                run.setReturnMessage("不含税金额不能为空");
                return run;
            }
        }

        return run;
    }
}
