package com.dxhy.erp.service.impl;

import cn.hutool.core.codec.Base64;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.dxhy.common.constant.DbConstant;
import com.dxhy.common.datasource.config.DynamicContextHolder;
import com.dxhy.common.enums.ReturnCodeEnum;
import com.dxhy.common.service.impl.MpBaseServiceImpl;
import com.dxhy.common.util.pojo.Authorize;
import com.dxhy.common.util.pojo.GlobalInfo;
import com.dxhy.erp.controller.SDNYMainProcessController;
import com.dxhy.erp.dao.SysDeptDao;
import com.dxhy.erp.dao.TdxRecordInvoiceDao;
import com.dxhy.erp.entity.SysDeptEntity;
import com.dxhy.erp.entity.TdxRecordInvoice;
import com.dxhy.erp.entity.sdny.SNRequestObject;
import com.dxhy.erp.model.*;
import com.dxhy.erp.model.auth.InterfaceCode;
import com.dxhy.erp.service.GatherService;
import com.dxhy.erp.utils.CheckUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author dxhy
 */
@SuppressWarnings({"AlibabaUndefineMagicConstant", "AlibabaMethodTooLong", "AlibabaAvoidComplexCondition"})
@Service("gatherService")
@Slf4j
public class GatherServiceImpl extends MpBaseServiceImpl<TdxRecordInvoiceDao, TdxRecordInvoice>
    implements GatherService {

    private static final Map<String, Integer> M = new HashMap<>();

    private static final Map<String, Integer> HASH = new HashMap<>();
    @Value("${erp.collectNum}")
    private String collectNum;
    @Value("${erp.stateNum}")
    private String stateNum;

    private String userNum;
    @Resource
    private SysDeptDao sysDeptDao;

    @Resource
    private SDNYMainProcessController mainService;

    @Override
    public String get(GlobalInfo globalInfo, Map<String, String> map, HttpServletRequest request,
        HttpServletResponse response, Authorize authorize) {
        ReturnStateInfo run = new ReturnStateInfo();
        List<TdxRecordInvoice> list;
        List<InvoiceDetailInfo> detailList;
        List<VehicleSaleInvoices> vehicleList;
        CollectData data;
        try {
            data = JSON.parseObject(map.get("data"), CollectData.class);
            run = getCheck(data);
            if (run.getReturnCode() != null || run.getReturnMessage() != null) {
                InterfaceCode interfaceCode = new InterfaceCode();
                interfaceCode.setGlobalInfo(globalInfo);
                interfaceCode.setReturnStateInfo(run);
                return JSON.toJSONString(interfaceCode);
            }
            if (StringUtils.isNotBlank(data.getQsDateBegin()) || StringUtils.isNotBlank(data.getQsDateEnd())) {
                data.setQsStatus("1");
            }
            if (StringUtils.isNotBlank(data.getTaxPeriod())) {
                data.setRzhStatus("1");
            }
            DynamicContextHolder.push(DbConstant.BASICS_READ);
            SysDeptEntity deptEntity = sysDeptDao.getOrg(data.getBuyerTaxNo());
            String dbName;
            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 interfaceCode = new InterfaceCode();
                interfaceCode.setGlobalInfo(globalInfo);
                interfaceCode.setReturnStateInfo(runInfo);
                return JSON.toJSONString(interfaceCode);
            }
            Integer total;
            try {
                userNum = collectNum;
                total = M.get(data.getBatchNo());
                if (total == null) {
                    DynamicContextHolder.push(dbName + DbConstant.BUSINESS_READ);
                    total = selectByAllCount(data);
                    M.put(data.getBatchNo(), total);
                }
            } catch (Exception e) {
                log.info("获取总条数错误：" + e);
                DynamicContextHolder.push(dbName + DbConstant.BUSINESS_READ);
                total = selectByAllCount(data);
                M.put(data.getBatchNo(), total);
                e.printStackTrace();
            }
            if ("1".equals(data.getStatus())) {
                int mxsize = 0;
                int startRow = data.getStartRow();
                String requestRow = data.getRequestRow();
                if (StringUtils.isNotBlank(requestRow)) {
                    userNum = requestRow;
                }
                // 01回传信息
                List<InvoiceInfo> invoices = new ArrayList<>();
                // 03机动车回传信息
                List<VehicleSaleInvoiceInfos> vehicleInvoiceInfos = new ArrayList<>();
                //15二手车
                List<ESCVehicleSaleInvoiceInfos> escVehicleSaleInvoiceInfosList = new ArrayList<>();
                List<?> invoiceList = new ArrayList<>();
                boolean continueQuery = true;
                while (continueQuery && mxsize < Integer.parseInt(userNum) && invoices.size() < total
                    && startRow <= total) {
                    DynamicContextHolder.push(dbName + DbConstant.BUSINESS_READ);
                    list = selectByCollect(data, startRow, 100);
                    log.info("-----------获取发票完成----------" + globalInfo.getDataExchangeId());
                    startRow += 100;
                    for (TdxRecordInvoice info : list) {
                        String uuid = (StringUtils.isBlank(info.getInvoiceCode())?"":info.getInvoiceCode()) + info.getInvoiceNo();
                        if ("03".equals(info.getInvoiceType())) {
                            DynamicContextHolder.push(dbName + DbConstant.BUSINESS_READ);
                            vehicleList = selectVehicle(uuid);
                            if (vehicleList != null && vehicleList.size() > 0) {
                                mxsize += vehicleList.size();
                                for (VehicleSaleInvoices vehicle : vehicleList) {
                                    VehicleSaleInvoiceInfos vehicleInfo = getVehicleInfo(vehicle, info);
                                    vehicleInvoiceInfos.add(vehicleInfo);
                                }
                                if (mxsize > Integer.parseInt(userNum)) {
                                    continueQuery = false;
                                    break;
                                }
                            }
                        }else   if ("15".equals(info.getInvoiceType())) {
                            DynamicContextHolder.push(dbName + DbConstant.BUSINESS_READ);
                            vehicleList = selectVehicle(uuid);
                            if (vehicleList != null && vehicleList.size() > 0) {
                                mxsize += vehicleList.size();
                                for (VehicleSaleInvoices vehicle : vehicleList) {
                                    ESCVehicleSaleInvoiceInfos vehicleInfo = getEscVehicleInfo(vehicle, info);
                                    escVehicleSaleInvoiceInfosList.add(vehicleInfo);
                                }
                                if (mxsize > Integer.parseInt(userNum)) {
                                    continueQuery = false;
                                    break;
                                }
                            }
                        } else {
                            DynamicContextHolder.push(dbName + DbConstant.DETAIL_READ);
                            detailList = getDetailInfo(uuid);
                            List<InvoiceDetailInfo> listInfo = new ArrayList<>();
                            if (detailList != null && detailList.size() > 0) {
                                mxsize += detailList.size();
                                for (InvoiceDetailInfo detail : detailList) {
                                    InvoiceDetailInfo detailInfo = getInvoiceDetailInfo(detail);
                                    listInfo.add(detailInfo);
                                }
                            }
                            InvoiceInfo invoiceInfo = getInvoiceInfo(info);
                            invoiceInfo.setDetailList(listInfo);
                            invoices.add(invoiceInfo);
                            if (mxsize >= Integer.parseInt(collectNum)) {
                                continueQuery = false;
                                break;
                            }
                        }
                    }
                }
                log.info("===========发票实体转换完成============" + globalInfo.getDataExchangeId());
                GatherData gather = new GatherData();
                gather.setInvoiceType(data.getInvoiceType());
                gather.setStartRow(data.getStartRow());
                gather.setTotalRows(total);
                gather.setContentRows(invoices.size() + vehicleInvoiceInfos.size());
                RecordInvoices recordInvoices = new RecordInvoices();
                if (vehicleInvoiceInfos.size() > 0) {
                    gather.setInvoices(vehicleInvoiceInfos);
                }
                if (invoices.size() > 0) {
                    gather.setInvoices(invoices);
                }
                if (escVehicleSaleInvoiceInfosList.size() > 0) {
                    gather.setInvoices(escVehicleSaleInvoiceInfosList);
                }
                String result = JSON.toJSONString(gather);
                run.setReturnCode(ReturnCodeEnum.CLCG.getFhzDm());
                run.setReturnMessage(ReturnCodeEnum.CLCG.getFhzMc(ReturnCodeEnum.CLCG.getIndex()));
                InterfaceCode interfaceCode = new InterfaceCode();
                interfaceCode.setGlobalInfo(globalInfo);
                interfaceCode.setReturnStateInfo(run);
                interfaceCode.setData(Base64.encode(result));
                return JSON.toJSONString(interfaceCode);
            } else if ("0".equals(data.getStatus())) {
                M.remove(data.getBatchNo());
                run.setReturnCode("0000");
                run.setReturnMessage("处理成功");
                String globalJson = null;
                String runJson = null;
                try {
                    runJson = JSON.toJSONString(run);
                    globalJson = JSON.toJSONString(globalInfo);
                } catch (Exception ignored) {
                }
                response.setCharacterEncoding("UTF-8");
                response.setContentType("application/json; charset=utf-8");
                return "{\"globalInfo\":" + globalJson + ",\"returnStateInfo\":" + runJson + "}";
            } else {
                run.setReturnCode("9999");
                run.setReturnMessage("处理失败");
                String globalJson = null;
                String runJson = null;
                try {
                    runJson = JSON.toJSONString(run);
                    globalJson = JSON.toJSONString(globalInfo);
                } catch (Exception ignored) {
                }
                response.setCharacterEncoding("UTF-8");
                response.setContentType("application/json; charset=utf-8");
                return "{\"globalInfo\":" + globalJson + ",\"returnStateInfo\":" + runJson + "}";
            }

        } catch (Exception e) {
            e.printStackTrace();
            run.setReturnCode("2011");
            run.setReturnMessage("其他异常");
            String globalJson = null;
            String runJson = null;
            try {
                runJson = JSON.toJSONString(run);
                globalJson = JSON.toJSONString(globalInfo);
            } catch (Exception ignored) {
            }
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json; charset=utf-8");
            return "{\"globalInfo\":" + globalJson + ",\"returnStateInfo\":" + runJson + "}";
        }
    }

    @Override
    public String getState(GlobalInfo globalInfo, Map<String, String> map, HttpServletRequest request,
        HttpServletResponse response, Authorize authorize) {
        ReturnStateInfo run = new ReturnStateInfo();
        List<State> list;
        try {
            StateData data = JSONObject.parseObject(map.get("data"), StateData.class);
            run = getCheckState(data);
            if (run.getReturnCode() != null || run.getReturnMessage() != null) {
                InterfaceCode interfaceCode = new InterfaceCode();
                interfaceCode.setGlobalInfo(globalInfo);
                interfaceCode.setReturnStateInfo(run);
                return JSON.toJSONString(interfaceCode);
            }
            DynamicContextHolder.push(DbConstant.BASICS_READ);
            SysDeptEntity deptEntity = sysDeptDao.getOrg(data.getBuyerTaxNo());
            String dbName;
            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 interfaceCode = new InterfaceCode();
                interfaceCode.setGlobalInfo(globalInfo);
                interfaceCode.setReturnStateInfo(runInfo);
                return JSON.toJSONString(interfaceCode);
            }
            Integer total;
            DynamicContextHolder.push(dbName + DbConstant.BUSINESS_READ);
            try {
                total = HASH.get(data.getBatchNo());
                if (total == null || total == 0) {

                    total = selectByStateAllCount(data.getStatusChangeDateBegin(), data.getStatusChangeDateEnd(),
                        data.getBuyerTaxNo());
                    HASH.put(data.getBatchNo(), total);
                }
            } catch (Exception e) {
                total = selectByStateAllCount(data.getStatusChangeDateBegin(), data.getStatusChangeDateEnd(),
                    data.getBuyerTaxNo());
                HASH.put(data.getBatchNo(), total);
            }

            if ("1".equals(data.getStatus())) {
                int startRow = data.getStartRow();
                List<State> infos = new ArrayList<>();
                boolean continueQuery = true;

                while (continueQuery && infos.size() < Integer.parseInt(stateNum) && infos.size() < total
                    && startRow <= total) {
                    list = selectByState(data.getStatusChangeDateBegin(), data.getStatusChangeDateEnd(),
                        data.getBuyerTaxNo(), startRow, 1000);
                    startRow += 1000;
                    for (State ss : list) {
                        State stateInfo = this.getStateInfo(ss);
                        infos.add(stateInfo);
                        if (infos.size() >= Integer.parseInt(stateNum)) {
                            continueQuery = false;
                            break;
                        }
                    }

                }
                GatherData status = new GatherData();
                status.setContentRows(infos.size());
                status.setStartRow(data.getStartRow());
                status.setTotalRows(total);
                status.setInvoices(infos);
                String result = JSON.toJSONString(status);
                run.setReturnCode(ReturnCodeEnum.CLCG.getFhzDm());
                run.setReturnMessage(ReturnCodeEnum.CLCG.getFhzMc(ReturnCodeEnum.CLCG.getIndex()));
                InterfaceCode interfaceCode = new InterfaceCode();
                interfaceCode.setReturnStateInfo(run);
                interfaceCode.setGlobalInfo(globalInfo);
                interfaceCode.setData(Base64.encode(result));
                return JSON.toJSONString(interfaceCode);
            } else if ("0".equals(data.getStatus())) {
                HASH.remove(data.getBatchNo());
                run.setReturnCode(ReturnCodeEnum.CLCG.getFhzDm());
                run.setReturnMessage(ReturnCodeEnum.CLCG.getFhzMc(ReturnCodeEnum.CLCG.getIndex()));
                InterfaceCode interfaceCode = new InterfaceCode();
                interfaceCode.setReturnStateInfo(run);
                interfaceCode.setGlobalInfo(globalInfo);
                return JSON.toJSONString(interfaceCode);

            } else {
                run.setReturnCode(ReturnCodeEnum.CLSB.getFhzDm());
                run.setReturnMessage(ReturnCodeEnum.CLSB.getFhzMc(ReturnCodeEnum.CLSB.getIndex()));
                InterfaceCode interfaceCode = new InterfaceCode();
                interfaceCode.setReturnStateInfo(run);
                interfaceCode.setGlobalInfo(globalInfo);
                return JSON.toJSONString(interfaceCode);
            }
        } catch (Exception e) {
            run.setReturnCode(ReturnCodeEnum.QTYC.getFhzDm());
            run.setReturnMessage(ReturnCodeEnum.QTYC.getFhzMc(ReturnCodeEnum.QTYC.getIndex()));
            InterfaceCode interfaceCode = new InterfaceCode();

            try {
                interfaceCode.setReturnStateInfo(run);
                interfaceCode.setGlobalInfo(globalInfo);
            } catch (Exception ignored) {
            }
            return JSON.toJSONString(interfaceCode);
        }
    }

    @Override
    public String getSingle(GlobalInfo globalInfo, Map<String, String> map, HttpServletRequest request,
        HttpServletResponse response, Authorize authorize) {
        ReturnStateInfo run = new ReturnStateInfo();
        List<TdxRecordInvoice> list = null;
        List<InvoiceDetailInfo> detailList;
        List<VehicleSaleInvoices> vehicleList;
        SingleInvoiceReq data;
        try {
            data = JSON.parseObject(map.get("data"), SingleInvoiceReq.class);
            run = getCheckSingle(data);
            if (run.getReturnCode() != null || run.getReturnMessage() != null) {
                InterfaceCode interfaceCode = new InterfaceCode();
                interfaceCode.setGlobalInfo(globalInfo);
                interfaceCode.setReturnStateInfo(run);
                return JSON.toJSONString(interfaceCode);
            }
            DynamicContextHolder.push(DbConstant.BASICS_READ);
            SysDeptEntity deptEntity = sysDeptDao.getOrg(data.getBuyerTaxNo());
            String dbName;
            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 interfaceCode = new InterfaceCode();
                interfaceCode.setGlobalInfo(globalInfo);
                interfaceCode.setReturnStateInfo(runInfo);
                return JSON.toJSONString(interfaceCode);
            }
            DynamicContextHolder.push(dbName + DbConstant.BUSINESS_READ);
            TdxRecordInvoice recordInvoice =
                this.baseMapper.selectSingleInvoice(data.getBuyerTaxNo(), data.getInvoiceCode(), data.getInvoiceNo());
            VehicleSaleInvoiceInfos vehicleInfo = null;
            InvoiceInfo invoiceInfo = null;
            //15二手车
            ESCVehicleSaleInvoiceInfos vehicleInfos = null;
            if (recordInvoice != null) {
                if ("03".equals(recordInvoice.getInvoiceType())) {
                    DynamicContextHolder.push(dbName + DbConstant.BUSINESS_READ);
//                    vehicleList = selectVehicle(recordInvoice.getInvoiceCode() + recordInvoice.getInvoiceNo());
                    vehicleList = selectVehicle(recordInvoice.getUuid());
                    if (vehicleList != null && vehicleList.size() > 0) {
                        VehicleSaleInvoices vehicle = vehicleList.get(0);
                        vehicleInfo = getVehicleInfo(vehicle, recordInvoice);
                    }
                } else   if ("15".equals(recordInvoice.getInvoiceType())) {
                    DynamicContextHolder.push(dbName + DbConstant.BUSINESS_READ);
                    vehicleList = selectVehicle(recordInvoice.getUuid());
                    if (vehicleList != null && vehicleList.size() > 0) {
                        for (VehicleSaleInvoices vehicle : vehicleList) {
                            vehicleInfos = getEscVehicleInfo(vehicle, recordInvoice);
                        }
                    }
                }else {
                    DynamicContextHolder.push(dbName + DbConstant.DETAIL_READ);
//                    detailList = getDetailInfo(recordInvoice.getInvoiceCode() + recordInvoice.getInvoiceNo());
                    detailList = getDetailInfo(recordInvoice.getUuid());
                    List<InvoiceDetailInfo> listInfo = new ArrayList<>();
                    if (detailList != null && detailList.size() > 0) {
                        for (InvoiceDetailInfo detail : detailList) {
                            InvoiceDetailInfo detailInfo = getInvoiceDetailInfo(detail);
                            listInfo.add(detailInfo);
                        }
                    }
                    invoiceInfo = getInvoiceInfo(recordInvoice);
                    invoiceInfo.setDetailList(listInfo);

                }
            } else {
                ReturnStateInfo runInfo = new ReturnStateInfo();
                runInfo.setReturnCode(ReturnCodeEnum.FPBCZ.getFhzDm());
                runInfo.setReturnMessage(ReturnCodeEnum.FPBCZ.getFhzMc(ReturnCodeEnum.FPBCZ.getIndex()));
                InterfaceCode interfaceCode = new InterfaceCode();
                interfaceCode.setGlobalInfo(globalInfo);
                interfaceCode.setReturnStateInfo(runInfo);
                return JSON.toJSONString(interfaceCode);
            }
            log.info("===========发票实体转换完成============" + globalInfo.getDataExchangeId());

            String result = "";
            if (vehicleInfo != null) {
                result = JSON.toJSONString(vehicleInfo);
            }
            if (invoiceInfo != null) {
                result = JSON.toJSONString(invoiceInfo);
            }
            if (vehicleInfos != null) {
                result = JSON.toJSONString(vehicleInfos);
            }
            run.setReturnCode(ReturnCodeEnum.CLCG.getFhzDm());
            run.setReturnMessage(ReturnCodeEnum.CLCG.getFhzMc(ReturnCodeEnum.CLCG.getIndex()));
            InterfaceCode interfaceCode = new InterfaceCode();
            interfaceCode.setGlobalInfo(globalInfo);
            interfaceCode.setReturnStateInfo(run);
            interfaceCode.setData(Base64.encode(result));
            return JSON.toJSONString(interfaceCode);

        } catch (Exception e) {
            e.printStackTrace();
            run.setReturnCode("2011");
            run.setReturnMessage("其他异常");
            String globalJson = null;
            String runJson = null;
            try {
                runJson = JSON.toJSONString(run);
                globalJson = JSON.toJSONString(globalInfo);
            } catch (Exception ignored) {
            }
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json; charset=utf-8");
            return "{\"globalInfo\":" + globalJson + ",\"returnStateInfo\":" + runJson + "}";
        }
    }

    @Override
    public String getAuthResult(GlobalInfo globalInfo, Map<String, String> map, HttpServletRequest request,
        HttpServletResponse response, Authorize authorize) {
        ReturnStateInfo run = new ReturnStateInfo();
        List<AuthStatus> list;
        CollectData data;
        try {
            data = JSON.parseObject(map.get("data"), CollectData.class);
            run = getCheckRz(data);
            if (run.getReturnCode() != null || run.getReturnMessage() != null) {
                InterfaceCode interfaceCode = new InterfaceCode();
                interfaceCode.setGlobalInfo(globalInfo);
                interfaceCode.setReturnStateInfo(run);
                return JSON.toJSONString(interfaceCode);
            }
            DynamicContextHolder.push(DbConstant.BASICS_READ);
            SysDeptEntity deptEntity = sysDeptDao.getOrg(data.getBuyerTaxNo());
            String dbName;
            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 interfaceCode = new InterfaceCode();
                interfaceCode.setGlobalInfo(globalInfo);
                interfaceCode.setReturnStateInfo(runInfo);
                return JSON.toJSONString(interfaceCode);
            }
            Integer total;
            try {
                userNum = collectNum;
                total = M.get(data.getBatchNo());
                if (total == null) {
                    DynamicContextHolder.push(dbName + DbConstant.BUSINESS_READ);
                    total = selectAuthResultCount(data);
                    M.put(data.getBatchNo(), total);
                }
            } catch (Exception e) {
                log.info("获取总条数错误：" + e);
                DynamicContextHolder.push(dbName + DbConstant.BUSINESS_READ);
                total = selectAuthResultCount(data);
                M.put(data.getBatchNo(), total);
                e.printStackTrace();
            }
            if ("1".equals(data.getStatus())) {
                int mxsize = 0;
                int startRow = data.getStartRow();
                String requestRow = data.getRequestRow();
                if (StringUtils.isNotBlank(requestRow)) {
                    userNum = requestRow;
                }
                // 01回传信息
                List<AuthStatus> invoices = new ArrayList<>();
                List<?> invoiceList = new ArrayList<>();
                DecimalFormat df = new DecimalFormat("#0.00");
                boolean continueQuery = true;
                while (continueQuery && mxsize < Integer.parseInt(userNum) && invoices.size() < total
                    && startRow <= total) {
                    DynamicContextHolder.push(dbName + DbConstant.BUSINESS_READ);
                    list = selectAllAuthResult(data, startRow, 100);
                    log.info("-----------获取发票完成----------" + globalInfo.getDataExchangeId());
                    startRow += 100;

                    for (AuthStatus info : list) {
                        if ("6".equals(info.getAuthState())) {
                            info.setAuthState("0");
                        }
                        info.setInvoiceAmount(df.format(new BigDecimal(info.getInvoiceAmount())));
                        info.setTaxAmount(df.format(new BigDecimal(info.getTaxAmount())));
                        info.setTaxCredit(df.format(new BigDecimal(info.getTaxCredit())));
                        invoices.add(info);
                        mxsize++;
                        if (mxsize >= Integer.parseInt(userNum)) {
                            continueQuery = false;
                            break;
                        }
                    }
                }
                log.info("===========发票实体转换完成============" + globalInfo.getDataExchangeId());
                GatherData gather = new GatherData();
                gather.setInvoiceType(data.getInvoiceType());
                gather.setStartRow(data.getStartRow());
                gather.setTotalRows(total);
                gather.setContentRows(invoices.size());
                if (invoices.size() > 0) {
                    gather.setInvoices(invoices);
                }
                String result = JSON.toJSONString(gather);
                run.setReturnCode(ReturnCodeEnum.CLCG.getFhzDm());
                run.setReturnMessage(ReturnCodeEnum.CLCG.getFhzMc(ReturnCodeEnum.CLCG.getIndex()));
                InterfaceCode interfaceCode = new InterfaceCode();
                interfaceCode.setGlobalInfo(globalInfo);
                interfaceCode.setReturnStateInfo(run);
                interfaceCode.setData(Base64.encode(result));
                return JSON.toJSONString(interfaceCode);
            } else if ("0".equals(data.getStatus())) {
                M.remove(data.getBatchNo());
                run.setReturnCode("0000");
                run.setReturnMessage("处理成功");
                String globalJson = null;
                String runJson = null;
                try {
                    runJson = JSON.toJSONString(run);
                    globalJson = JSON.toJSONString(globalInfo);
                } catch (Exception ignored) {
                }
                response.setCharacterEncoding("UTF-8");
                response.setContentType("application/json; charset=utf-8");
                return "{\"globalInfo\":" + globalJson + ",\"returnStateInfo\":" + runJson + "}";
            } else {
                run.setReturnCode("9999");
                run.setReturnMessage("处理失败");
                String globalJson = null;
                String runJson = null;
                try {
                    runJson = JSON.toJSONString(run);
                    globalJson = JSON.toJSONString(globalInfo);
                } catch (Exception ignored) {
                }
                response.setCharacterEncoding("UTF-8");
                response.setContentType("application/json; charset=utf-8");
                return "{\"globalInfo\":" + globalJson + ",\"returnStateInfo\":" + runJson + "}";
            }

        } catch (Exception e) {
            e.printStackTrace();
            run.setReturnCode("2011");
            run.setReturnMessage("其他异常");
            String globalJson = null;
            String runJson = null;
            try {
                runJson = JSON.toJSONString(run);
                globalJson = JSON.toJSONString(globalInfo);
            } catch (Exception ignored) {
            }
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json; charset=utf-8");
            return "{\"globalInfo\":" + globalJson + ",\"returnStateInfo\":" + runJson + "}";
        }
    }

    public InvoiceInfo getInvoiceInfo(TdxRecordInvoice invoice) {
        DecimalFormat df = new DecimalFormat("#0.00");
        InvoiceInfo info = new InvoiceInfo();
        if(StringUtils.isNotBlank(invoice.getEleInvoiceNo())){
            info.setEleInvoiceNo(invoice.getEleInvoiceNo());
        }else {
            info.setEleInvoiceNo("");
        }
        info.setInvoiceCode(invoice.getInvoiceCode());
        info.setInvoiceNo(invoice.getInvoiceNo());
        info.setInvoiceDate(new SimpleDateFormat("yyyyMMdd").format(invoice.getInvoiceDate()));
        if (invoice.getGfBankAndNo() == null) {
            info.setBuyerAccount("");
        } else {
            info.setBuyerAccount(invoice.getGfBankAndNo());
        }
        if (invoice.getGfAddressAndPhone() == null) {
            info.setBuyerAddressPhone("");
        } else {
            info.setBuyerAddressPhone(invoice.getGfAddressAndPhone());
        }
        if (invoice.getGfName() == null) {
            info.setBuyerName("");
        } else {

            info.setBuyerName(invoice.getGfName());
        }

        info.setBuyerTaxNo(invoice.getGfTaxNo());
        if (invoice.getXfBankAndNo() == null) {
            info.setSalerAccount("");
        } else {
            info.setSalerAccount(invoice.getXfBankAndNo());
        }
        if (invoice.getXfAddressAndPhone() == null) {
            info.setSalerAddressPhone("");
        } else {
            info.setSalerAddressPhone(invoice.getXfAddressAndPhone());
        }
        if (invoice.getXfName() == null) {
            info.setSalerName("");
        } else {
            info.setSalerName(invoice.getXfName());

        }
        info.setSalerTaxNo(invoice.getXfTaxNo());
        info.setInvoiceAmount(df.format(invoice.getInvoiceAmount()));
        info.setTaxAmount(df.format(invoice.getTaxAmount()));
        info.setTotalAmount(df.format(invoice.getTotalAmount()));
        if (invoice.getRemark() == null) {
            info.setRemark("");
        } else {
            info.setRemark(invoice.getRemark());
        }
        info.setCurrentTaxPeriod(invoice.getDqskssq());
        info.setLegalizeEndDate(invoice.getGxjzr());
        info.setLegalizeInvoiceDateBegin(invoice.getGxfwq());
        info.setLegalizeInvoiceDateEnd(invoice.getGxfwz());
        if (invoice.getRzhDate() == null) {
            info.setLegalizeDate("");
        } else {
            info.setLegalizeDate(new SimpleDateFormat("yyyyMMdd").format(invoice.getRzhDate()));
        }
        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 (invoice.getRzlx() == null) {
            info.setRzlx("");
        } 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 (invoice.getRzhType() == null) {
            info.setLegalizeType("");
        } else {
            info.setLegalizeType(invoice.getRzhType());
        }
        if (StringUtils.isNotBlank(invoice.getGlzt())) {
            info.setManagementStatus(invoice.getGlzt());
        } else {
            info.setManagementStatus("");
        }
        if (StringUtils.isNotBlank(invoice.getXxly())) {
            info.setInformationSources(invoice.getXxly());
        } else {
            info.setInformationSources("");
        }
        if ("1".equals(invoice.getRzlx()) || "4".equals(invoice.getRzlx())) {
            info.setTaxCredit(df.format(invoice.getDkTaxAmount()));
        } else {
            info.setTaxCredit("");
        }
        if (StringUtils.isNotBlank(invoice.getYqkgxbz())) {
            info.setOverdueCheckMark(invoice.getYqkgxbz());
        } else {
            info.setOverdueCheckMark("");
        }
        if (StringUtils.isNotBlank(invoice.getYclx())) {
            info.setExceptionType(invoice.getYclx());
        } else {
            info.setExceptionType("");
        }
        if (StringUtils.isNotBlank(invoice.getQsStatus())) {
            info.setQsStatus(invoice.getQsStatus());
        } else {
            info.setQsStatus("");
        }
        if (StringUtils.isNotBlank(invoice.getQsName())) {
            info.setQsUser(invoice.getQsName());
        } else {
            info.setQsUser("");
        }
        if (invoice.getQsDate() != null) {
            info.setQsDate(new SimpleDateFormat("yyyyMMddHHmmss").format(invoice.getQsDate()));
        } else {
            info.setQsDate("");
        }
        return info;
    }

    @Override
    public String singleInvoiceChenck(GlobalInfo globalInfo, Map<String, String> map, HttpServletRequest request,
                            HttpServletResponse response, Authorize authorize) {
        ReturnStateInfo run = new ReturnStateInfo();
        try {
            if (run.getReturnCode() != null || run.getReturnMessage() != null) {
                InterfaceCode interfaceCode = new InterfaceCode();
                interfaceCode.setGlobalInfo(globalInfo);
                interfaceCode.setReturnStateInfo(run);
                return JSON.toJSONString(interfaceCode);
            }
            String dbName = "business";
            DynamicContextHolder.push(dbName + DbConstant.BUSINESS_READ);
            Map<String, String> param = JSONObject.parseObject(map.get("data").getBytes(),Map.class);
            ResponseEntity<String> responseEntity = mainService.singleInvoiceCheck(param);
            String body = responseEntity.getBody();

//            Map<String, String> resultMap = Arrays.asList(body.split("=")).stream()
//                    .map(elem -> elem.split(":"))
//                    .collect(Collectors.toMap(e -> e[0], e -> e[1]));

            String result = "";
            if (body != null) {
                result = body;
            } else {
                ReturnStateInfo runInfo = new ReturnStateInfo();
                runInfo.setReturnCode(ReturnCodeEnum.FPBCZ.getFhzDm());
                runInfo.setReturnMessage(ReturnCodeEnum.FPBCZ.getFhzMc(ReturnCodeEnum.FPBCZ.getIndex()));
                InterfaceCode interfaceCode = new InterfaceCode();
                interfaceCode.setGlobalInfo(globalInfo);
                interfaceCode.setReturnStateInfo(runInfo);
                return JSON.toJSONString(interfaceCode);
            }
            log.info("===========发票实体转换完成============" + globalInfo.getDataExchangeId());

            run.setReturnCode(ReturnCodeEnum.CLCG.getFhzDm());
            run.setReturnMessage(ReturnCodeEnum.CLCG.getFhzMc(ReturnCodeEnum.CLCG.getIndex()));
            InterfaceCode interfaceCode = new InterfaceCode();
            interfaceCode.setGlobalInfo(globalInfo);
            interfaceCode.setReturnStateInfo(run);
            interfaceCode.setData(Base64.encode(result));
            return JSON.toJSONString(interfaceCode);

        } catch (Exception e) {
            e.printStackTrace();
            log.error("发生异常,报错信息为:{}",e);
            run.setReturnCode("2011");
            run.setReturnMessage("其他异常");
            String globalJson = null;
            String runJson = null;
            try {
                runJson = JSON.toJSONString(run);
                globalJson = JSON.toJSONString(globalInfo);
            } catch (Exception ignored) {
            }
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json; charset=utf-8");
            return "{\"globalInfo\":" + globalJson + ",\"returnStateInfo\":" + runJson + "}";
        }
    }

    @Override
    public String syncInvoiceInfo(GlobalInfo globalInfo, Map<String, String> map, HttpServletRequest request,
                                      HttpServletResponse response, Authorize authorize) {
        ReturnStateInfo run = new ReturnStateInfo();
        try {
            if (run.getReturnCode() != null || run.getReturnMessage() != null) {
                InterfaceCode interfaceCode = new InterfaceCode();
                interfaceCode.setGlobalInfo(globalInfo);
                interfaceCode.setReturnStateInfo(run);
                return JSON.toJSONString(interfaceCode);
            }
            String dbName = "business";
            DynamicContextHolder.push(dbName + DbConstant.BUSINESS_READ);
            String data = map.get("data");

            SNRequestObject snRequestObject = JSONObject.parseObject(data.getBytes(), SNRequestObject.class);
            ResponseEntity<?> responseEntity = mainService.syncInvoiceInfo(snRequestObject);
            String body = responseEntity.getBody().toString();
            body = body.replaceAll("=",":");
            String result = "";
            if (body != null) {
                result = body;
            } else {
                ReturnStateInfo runInfo = new ReturnStateInfo();
                runInfo.setReturnCode(ReturnCodeEnum.FPBCZ.getFhzDm());
                runInfo.setReturnMessage(ReturnCodeEnum.FPBCZ.getFhzMc(ReturnCodeEnum.FPBCZ.getIndex()));
                InterfaceCode interfaceCode = new InterfaceCode();
                interfaceCode.setGlobalInfo(globalInfo);
                interfaceCode.setReturnStateInfo(runInfo);
                return JSON.toJSONString(interfaceCode);
            }
            log.info("===========发票实体转换完成============" + globalInfo.getDataExchangeId());

            run.setReturnCode(ReturnCodeEnum.CLCG.getFhzDm());
            run.setReturnMessage(ReturnCodeEnum.CLCG.getFhzMc(ReturnCodeEnum.CLCG.getIndex()));
            InterfaceCode interfaceCode = new InterfaceCode();
            interfaceCode.setGlobalInfo(globalInfo);
            interfaceCode.setReturnStateInfo(run);
            interfaceCode.setData(Base64.encode(result));
            return JSON.toJSONString(interfaceCode);

        } catch (Exception e) {
            e.printStackTrace();
            run.setReturnCode("2011");
            run.setReturnMessage("其他异常");
            String globalJson = null;
            String runJson = null;
            try {
                runJson = JSON.toJSONString(run);
                globalJson = JSON.toJSONString(globalInfo);
            } catch (Exception ignored) {
            }
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json; charset=utf-8");
            return "{\"globalInfo\":" + globalJson + ",\"returnStateInfo\":" + runJson + "}";
        }
    }

    public InvoiceDetailInfo getInvoiceDetailInfo(InvoiceDetailInfo detail) {
        InvoiceDetailInfo detailInfo = new InvoiceDetailInfo();
        detailInfo.setDetailNo(detail.getDetailNo() + "");
        detailInfo.setGoodsName(detail.getGoodsName());
        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 {
            detailInfo.setTaxRate(detail.getTaxRate());
        }
        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 List<InvoiceDetailInfo> getDetailInfo(String uuid) {
        return super.baseMapper.selectDetailInfo(uuid);
    }

    public ESCVehicleSaleInvoiceInfos getEscVehicleInfo(VehicleSaleInvoices vehicleSaleInvoice, TdxRecordInvoice veinfo) {
        DecimalFormat df = new DecimalFormat("#0.00");
        ESCVehicleSaleInvoiceInfos info = new ESCVehicleSaleInvoiceInfos();
        info.setInvoiceType(veinfo.getInvoiceType());
        info.setInvoiceCode(veinfo.getInvoiceCode());
        info.setInvoiceNo(veinfo.getInvoiceNo());
        info.setInvoiceDate(new SimpleDateFormat("yyyyMMdd").format(veinfo.getInvoiceDate()));
        info.setBuyerIdNum(vehicleSaleInvoice.getBuyerIdNum());
        info.setBuyerName(vehicleSaleInvoice.getBuyerUnit());
        info.setBuyerAddress(vehicleSaleInvoice.getBuyerUnitAddress());
        info.setBuyerPhone(vehicleSaleInvoice.getBuyerPhone());
        info.setSellerIdNum(vehicleSaleInvoice.getSellerUnitCode());
        info.setSellerName(vehicleSaleInvoice.getSellerUnit());
        info.setSellerAddress(vehicleSaleInvoice.getSellerUnitAddress());
        info.setSellerPhone(vehicleSaleInvoice.getSellerPhone());
        info.setPlateNo(vehicleSaleInvoice.getPlateNo());
        info.setCertificateNo(vehicleSaleInvoice.getCertificate());
        info.setVehicleType(vehicleSaleInvoice.getVehicleType());
        info.setVehicleNo(vehicleSaleInvoice.getVehicleNo());
        info.setFactoryModel(vehicleSaleInvoice.getFactoryModel());
        info.setVehicleAdminOffice(vehicleSaleInvoice.getVehicleAdminOffice());
        info.setTotalAmount(df.format(veinfo.getTotalAmount()));
        info.setAuctionUnit(vehicleSaleInvoice.getAuctionUnit());
        info.setAuctionAddress(vehicleSaleInvoice.getAuctionAddress());
        info.setAuctionBank(vehicleSaleInvoice.getAuctionBank());
        info.setAuctionPhone(vehicleSaleInvoice.getAuctionPhone());
        info.setAuctionTaxno(vehicleSaleInvoice.getAuctionTaxNo());
        info.setCarMarket(vehicleSaleInvoice.getCarMarket());
        info.setCarMarketAddress(vehicleSaleInvoice.getCarMarketAddress());
        info.setCarMarketBank(vehicleSaleInvoice.getCarMarketBank());
        info.setCarMarketPhone(vehicleSaleInvoice.getCarMarketPhone());
        info.setCarMarketTaxno(vehicleSaleInvoice.getCarMarketTaxNo());
        info.setRemark(veinfo.getRemark());
        info.setDkTaxno(veinfo.getDkTaxno());
        info.setDkTaxname(veinfo.getDkTaxname());
        info.setInvoiceStatus(veinfo.getInvoiceStatus());
        info.setCheckStatus(veinfo.getSfygx());
        info.setLegalizeState(veinfo.getRzhYesorno());
        if (veinfo.getRzhDate() == null) {
            info.setLegalizeDate("");
        } else {
            info.setLegalizeDate(new SimpleDateFormat("yyyyMMdd").format(veinfo.getRzhDate()));
        }
        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 (veinfo.getRzlx() == null) {
            info.setRzlx("");
        } else {
            info.setRzlx(veinfo.getRzlx());
        }
        if (StringUtils.isNotBlank(veinfo.getGlzt())) {
            info.setManagementStatus(veinfo.getGlzt());
        } else {
            info.setManagementStatus("");
        }
        if (StringUtils.isNotBlank(veinfo.getXxly())) {
            info.setInformationSources(veinfo.getXxly());
        } else {
            info.setInformationSources("");
        }
        if (StringUtils.isNotBlank(veinfo.getYqkgxbz())) {
            info.setOverdueCheckMark(veinfo.getYqkgxbz());
        } else {
            info.setOverdueCheckMark("");
        }
        if (StringUtils.isNotBlank(veinfo.getYclx())) {
            info.setExceptionType(veinfo.getYclx());
        } else {
            info.setExceptionType("");
        }
        if (StringUtils.isNotBlank(veinfo.getQsStatus())) {
            info.setQsStatus(veinfo.getQsStatus());
        } else {
            info.setQsStatus("");
        }
        if (StringUtils.isNotBlank(veinfo.getQsName())) {
            info.setQsUser(veinfo.getQsName());
        } else {
            info.setQsUser("");
        }
        if (veinfo.getQsDate() != null) {
            info.setQsDate(new SimpleDateFormat("yyyyMMddHHmmss").format(veinfo.getQsDate()));
        } else {
            info.setQsDate("");
        }
        return info;
    }
    public VehicleSaleInvoiceInfos getVehicleInfo(VehicleSaleInvoices vehicleSaleInvoice, TdxRecordInvoice veinfo) {
        DecimalFormat df = new DecimalFormat("#0.00");
        VehicleSaleInvoiceInfos info = new VehicleSaleInvoiceInfos();
        if(StringUtils.isNotBlank(veinfo.getInvoiceCode())){
            info.setInvoiceCode(veinfo.getInvoiceCode());
        }else {
            info.setInvoiceCode("");
        }
        info.setInvoiceNo(veinfo.getInvoiceNo());
        info.setCurrentTaxPeriod(veinfo.getDqskssq());
        info.setLegalizeEndDate(veinfo.getGxjzr());
        info.setLegalizeInvoiceDateBegin(veinfo.getGxfwq());
        info.setLegalizeInvoiceDateEnd(veinfo.getGxfwz());
        info.setInvoiceType(veinfo.getInvoiceType());
        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());
        }
        info.setTotalAmount(df.format(veinfo.getTotalAmount()));
        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.setBuyerBank("");
        } else {
            info.setBuyerBank(vehicleSaleInvoice.getBuyerBank());
        }
        if (StringUtils.isBlank(veinfo.getXfBankAndNo())) {
            info.setBuyerAcount("");
        } else {
            info.setBuyerAcount(veinfo.getXfBankAndNo());
        }
        if (StringUtils.isBlank(veinfo.getXfAddressAndPhone())) {
            info.setBuyerAddressPhone("");
        } else {
            info.setBuyerAddressPhone(veinfo.getXfAddressAndPhone());
        }
        if(StringUtils.isNotBlank(vehicleSaleInvoice.getTaxRate())){
            info.setTaxRate(vehicleSaleInvoice.getTaxRate().replace("%",""));
        }else {
            info.setTaxRate("");
        }
//        try {
//            info.setTaxRate(Double.valueOf(vehicleSaleInvoice.getTaxRate()).intValue() + "");
//        } catch (Exception e) {
//            info.setTaxRate("0");
//        }
        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.getRzhDate() == null) {
            info.setLegalizeDate("");
        } else {
            info.setLegalizeDate(new SimpleDateFormat("yyyyMMdd").format(veinfo.getRzhDate()));
        }
        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 (veinfo.getRzlx() == null) {
            info.setRzlx("");
        } else {
            info.setRzlx(veinfo.getRzlx());
        }
        if (StringUtils.isNotBlank(veinfo.getGlzt())) {
            info.setManagementStatus(veinfo.getGlzt());
        } else {
            info.setManagementStatus("");
        }
        if (StringUtils.isNotBlank(veinfo.getXxly())) {
            info.setInformationSources(veinfo.getXxly());
        } else {
            info.setInformationSources("");
        }
        if ("1".equals(veinfo.getRzlx()) || "4".equals(veinfo.getRzlx())) {
            info.setTaxCredit(df.format(veinfo.getDkTaxAmount()));
        } else {
            info.setTaxCredit("");
        }
        if (StringUtils.isNotBlank(veinfo.getYqkgxbz())) {
            info.setOverdueCheckMark(veinfo.getYqkgxbz());
        } else {
            info.setOverdueCheckMark("");
        }
        if (StringUtils.isNotBlank(veinfo.getYclx())) {
            info.setExceptionType(veinfo.getYclx());
        } else {
            info.setExceptionType("");
        }
        if (StringUtils.isNotBlank(veinfo.getQsStatus())) {
            info.setQsStatus(veinfo.getQsStatus());
        } else {
            info.setQsStatus("");
        }
        if (StringUtils.isNotBlank(veinfo.getQsName())) {
            info.setQsUser(veinfo.getQsName());
        } else {
            info.setQsUser("");
        }
        if (veinfo.getQsDate() != null) {
            info.setQsDate(new SimpleDateFormat("yyyyMMddHHmmss").format(veinfo.getQsDate()));
        } else {
            info.setQsDate("");
        }
        return info;
    }

    public List<VehicleSaleInvoices> selectVehicle(String uuid) {
        return super.baseMapper.selectVehicle(uuid);
    }

    public Integer selectByAllCount(CollectData data) {
        Map<String, Object> map = new HashMap<>(16);
        map.put("buyerTaxNo", data.getBuyerTaxNo());
        map.put("invoiceType", data.getInvoiceType());
        map.put("createDateBegin", data.getCreateDateBegin());
        map.put("createDateEnd", data.getCreateDateEnd());
        map.put("startRow", data.getStartRow());
        map.put("requestRow", data.getRequestRow());
        map.put("qsStatus", data.getQsStatus());
        map.put("qsDateBegin", data.getQsDateBegin());
        map.put("qsDateEnd", data.getQsDateEnd());
        map.put("rzhStatus", data.getRzhStatus());
        map.put("taxPeriod", data.getTaxPeriod());
        return super.baseMapper.selectAllCount(map);
    }

    public Integer selectAuthResultCount(CollectData data) {
        Map<String, Object> map = new HashMap<>(16);
        map.put("buyerTaxNo", data.getBuyerTaxNo());
        map.put("startRow", data.getStartRow());
        map.put("requestRow", data.getRequestRow());
        map.put("rzhStatus", data.getRzhStatus());
        map.put("taxPeriod", data.getTaxPeriod());
        map.put("rzhUser", data.getRzhUser());
        return super.baseMapper.selectAuthResultCount(map);
    }

    public List<TdxRecordInvoice> selectByCollect(CollectData data, Integer start, Integer num) {
        Map<String, Object> map = new HashMap<>(16);
        map.put("buyerTaxNo", data.getBuyerTaxNo());
        map.put("invoiceType", data.getInvoiceType());
        map.put("createDateBegin", data.getCreateDateBegin());
        map.put("createDateEnd", data.getCreateDateEnd());
        map.put("startRow", data.getStartRow());
        map.put("requestRow", data.getRequestRow());
        map.put("qsStatus", data.getQsStatus());
        map.put("qsDateBegin", data.getQsDateBegin());
        map.put("qsDateEnd", data.getQsDateEnd());
        map.put("rzhStatus", data.getRzhStatus());
        map.put("taxPeriod", data.getTaxPeriod());
        map.put("start", start - 1);
        map.put("num", num);
        return super.baseMapper.selectByCollect(map);
    }

    public List<AuthStatus> selectAllAuthResult(CollectData data, Integer start, Integer num) {
        Map<String, Object> map = new HashMap<>(16);
        map.put("buyerTaxNo", data.getBuyerTaxNo());
        map.put("startRow", data.getStartRow());
        map.put("requestRow", data.getRequestRow());
        map.put("rzhStatus", data.getRzhStatus());
        map.put("taxPeriod", data.getTaxPeriod());
        map.put("rzhUser", data.getRzhUser());
        map.put("start", start - 1);
        map.put("num", num);
        return super.baseMapper.selectAllAuthResult(map);
    }

    public Integer selectByStateAllCount(String statusChangeDateBegin, String statusChangeDateEnd, String buyerTaxNo) {
        Map<String, Object> map = new HashMap<>(16);
        map.put("buyerTaxNo", buyerTaxNo);
        map.put("startDate", statusChangeDateBegin);
        map.put("endDate", statusChangeDateEnd);
        return super.baseMapper.selectByStateAllCount(map);
    }

    public List<State> selectByState(String statusChangeDateBegin, String statusChangeDateEnd, String buyerTaxNo,
        Integer start, Integer num) {
        Map<String, Object> map = new HashMap<>(16);
        map.put("buyerTaxNo", buyerTaxNo);
        map.put("startDate", statusChangeDateBegin);
        map.put("endDate", statusChangeDateEnd);
        map.put("start", start - 1);
        map.put("num", num);
        return super.baseMapper.selectByState(map);
    }

    public State getStateInfo(State state) {
        DecimalFormat df = new DecimalFormat("#0.00");
        State info = new State();
        if(StringUtils.isNotBlank(state.getInvoiceCode())){
            info.setInvoiceCode(state.getInvoiceCode());
        }else {
            info.setInvoiceCode("");
        }
        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.setManagementStatus("");
        } else {
            info.setManagementStatus(state.getManagementStatus());
        }
        if (state.getInformationSources() == null) {
            info.setInformationSources("");
        } else {
            info.setInformationSources(state.getInformationSources());
        }
        if (StringUtils.isBlank(state.getTaxCredit())) {
            info.setTaxCredit("");
        } else {
            info.setTaxCredit(df.format(new BigDecimal(state.getTaxCredit())));
        }
        if (state.getOverdueCheckMark() == null) {
            info.setOverdueCheckMark("");
        } else {
            info.setOverdueCheckMark(state.getOverdueCheckMark());
        }
        if (state.getExceptionType() == null) {
            info.setExceptionType("");
        } else {
            info.setExceptionType(state.getExceptionType());
        }
        return info;
    }

    public ReturnStateInfo getCheck(CollectData data) {
        ReturnStateInfo run = new ReturnStateInfo();
        if (CheckUtils.isNullOrEmpty(data.getBatchNo()) || (!CheckUtils.stringLength(data.getBatchNo(), 32))) {
            run.setReturnCode(ReturnCodeEnum.PCHBNWK.getFhzDm());
            run.setReturnMessage(ReturnCodeEnum.PCHBNWK.getFhzMc(ReturnCodeEnum.PCHBNWK.getIndex()));
        }
        if (CheckUtils.isNullOrEmpty(data.getBuyerTaxNo())) {
            run.setReturnCode(ReturnCodeEnum.SHBNWK.getFhzDm());
            run.setReturnMessage(ReturnCodeEnum.SHBNWK.getFhzMc(ReturnCodeEnum.SHBNWK.getIndex()));
        }

        if (CheckUtils.isNullOrEmpty(data.getCreateDateBegin())
            || (!CheckUtils.stringLength(data.getCreateDateBegin(), 14))) {
            run.setReturnCode(ReturnCodeEnum.QSRQBNWK.getFhzDm());
            run.setReturnMessage(ReturnCodeEnum.QSRQBNWK.getFhzMc(ReturnCodeEnum.QSRQBNWK.getIndex()));
        }
        if (CheckUtils.isNullOrEmpty(data.getCreateDateEnd())
            || (!CheckUtils.stringLength(data.getCreateDateEnd(), 14))) {
            run.setReturnCode(ReturnCodeEnum.JSRQBNWK.getFhzDm());
            run.setReturnMessage(ReturnCodeEnum.JSRQBNWK.getFhzMc(ReturnCodeEnum.JSRQBNWK.getIndex()));
        }
        if (CheckUtils.isNullOrEmpty(data.getStatus()) || (!CheckUtils.stringLength(data.getStatus(), 1))) {
            run.setReturnCode(ReturnCodeEnum.ZTBZBNWK.getFhzDm());
            run.setReturnMessage(ReturnCodeEnum.ZTBZBNWK.getFhzMc(ReturnCodeEnum.ZTBZBNWK.getIndex()));
        }
        if (!CheckUtils.checkNum(data.getStartRow())) {
            run.setReturnCode(ReturnCodeEnum.KSHSCW.getFhzDm());
            run.setReturnMessage(ReturnCodeEnum.KSHSCW.getFhzMc(ReturnCodeEnum.KSHSCW.getIndex()));
        }
        if (CheckUtils.isNullOrEmpty(data.getInvoiceType())) {
            run.setReturnCode(ReturnCodeEnum.FPLXWK.getFhzDm());
            run.setReturnMessage(ReturnCodeEnum.FPLXWK.getFhzMc(ReturnCodeEnum.FPLXWK.getIndex()));
        }
        return run;
    }

    public ReturnStateInfo getCheckState(StateData data) {
        ReturnStateInfo run = new ReturnStateInfo();

        if (CheckUtils.isNullOrEmpty(data.getBuyerTaxNo()) || !(CheckUtils.stringLength(data.getBuyerTaxNo(), 15)
            || CheckUtils.stringLength(data.getBuyerTaxNo(), 18))) {
            run.setReturnCode(ReturnCodeEnum.SHBNWK.getFhzDm());
            run.setReturnMessage(ReturnCodeEnum.SHBNWK.getFhzMc(ReturnCodeEnum.SHBNWK.getIndex()));
        }
        if (CheckUtils.isNullOrEmpty(data.getBatchNo()) || (!CheckUtils.stringLength(data.getBatchNo(), 32))) {
            run.setReturnCode(ReturnCodeEnum.PCHBNWK.getFhzDm());
            run.setReturnMessage(ReturnCodeEnum.PCHBNWK.getFhzMc(ReturnCodeEnum.PCHBNWK.getIndex()));
        }
        if (CheckUtils.isNullOrEmpty(data.getStatusChangeDateBegin())
            || (!CheckUtils.stringLength(data.getStatusChangeDateBegin(), 14))) {
            run.setReturnCode(ReturnCodeEnum.QSRQBNWK.getFhzDm());
            run.setReturnMessage(ReturnCodeEnum.QSRQBNWK.getFhzMc(ReturnCodeEnum.QSRQBNWK.getIndex()));
        }
        if (CheckUtils.isNullOrEmpty(data.getStatusChangeDateEnd())
            || (!CheckUtils.stringLength(data.getStatusChangeDateEnd(), 14))) {
            run.setReturnCode(ReturnCodeEnum.JSRQBNWK.getFhzDm());
            run.setReturnMessage(ReturnCodeEnum.JSRQBNWK.getFhzMc(ReturnCodeEnum.JSRQBNWK.getIndex()));
        }
        if (CheckUtils.isNullOrEmpty(data.getStatus()) || (!CheckUtils.stringLength(data.getStatus(), 1))) {
            run.setReturnCode(ReturnCodeEnum.ZTBZBNWK.getFhzDm());
            run.setReturnMessage(ReturnCodeEnum.ZTBZBNWK.getFhzMc(ReturnCodeEnum.ZTBZBNWK.getIndex()));
        }
        if (!CheckUtils.checkNum(data.getStartRow())) {
            run.setReturnCode(ReturnCodeEnum.KSHSCW.getFhzDm());
            run.setReturnMessage(ReturnCodeEnum.KSHSCW.getFhzMc(ReturnCodeEnum.KSHSCW.getIndex()));
        }
        return run;
    }

    public ReturnStateInfo getCheckSingle(SingleInvoiceReq data) {
        ReturnStateInfo run = new ReturnStateInfo();
        boolean r =
            CheckUtils.isNullOrEmpty(data.getBuyerTaxNo()) || !(CheckUtils.stringLength(data.getBuyerTaxNo(), 15)
                || CheckUtils.stringLength(data.getBuyerTaxNo(), 18));
        if (r) {
            run.setReturnCode(ReturnCodeEnum.SHBNWK.getFhzDm());
            run.setReturnMessage(ReturnCodeEnum.SHBNWK.getFhzMc(ReturnCodeEnum.SHBNWK.getIndex()));
        }
//        boolean r1 =
//                CheckUtils.isNullOrEmpty(data.getInvoiceCode()) || !(CheckUtils.stringLength(data.getInvoiceCode(), 10)
//                        || CheckUtils.stringLength(data.getInvoiceCode(), 12));
//        if (r1) {
//            run.setReturnCode(ReturnCodeEnum.DMHMBF.getFhzDm());
//            run.setReturnMessage(ReturnCodeEnum.DMHMBF.getFhzMc(ReturnCodeEnum.DMHMBF.getIndex()));
//        }
        boolean r2 = CheckUtils.isNullOrEmpty(data.getInvoiceNo())
            || !(CheckUtils.stringLength(data.getInvoiceNo(), 8) || CheckUtils.stringLength(data.getInvoiceNo(), 10)
        ||CheckUtils.stringLength(data.getInvoiceNo(), 20));
        if (r2) {
            run.setReturnCode(ReturnCodeEnum.DMHMBF.getFhzDm());
            run.setReturnMessage(ReturnCodeEnum.DMHMBF.getFhzMc(ReturnCodeEnum.DMHMBF.getIndex()));
        }else {
            if(!CheckUtils.stringLength(data.getInvoiceNo(), 20)){
                boolean r1 =
                        CheckUtils.isNullOrEmpty(data.getInvoiceCode()) || !(CheckUtils.stringLength(data.getInvoiceCode(), 10)
                                || CheckUtils.stringLength(data.getInvoiceCode(), 12));
                if (r1) {
                    run.setReturnCode(ReturnCodeEnum.DMHMBF.getFhzDm());
                    run.setReturnMessage(ReturnCodeEnum.DMHMBF.getFhzMc(ReturnCodeEnum.DMHMBF.getIndex()));
                }
            }
        }
        return run;
    }

    public ReturnStateInfo getCheckRz(CollectData data) {
        ReturnStateInfo run = new ReturnStateInfo();
        if (CheckUtils.isNullOrEmpty(data.getBatchNo()) || (!CheckUtils.stringLength(data.getBatchNo(), 32))) {
            run.setReturnCode(ReturnCodeEnum.PCHBNWK.getFhzDm());
            run.setReturnMessage(ReturnCodeEnum.PCHBNWK.getFhzMc(ReturnCodeEnum.PCHBNWK.getIndex()));
        }
        if (CheckUtils.isNullOrEmpty(data.getBuyerTaxNo())) {
            run.setReturnCode(ReturnCodeEnum.SHBNWK.getFhzDm());
            run.setReturnMessage(ReturnCodeEnum.SHBNWK.getFhzMc(ReturnCodeEnum.SHBNWK.getIndex()));
        }
        if (CheckUtils.isNullOrEmpty(data.getStatus()) || (!CheckUtils.stringLength(data.getStatus(), 1))) {
            run.setReturnCode(ReturnCodeEnum.ZTBZBNWK.getFhzDm());
            run.setReturnMessage(ReturnCodeEnum.ZTBZBNWK.getFhzMc(ReturnCodeEnum.ZTBZBNWK.getIndex()));
        }
        if (!CheckUtils.checkNum(data.getStartRow())) {
            run.setReturnCode(ReturnCodeEnum.KSHSCW.getFhzDm());
            run.setReturnMessage(ReturnCodeEnum.KSHSCW.getFhzMc(ReturnCodeEnum.KSHSCW.getIndex()));
        }
        boolean r = !("1".equals(data.getRzhStatus()) || "2".equals(data.getRzhStatus()));
        if (CheckUtils.isNullOrEmpty(data.getRzhStatus()) || r) {
            run.setReturnCode(ReturnCodeEnum.RZZTBNWK.getFhzDm());
            run.setReturnMessage(ReturnCodeEnum.RZZTBNWK.getFhzMc(ReturnCodeEnum.RZZTBNWK.getIndex()));
        }
        return run;
    }
}
