package com.dxhy.jxpt.baseService.sign.service.singletable.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.dxhy.common.constant.DbConstant;
import com.dxhy.common.datasource.config.DynamicContextHolder;
import com.dxhy.common.enums.*;
import com.dxhy.common.service.impl.MpBaseServiceImpl;
import com.dxhy.common.util.MathUtil;
import com.dxhy.common.util.NumberToCN;
import com.dxhy.common.util.StringHelper;
import com.dxhy.common.utils.Aops;
import com.dxhy.common.utils.CommonUtil;
import com.dxhy.common.utils.DateUtils;
import com.dxhy.jxpt.baseService.sign.dao.SignRecordInvoiceDao;
import com.dxhy.api.model.invoice.TDxRecordInvoice;
import com.dxhy.api.model.sign.TDxRecordInvoiceDetail;
import com.dxhy.api.model.sign.TDxRecordInvoiceStatistics;
import com.dxhy.api.model.sign.TDxVehicleSaleInvoice;
import com.dxhy.api.model.sign.CheckRecordInvoiceDetailVO;
import com.dxhy.api.model.sign.CheckVehicleSaleVO;
import com.dxhy.api.model.sign.InvoiceSubjectVO;
import com.dxhy.jxpt.baseService.sign.service.fpqs.SignFpqsService;
import com.dxhy.jxpt.baseService.sign.service.singletable.SignInvoiceDetailService;
import com.dxhy.jxpt.baseService.sign.service.singletable.SignInvoiceStatisticsService;
import com.dxhy.jxpt.baseService.sign.service.singletable.SignJdcService;
import com.dxhy.jxpt.baseService.sign.service.singletable.SignSaveInvoiceInfoService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 *
 * 保存发票查验结果业务处理实现类
 *
 * @author ld
 */
@SuppressWarnings("AlibabaUndefineMagicConstant")
@Service("signSaveInvoiceInfoService")
@Slf4j

public class SignSaveInvoiceInfoServiceImpl extends MpBaseServiceImpl<SignRecordInvoiceDao, TDxRecordInvoice>
    implements SignSaveInvoiceInfoService {

    @Resource
    private SignJdcService signJdcService;

    @Resource
    private SignInvoiceDetailService signInvoiceDetailService;

    @Resource
    private SignInvoiceStatisticsService signInvoiceStatisticsService;
    @Resource
    private SignFpqsService signFpqsService;

    @Override
    public void saveQueryInvoiceResult(JSONObject queryInvoiceResult, String userName, String qsType, String dbName) {

        // 获取底账表信息
        TDxRecordInvoice recordInvoice = getRecordInvoice(queryInvoiceResult, userName, qsType);
        // 获取机动车表信息
        TDxVehicleSaleInvoice vehicleSaleInvoice = getVehicleSaleInvoice(queryInvoiceResult);
        // 底账明细表
        List<TDxRecordInvoiceDetail> recordInvoiceDetail = getRecordInvoiceDetail(queryInvoiceResult);
        // 税率统计表
        List<TDxRecordInvoiceStatistics> invoiceStatistics = getInvoiceStatistics(queryInvoiceResult);

        //获取二手车明细信息
        TDxVehicleSaleInvoice vehicleInvoice = vehicleInvoice(queryInvoiceResult);

        // 保存前先查询底账数据是否已存在，已存在则不用重复保存
        TDxRecordInvoice recordInvoiceExit = queryInvoice(recordInvoice.getUuid(), dbName);
        if (recordInvoiceExit == null) {
            // 机动车票
            if (vehicleSaleInvoice != null) {
                DynamicContextHolder.push(dbName + DbConstant.BUSINESS_WRITE);
                boolean saveVehicleSaleInvoice =
                    this.saveVehicleSaleInvoice(recordInvoice, vehicleSaleInvoice, invoiceStatistics);
                if (saveVehicleSaleInvoice) {
                    boolean deleteVehicleSaleInvoice =
                        signJdcService.deleteVehicleSaleInvoice(recordInvoice.getUuid(), dbName);
                    if (deleteVehicleSaleInvoice) {
                        signJdcService.saveVehicleSaleInvoice(vehicleSaleInvoice, dbName);
                    }
                    // 保存税率统计表
                    if (invoiceStatistics.size() > 0) {
                        boolean deleteStatistics = signInvoiceStatisticsService
                            .deleteStatistics(recordInvoice.getInvoiceCode(), recordInvoice.getInvoiceNo(), dbName);
                        if (deleteStatistics) {
                            signInvoiceStatisticsService.saveInvoiceStatistics(invoiceStatistics, dbName);
                        }
                    }
                }
            }
            // 二手车
            if (vehicleInvoice != null) {
                DynamicContextHolder.push(dbName + DbConstant.BUSINESS_WRITE);
                boolean saveVehicleSaleInvoice =
                        this.saveVehicleSaleInvoice(recordInvoice, vehicleInvoice, invoiceStatistics);
                if (saveVehicleSaleInvoice) {
                    if (vehicleInvoice != null) {
                        boolean deleteVehicleSaleInvoice =
                                signJdcService.deleteVehicleSaleInvoice(recordInvoice.getUuid(), dbName);
                        if (deleteVehicleSaleInvoice) {
                            signJdcService.saveVehicleSaleInvoice(vehicleInvoice, dbName);
                        }
                    }
                    // 保存税率统计表
                    if (invoiceStatistics.size() > 0) {
                        DynamicContextHolder.push(dbName + DbConstant.BUSINESS_WRITE);
                        signInvoiceStatisticsService.remove(new UpdateWrapper<TDxRecordInvoiceStatistics>()
                                .eq("invoice_code", recordInvoice.getInvoiceCode()).eq("invoice_no", recordInvoice.getInvoiceNo()));
                        signInvoiceStatisticsService.saveBatch(invoiceStatistics);
                    }
                }
            }
            // 其它票，保存底账明细表数据
            if (recordInvoiceDetail != null && recordInvoiceDetail.size() > 0) {
                DynamicContextHolder.push(dbName + DbConstant.BUSINESS_WRITE);
                // 保存底账表数据
                boolean insertRecordInvoice = Aops.getSelf(this).insertRecordInvoice(recordInvoice);
                if (insertRecordInvoice) {
                    // 保存底账明细表数据
                    try {
                        // 删除已存在的数据，防止数据重复
                        if (recordInvoiceDetail.size() > 0) {
                            boolean deleteDetail =
                                signInvoiceDetailService.deleteDetail(recordInvoice.getUuid(), dbName);
                            if (deleteDetail) {
                                signInvoiceDetailService.saveInvoiceDetail(recordInvoiceDetail, dbName);
                            }
                        }

                    } catch (Exception e) {
                       log.info("业务处理异常：{}", e);
                        DynamicContextHolder.push(dbName + DbConstant.BUSINESS_WRITE);
                        // 保存明细表异常，设置底账表的明细标志为0,detail_yesorno=0
                        TDxRecordInvoice invoice = new TDxRecordInvoice();
                        invoice.setDetailYesorno("0");
                        this.updateInvoice(invoice);
                    }

                    // 保存税率统计表
                    if (invoiceStatistics.size() > 0) {
                        DynamicContextHolder.push(dbName + DbConstant.BUSINESS_WRITE);
                        if(StringUtils.isNotBlank(recordInvoice.getInvoiceCode())){
                            signInvoiceStatisticsService.remove(new UpdateWrapper<TDxRecordInvoiceStatistics>()
                                    .eq("invoice_code", recordInvoice.getInvoiceCode()).eq("invoice_no", recordInvoice.getInvoiceNo()));
                        }else {
                            signInvoiceStatisticsService.remove(new UpdateWrapper<TDxRecordInvoiceStatistics>()
                                    .eq("invoice_no", recordInvoice.getInvoiceNo()));
                        }

                        signInvoiceStatisticsService.saveBatch(invoiceStatistics);
                    }
                }
            }
        } else {
            DynamicContextHolder.push(dbName + DbConstant.BUSINESS_WRITE);
            TDxRecordInvoice recordInvoiceUpdate = new TDxRecordInvoice();
            recordInvoiceUpdate.setQsDate(DateUtils.getSqlDateLong());
            recordInvoiceUpdate.setQsName(userName);
            recordInvoiceUpdate.setQsStatus(FpqsjgEnum.YQS.getQsjgDm());
            recordInvoiceUpdate.setQsType(qsType);
            recordInvoiceUpdate.setUuid(recordInvoice.getUuid());
            if (recordInvoice.getDeptId() != null) {
                recordInvoiceUpdate.setDeptId(recordInvoice.getDeptId());
                recordInvoiceUpdate.setDeptName(recordInvoice.getDeptName());
            }
            this.updateInvoice(recordInvoiceUpdate);
        }
    }

    /**
     * 查看抵账表数据是否存在
     *
     * @param uuid
     *            uuid
     * @param dbName
     *            数据源
     * @return 返回结果
     */
    public TDxRecordInvoice queryInvoice(String uuid, String dbName) {
        DynamicContextHolder.push(dbName + DbConstant.BUSINESS_READ);
        return baseMapper.selectOne(new QueryWrapper<TDxRecordInvoice>().eq("uuid", uuid));
    }

    /**
     * 修改抵账表数据
     *
     * @param recordInvoiceUpdate
     *            请求参数
     */
    @Transactional(rollbackFor = Exception.class)
    public void updateInvoice(TDxRecordInvoice recordInvoiceUpdate) {
        try {
            baseMapper.update(recordInvoiceUpdate,
                new QueryWrapper<TDxRecordInvoice>().eq("uuid", recordInvoiceUpdate.getUuid()));
        } catch (Exception e) {
           log.info("业务处理异常：{}", e);
        }
    }

    /**
     * 保存抵账表数据
     *
     * @param recordInvoice
     *            请求参数
     * @return 返回结果
     */
    @Transactional(rollbackFor = Exception.class)
    public boolean insertRecordInvoice(TDxRecordInvoice recordInvoice) {
        try {
            baseMapper.insert(recordInvoice);
            return true;
        } catch (Exception e) {
           log.info("业务处理异常：{}", e);
            return false;
        }
    }

    /**
     * 根据查验结果获取税率统计表对象
     *
     * @param queryInvoiceResult
     *            请求参数
     *
     * @return 返回结果
     *
     */
    private List<TDxRecordInvoiceStatistics> getInvoiceStatistics(JSONObject queryInvoiceResult) {
        List<TDxRecordInvoiceStatistics> invoiceStatisticsList = new ArrayList<>();
        String invoiceType = queryInvoiceResult.getString("invoiceType");
        if (FplxEnum.JDC.getFplxDm().equals(invoiceType)) {
            TDxRecordInvoiceStatistics invoiceStatistics = new TDxRecordInvoiceStatistics();
            invoiceStatistics.setCreateDate(DateUtils.getSqlDateLong());
            invoiceStatistics.setInvoiceCode(queryInvoiceResult.getString("invoiceCode"));
            invoiceStatistics.setInvoiceNo(queryInvoiceResult.getString("invoiceNo"));
            invoiceStatistics.setDetailAmount(queryInvoiceResult.getBigDecimal("invoiceAmount"));
            invoiceStatistics.setTaxRate(queryInvoiceResult.getString("taxRate"));
            invoiceStatistics.setTaxAmount(queryInvoiceResult.getBigDecimal("taxAmount"));
            invoiceStatistics.setTotalAmount(queryInvoiceResult.getBigDecimal("totalAmount"));
            invoiceStatisticsList.add(invoiceStatistics);
        } else if(FplxEnum.ESC.getFplxDm().equals(invoiceType)){
            TDxRecordInvoiceStatistics invoiceStatistics = new TDxRecordInvoiceStatistics();
            invoiceStatistics.setCreateDate(DateUtils.getSqlDateLong());
            invoiceStatistics.setInvoiceCode(queryInvoiceResult.getString("invoiceCode"));
            invoiceStatistics.setInvoiceNo(queryInvoiceResult.getString("invoiceNo"));
            invoiceStatistics.setDetailAmount(queryInvoiceResult.getBigDecimal("carPrice"));
            invoiceStatistics.setTotalAmount(queryInvoiceResult.getBigDecimal("carPrice"));
            invoiceStatisticsList.add(invoiceStatistics);
        } else{
            if (queryInvoiceResult.containsKey("detailList")) {
                invoiceStatisticsList = signFpqsService.buildRecordInvoiceStatisticsList(queryInvoiceResult);
            }
        }

        return invoiceStatisticsList;
    }

    /**
     * 保存机动车
     *
     * @param recordInvoice
     *            请求参数
     * @param vehicleSaleInvoice
     *            请求参数
     * @param invoiceStatistics
     *            请求参数
     *
     */
    @Transactional(rollbackFor = Exception.class)
    public boolean saveVehicleSaleInvoice(TDxRecordInvoice recordInvoice, TDxVehicleSaleInvoice vehicleSaleInvoice,
        List<TDxRecordInvoiceStatistics> invoiceStatistics) {
        // 保存底账表数据
        try {
            baseMapper.insert(recordInvoice);
            return true;
        } catch (Exception e) {
           log.info("业务处理异常：{}", e);
            return false;
        }
    }

    @Override
    public List<TDxRecordInvoiceDetail> getRecordInvoiceDetail(JSONObject queryInvoiceResult) {
        if (queryInvoiceResult.containsKey("detailList")) {
            JSONArray dataArray = queryInvoiceResult.getJSONArray("detailList");
            if (dataArray != null && dataArray.size() > 0) {
                String invoiceType = queryInvoiceResult.getString("invoiceType");
                String invoiceCode = queryInvoiceResult.getString("invoiceCode");
                String invoiceNo = queryInvoiceResult.getString("invoiceNo");
                String uuid = invoiceCode + invoiceNo;
                List<TDxRecordInvoiceDetail> invoiceDetailList = new ArrayList<>(dataArray.size());
                for (int i = 0; i < dataArray.size(); i++) {
                    JSONObject invoiceDetailQuery = dataArray.getJSONObject(i);
                    TDxRecordInvoiceDetail invoiceDetail = new TDxRecordInvoiceDetail();
                    invoiceDetail.setUuid(uuid);
                    if(FplxEnum.QDZZP.getFplxDm().equals(invoiceType) || FplxEnum.QDPP.getFplxDm().equals(invoiceType)){
                        invoiceDetail.setInvoiceNo(uuid);
                    }else {
                        invoiceDetail.setInvoiceCode(invoiceCode);
                        invoiceDetail.setInvoiceNo(invoiceNo);
                    }
                    invoiceDetail.setDetailNo(invoiceDetailQuery.getString("detailNo"));
                    invoiceDetail.setGoodsName(invoiceDetailQuery.getString("goodsName"));
                    invoiceDetail.setModel(invoiceDetailQuery.getString("specificationModel"));
                    invoiceDetail.setUnit(invoiceDetailQuery.getString("unit"));
                    invoiceDetail.setNum(invoiceDetailQuery.getString("num"));
                    invoiceDetail.setUnitPrice(invoiceDetailQuery.getString("unitPrice"));
                    invoiceDetail.setDetailAmount(invoiceDetailQuery.getString("detailAmount"));
                    invoiceDetail.setTaxRate(invoiceDetailQuery.getString("taxRate"));
                    invoiceDetail.setTaxAmount(invoiceDetailQuery.getString("taxAmount"));
                    if (FplxEnum.TXF.getFplxDm().equals(invoiceType)) {
                        // 通行费发票
                        invoiceDetail.setCph(invoiceDetailQuery.getString("cph"));
                        invoiceDetail.setLx(invoiceDetailQuery.getString("lx"));
                        invoiceDetail.setTxrqq(invoiceDetailQuery.getString("txrqq"));
                        invoiceDetail.setTxrqz(invoiceDetailQuery.getString("txrqz"));
                    }
                    invoiceDetailList.add(invoiceDetail);
                }
                return invoiceDetailList;
            } else {
                return null;
            }
        } else {
            return null;
        }
    }

    @Override
    public TDxVehicleSaleInvoice getVehicleSaleInvoice(JSONObject queryInvoiceResult) {
        String invoiceType = queryInvoiceResult.getString("invoiceType");
        if (FplxEnum.JDC.getFplxDm().equals(invoiceType)) {
            String invoiceCode = queryInvoiceResult.getString("invoiceCode");
            String invoiceNo = queryInvoiceResult.getString("invoiceNo");
            String uuid = invoiceCode + invoiceNo;

            TDxVehicleSaleInvoice vehicleSaleInvoice = new TDxVehicleSaleInvoice();
            vehicleSaleInvoice.setUuid(uuid);
            vehicleSaleInvoice.setBuyerIdNum(queryInvoiceResult.getString("buyerIDNum"));
            vehicleSaleInvoice.setVehicleType(queryInvoiceResult.getString("vehicleType"));
            vehicleSaleInvoice.setFactoryModel(queryInvoiceResult.getString("factoryModel"));
            vehicleSaleInvoice.setProductPlace(queryInvoiceResult.getString("productPlace"));
            vehicleSaleInvoice.setCertificate(queryInvoiceResult.getString("certificate"));
            vehicleSaleInvoice.setCertificateImport(queryInvoiceResult.getString("certificateImport"));
            vehicleSaleInvoice.setInspectionNum(queryInvoiceResult.getString("inspectionNum"));
            vehicleSaleInvoice.setEngineNo(queryInvoiceResult.getString("engineNo"));
            vehicleSaleInvoice.setVehicleNo(queryInvoiceResult.getString("vehicleNo"));
            vehicleSaleInvoice.setTaxBureauCode(queryInvoiceResult.getString("taxBureauCode"));
            vehicleSaleInvoice.setTaxBureauName(queryInvoiceResult.getString("taxBureauName"));
            vehicleSaleInvoice.setTaxRecords(queryInvoiceResult.getString("taxRecords"));
            vehicleSaleInvoice.setTonnage(queryInvoiceResult.getString("tonnage"));
            vehicleSaleInvoice.setLimitPeople(queryInvoiceResult.getString("limitPeople"));
            vehicleSaleInvoice.setTaxRate(queryInvoiceResult.getString("taxRate"));
            vehicleSaleInvoice.setCompany(queryInvoiceResult.getString("company"));
            return vehicleSaleInvoice;
        } else {
            return null;
        }
    }

    @Override
    public TDxRecordInvoice getRecordInvoice(JSONObject queryInvoiceResult, String userName, String qsType) {
        TDxRecordInvoice invoice = new TDxRecordInvoice();

        String invoiceType = queryInvoiceResult.getString("invoiceType");
        String invoiceCode = queryInvoiceResult.getString("invoiceCode");
        String invoiceNo = queryInvoiceResult.getString("invoiceNo");
        String uuid = invoiceCode + invoiceNo;

        invoice.setInvoiceType(invoiceType);
        if(FplxEnum.QDZZP.getFplxDm().equals(invoiceType) || FplxEnum.QDPP.getFplxDm().equals(invoiceType)){
            invoice.setInvoiceCode(uuid.substring(0,12));
            invoice.setInvoiceNo(uuid.substring(12,20));
            invoice.setEleInvoiceNo(uuid);
        }else {
            invoice.setInvoiceCode(invoiceCode);
            invoice.setInvoiceNo(invoiceNo);
        }
        invoice.setUuid(uuid);
        if ("Y".equals(queryInvoiceResult.getString("isCancelled"))) {
            invoice.setInvoiceStatus(FpztEnum.ZF.getFpztDm(FpztEnum.ZF.getIndex()));
        } else if ("N".equals(queryInvoiceResult.getString("isCancelled"))) {
            invoice.setInvoiceStatus(FpztEnum.ZC.getFpztDm(FpztEnum.ZC.getIndex()));
        } else {
            invoice.setInvoiceStatus(queryInvoiceResult.getString("isCancelled"));
        }
        invoice.setInvoiceAmount(queryInvoiceResult.getBigDecimal("invoiceAmount"));
        invoice.setTaxAmount(queryInvoiceResult.getBigDecimal("taxAmount"));
        invoice.setTotalAmount(queryInvoiceResult.getBigDecimal("totalAmount"));
        invoice.setInvoiceDate(queryInvoiceResult.getDate("invoiceDate"));
        invoice.setGfAddressAndPhone(queryInvoiceResult.getString("buyerAddressPhone"));
        invoice.setGfBankAndNo(queryInvoiceResult.getString("buyerAccount"));
        invoice.setGfName(queryInvoiceResult.getString("buyerName"));
        invoice.setGfTaxNo(queryInvoiceResult.getString("buyerTaxNo"));
        invoice.setXfAddressAndPhone(queryInvoiceResult.getString("salerAddressPhone"));
        invoice.setXfBankAndNo(queryInvoiceResult.getString("salerAccount"));
        invoice.setXfName(queryInvoiceResult.getString("salerName"));
        invoice.setXfTaxNo(queryInvoiceResult.getString("salerTaxNo"));
        if(FplxEnum.ESC.getFplxDm().equals(invoiceType)){
            invoice.setInvoiceAmount(queryInvoiceResult.getBigDecimal("carPrice"));
            invoice.setTotalAmount(queryInvoiceResult.getBigDecimal("carPrice"));
            invoice.setGfName(queryInvoiceResult.getString("buyerUnitOrIndividual"));
            invoice.setGfTaxNo(queryInvoiceResult.getString("buyerUnitCodeOrIdNo"));
            invoice.setGfAddressAndPhone(queryInvoiceResult.getString("buyerUnitOrIndividualAddress"));
            invoice.setXfName(queryInvoiceResult.getString("sellerUnitOrIndividual"));
            invoice.setXfTaxNo(queryInvoiceResult.getString("sellerUnitCodeOrIdNo"));
            invoice.setXfAddressAndPhone(queryInvoiceResult.getString("sellerUnitOrIndividualAddress"));
        }
        invoice.setMachinecode(queryInvoiceResult.getString("machineNo"));
        invoice.setRemark(queryInvoiceResult.getString("remark"));
        invoice.setCheckCode(queryInvoiceResult.getString("checkCode"));
        invoice.setTxfbz(queryInvoiceResult.getString("txfbz"));
        invoice.setSourceSystem("1");
        invoice.setCompany(queryInvoiceResult.getString("company"));
        if (FplxEnum.JDC.getFplxDm().equals(invoiceType)) {
            invoice.setDetailYesorno("0");
        } else {
            if (queryInvoiceResult.containsKey("detailList")) {
                JSONArray dataArray = queryInvoiceResult.getJSONArray("detailList");
                if (dataArray != null && dataArray.size() > 0) {
                    invoice.setDetailYesorno("1");

                } else {
                    invoice.setDetailYesorno("0");
                }
            } else {
                invoice.setDetailYesorno("0");
            }
        }
        invoice.setCreateDate(new Date());
        invoice.setLastUpdateDate(new Date());
        invoice.setQsDate(DateUtils.getSqlDateLong());
        invoice.setQsStatus(FpqsjgEnum.YQS.getQsjgDm());
        invoice.setQsType(qsType);
        invoice.setValid("1");
        invoice.setDeptName(queryInvoiceResult.getString("deptName"));
        invoice.setDeptId(queryInvoiceResult.getString("deptId"));
        invoice.setQsName(userName);
        invoice.setRzhYesorno("0");
        invoice.setAuthStatus("0");
//        if(QsfsEnum.PDFQS.getQsfsDm().equals(qsType) || QsfsEnum.SMYQS.getQsfsDm().equals(qsType)){
//            invoice.setScanId(queryInvoiceResult.getString("scanId"));
//        }
        if (CommonUtil.isSdfp(invoiceType)) {
            invoice.setInvoiceSource("1");
        } else {
            invoice.setInvoiceSource("0");
        }
        invoice.setScanId(queryInvoiceResult.getString("scanId"));
        return invoice;
    }

    @Override
    public JSONObject createInvoiceInfo(TDxRecordInvoice invoiceRecord, String dbName) {
        String uuid = invoiceRecord.getUuid();
        String invoiceType = invoiceRecord.getInvoiceType();

        TDxVehicleSaleInvoice vehicleSaleInfo = null;
        List<TDxRecordInvoiceDetail> invoiceDetailList = null;

        DynamicContextHolder.push(dbName + DbConstant.BUSINESS_READ);
        if (FplxEnum.JDC.getFplxDm().equals(invoiceType)) {
            QueryWrapper<TDxVehicleSaleInvoice> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("uuid", uuid);
            vehicleSaleInfo = signJdcService.getOne(queryWrapper);
        } else {
            DynamicContextHolder.push(dbName + DbConstant.DETAIL_READ);
            QueryWrapper<TDxRecordInvoiceDetail> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("uuid", uuid);
            queryWrapper.orderByAsc("detail_no");
            invoiceDetailList = signInvoiceDetailService.list(queryWrapper);
        }
        return this.createCheckInfo(invoiceRecord, vehicleSaleInfo, invoiceDetailList);
    }

    /**
     * 根据数据拼接需要返回的报文
     *
     * @param invoiceRecord
     *            底账表信息
     * @param vehicleSaleInfo
     *            机动车表信息
     * @param invoiceDetailList
     *            底账明细表信息
     * @return 返回结果
     *
     */
    private JSONObject createCheckInfo(TDxRecordInvoice invoiceRecord, TDxVehicleSaleInvoice vehicleSaleInfo,
        List<TDxRecordInvoiceDetail> invoiceDetailList) {

        JSONObject checkInfo = new JSONObject();
        InvoiceSubjectVO checkRecordVo = this.convertToCheckRecordVo(invoiceRecord);

        // 取发票上的价税合计
        String totalAmount = checkRecordVo.getTotalAmount();
        // 价税合计小写
        checkInfo.put("detailAmountTotal", totalAmount);
        // 价税合计大写
        checkInfo.put("stringTotalAmount", NumberToCN.number2CNMontrayUnit(new BigDecimal(totalAmount)));
        // 发票票面信息
        checkInfo.put("invoiceSubjectList", JSON.toJSON(checkRecordVo));
        // 机动车部分信息
        if (vehicleSaleInfo != null) {
            CheckVehicleSaleVO checkVehicleSaleVo = this.convertToVehicleSaleVo(vehicleSaleInfo);
            checkInfo.put("vehicle", JSON.toJSON(checkVehicleSaleVo));
        } else {
            checkInfo.put("vehicle", new JSONObject());
        }
        String se = "";
        // 发票明细
        if (invoiceDetailList != null && invoiceDetailList.size() > 0) {
            int count = invoiceDetailList.size();

            JSONArray detail = new JSONArray(count);
            for (TDxRecordInvoiceDetail tDxRecordInvoiceDetail : invoiceDetailList) {
                CheckRecordInvoiceDetailVO checkRecordDetailVo = this.convertToRecordDetailVo(tDxRecordInvoiceDetail);
                // 明细框 税额合计
                detail.add(JSON.toJSON(checkRecordDetailVo));
                try {
                    Double.parseDouble(checkRecordDetailVo.getTaxAmount());
                } catch (Exception e) {
                    se = checkRecordDetailVo.getTaxAmount();
                }
            }
            checkInfo.put("invoiceDetails", detail);
            checkInfo.put("detailAmountSum", MathUtil.round(invoiceRecord.getInvoiceAmount().toPlainString()));
            if (StringUtils.isNotBlank(se)) {
                checkInfo.put("taxAmountSum", se);
            } else {
                checkInfo.put("taxAmountSum", MathUtil.round(invoiceRecord.getTaxAmount().toPlainString()));
            }
        } else {
            checkInfo.put("invoiceDetails", new JSONArray());
            checkInfo.put("detailAmountSum", "0");
            checkInfo.put("taxAmountSum", "0");
        }

        return checkInfo;
    }

    private InvoiceSubjectVO convertToCheckRecordVo(TDxRecordInvoice invoiceRecord) {
        InvoiceSubjectVO checkRecordVo = new InvoiceSubjectVO();
        String fpzt = this.getFpzt(invoiceRecord.getInvoiceStatus());
        String rzzt = this.getRzzt(invoiceRecord.getAuthStatus());
        String fpzlMc = this.getFpzlMc(invoiceRecord.getInvoiceType());
        String rzType = this.getRztype(invoiceRecord.getRzhType());
        String qsStatus = this.getQsStatus(invoiceRecord.getQsStatus());
        String qsType = this.getQsType(invoiceRecord.getQsType());
        String rzlx = this.getRzlx(invoiceRecord.getRzlx());
        String rzhYesorno = this.getRzhYesorno(invoiceRecord.getRzhYesorno());
        String gxUserName = invoiceRecord.getConfirmUser();
        String dqskssq = invoiceRecord.getRzhBelongDate();
        checkRecordVo.setInvoiceStatus(fpzt);
        checkRecordVo.setSourceSystem(
            (StringUtils.isNotBlank(invoiceRecord.getSourceSystem()) && "1".equals(invoiceRecord.getSourceSystem()))
                ? "查验" : "采集");
        if (invoiceRecord.getCreateDate() != null) {
            checkRecordVo.setCreateDate(DateUtils.dateToStrLong(invoiceRecord.getCreateDate()));
        } else {
            checkRecordVo.setCreateDate("");
        }
        checkRecordVo.setGxUserName(StringHelper.trimEnter(invoiceRecord.getGxUserName()));
        checkRecordVo.setRzhType(StringHelper.trimEnter(rzType));
        checkRecordVo.setInvoiceType(StringHelper.trimEnter(invoiceRecord.getInvoiceType()));
        checkRecordVo.setInvoiceString(StringHelper.trimEnter(fpzlMc));
        checkRecordVo.setInvoiceCode(invoiceRecord.getInvoiceCode());
        checkRecordVo.setInvoiceNo(invoiceRecord.getInvoiceNo());
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日");
        checkRecordVo.setInvoiceDate(sdf.format(invoiceRecord.getInvoiceDate()));
        checkRecordVo.setInvoiceAmount(invoiceRecord.getInvoiceAmount() == null ? ""
            : MathUtil.round(invoiceRecord.getInvoiceAmount().toPlainString()));
        checkRecordVo.setTaxAmount(
            invoiceRecord.getTaxAmount() == null ? "" : MathUtil.round(invoiceRecord.getTaxAmount().toPlainString()));
        if (invoiceRecord.getTotalAmount() == null) {
            BigDecimal add = invoiceRecord.getInvoiceAmount().add(invoiceRecord.getTaxAmount());
            checkRecordVo.setTotalAmount(MathUtil.round(add.toPlainString()));
        } else {
            checkRecordVo.setTotalAmount(invoiceRecord.getTotalAmount() == null ? ""
                : MathUtil.round(invoiceRecord.getTotalAmount().toPlainString()));
        }
        checkRecordVo.setGfTaxNo(StringHelper.trimEnter(invoiceRecord.getGfTaxNo()));
        checkRecordVo.setGfName(StringHelper.trimEnter(invoiceRecord.getGfName()));
        checkRecordVo.setGfAddressAndPhone(StringHelper.trimEnter(invoiceRecord.getGfAddressAndPhone()));
        checkRecordVo.setGfBankAndNo(StringHelper.trimEnter(invoiceRecord.getGfBankAndNo()));
        checkRecordVo.setXfTaxNo(StringHelper.trimEnter(invoiceRecord.getXfTaxNo()));
        checkRecordVo.setXfName(StringHelper.trimEnter(invoiceRecord.getXfName()));
        checkRecordVo.setXfAddressAndPhone(StringHelper.trimEnter(invoiceRecord.getXfAddressAndPhone()));
        checkRecordVo.setXfBankAndNo(StringHelper.trimEnter(invoiceRecord.getXfBankAndNo()));
        checkRecordVo.setDqskssq(StringHelper.trimEnter(invoiceRecord.getDqskssq()));
        checkRecordVo.setId(String.valueOf(invoiceRecord.getId()));
        checkRecordVo.setUuid(invoiceRecord.getUuid());
        checkRecordVo
            .setQsDate((invoiceRecord.getQsDate() == null) ? "" : DateUtils.dateToStrLong(invoiceRecord.getQsDate()));
        checkRecordVo.setQsName(StringHelper.trimEnter(invoiceRecord.getQsName()));
        checkRecordVo.setQsStatus(qsStatus);
        checkRecordVo.setQsType(qsType);
        checkRecordVo.setRzhDate(
            (invoiceRecord.getRzhDate() == null) ? "" : DateUtils.dateToStrLong(invoiceRecord.getRzhDate()));
        checkRecordVo.setRzlx(rzlx);
        checkRecordVo.setRemark(invoiceRecord.getRemark());
        checkRecordVo.setRzhYesorno(rzhYesorno);
        checkRecordVo.setAuthStatus(rzzt);
        checkRecordVo.setCheckCode(invoiceRecord.getCheckCode());
        checkRecordVo.setDqskssq(dqskssq);
        checkRecordVo.setGxUserName(gxUserName);
        return checkRecordVo;
    }

    private String getRzhYesorno(String rzhYesorno) {
        String rzh;
        if ("1".equals(rzhYesorno)) {
            rzh = "已认证";
        } else {
            rzh = "未认证";
        }
        return rzh;
    }

    /**
     * 转义认证类型
     *
     * @param rzlx
     *            认证类型
     * @return 返回结果
     *
     */
    private String getRzlx(String rzlx) {
        String rzlxmc = "";
        if ("1".equals(rzlx)) {
            rzlxmc = "抵扣认证";
        } else if ("2".equals(rzlx)) {
            rzlxmc = "退税认证";
        } else if ("3".equals(rzlx)) {
            rzlxmc = "代办退税认证";
        }
        return rzlxmc;
    }

    /**
     * 转义签收方式
     *
     * @param qsType
     *            签收方式
     * @return 返回结果
     *
     */
    private String getQsType(String qsType) {
        String qsfs = "";
        if (QsfsEnum.DRQS.getQsfsDm().equals(qsType)) {
            qsfs = QsfsEnum.DRQS.getQsfsMc(QsfsEnum.DRQS.getIndex());
        } else if (QsfsEnum.APPQS.getQsfsDm().equals(qsType)) {
            qsfs = QsfsEnum.APPQS.getQsfsMc(QsfsEnum.APPQS.getIndex());
        } else if (QsfsEnum.PDFQS.getQsfsDm().equals(qsType)) {
            qsfs = QsfsEnum.PDFQS.getQsfsMc(QsfsEnum.PDFQS.getIndex());
        } else if (QsfsEnum.SGQS.getQsfsDm().equals(qsType)) {
            qsfs = QsfsEnum.SGQS.getQsfsMc(QsfsEnum.SGQS.getIndex());
        } else if (QsfsEnum.SMQS.getQsfsDm().equals(qsType)) {
            qsfs = QsfsEnum.SMQS.getQsfsMc(QsfsEnum.SMQS.getIndex());
        } else if (QsfsEnum.SMYQS.getQsfsDm().equals(qsType)) {
            qsfs = QsfsEnum.SMYQS.getQsfsMc(QsfsEnum.SMYQS.getIndex());
        }
        return qsfs;
    }

    /**
     * 转义签收状态
     *
     * @param qsStatus
     *            签收状态
     * @return 返回结果
     *
     */
    private String getQsStatus(String qsStatus) {
        String qszt = "";
        if (FpqsjgEnum.YQS.getQsjgDm().equals(qsStatus)) {
            qszt = FpqsjgEnum.YQS.getQsjgMc(FpqsjgEnum.YQS.getIndex());
        } else if (FpqsjgEnum.WQS.getQsjgDm().equals(qsStatus)) {
            qszt = FpqsjgEnum.WQS.getQsjgMc(FpqsjgEnum.WQS.getIndex());
        }
        return qszt;
    }

    /**
     * 转义认证方式
     *
     * @param rzhType
     *            认证方式
     * @return 返回结果
     *
     */
    private String getRztype(String rzhType) {
        String rzType = "";
        if (RzfsEnum.GXRZ.getRzfsDm().equals(rzhType)) {
            rzType = RzfsEnum.GXRZ.getRzfsMc(RzfsEnum.GXRZ.getIndex());
        } else if (RzfsEnum.SMRZ.getRzfsDm().equals(rzhType)) {
            rzType = RzfsEnum.SMRZ.getRzfsMc(RzfsEnum.SMRZ.getIndex());
        }
        return rzType;
    }

    private String getFpzlMc(String invoiceType) {
        String fplx = "";
        if (FplxEnum.DZP.getFplxDm().equals(invoiceType)) {
            fplx = FplxEnum.DZP.getFplxMc(FplxEnum.DZP.getIndex());
        } else if (FplxEnum.JDC.getFplxDm().equals(invoiceType)) {
            fplx = FplxEnum.JDC.getFplxMc(FplxEnum.JDC.getIndex());
        } else if (FplxEnum.JSP.getFplxDm().equals(invoiceType)) {
            fplx = FplxEnum.JSP.getFplxMc(FplxEnum.JSP.getIndex());
        } else if (FplxEnum.PP.getFplxDm().equals(invoiceType)) {
            fplx = FplxEnum.PP.getFplxMc(FplxEnum.PP.getIndex());
        } else if (FplxEnum.TXF.getFplxDm().equals(invoiceType)) {
            fplx = FplxEnum.TXF.getFplxMc(FplxEnum.TXF.getIndex());
        } else if (FplxEnum.ZP.getFplxDm().equals(invoiceType)) {
            fplx = FplxEnum.ZP.getFplxMc(FplxEnum.ZP.getIndex());
        }
        return fplx;
    }

    private String getRzzt(String authStatus) {
        String rzzt = "";
        if (RzclztEnum.RZCG.getRzclztDm().equals(authStatus)) {
            rzzt = RzclztEnum.RZCG.getRzclztMc(RzclztEnum.RZCG.getIndex());
        } else if (RzclztEnum.RZSB.getRzclztDm().equals(authStatus)) {
            rzzt = RzclztEnum.RZSB.getRzclztMc(RzclztEnum.RZSB.getIndex());
        } else if (RzclztEnum.WRZ.getRzclztDm().equals(authStatus)) {
            rzzt = RzclztEnum.WRZ.getRzclztMc(RzclztEnum.WRZ.getIndex());
        } else if (RzclztEnum.YFSRZ.getRzclztDm().equals(authStatus)) {
            rzzt = RzclztEnum.YFSRZ.getRzclztMc(RzclztEnum.YFSRZ.getIndex());
        } else if (RzclztEnum.YGXWQR.getRzclztDm().equals(authStatus)) {
            rzzt = RzclztEnum.YGXWQR.getRzclztMc(RzclztEnum.YGXWQR.getIndex());
        } else if (RzclztEnum.YQR.getRzclztDm().equals(authStatus)) {
            rzzt = RzclztEnum.YQR.getRzclztMc(RzclztEnum.YQR.getIndex());
        }
        return rzzt;
    }

    private String getFpzt(String invoiceStatus) {
        String fpztMc = "";
        if (FpztEnum.HC.getFpztDm().equals(invoiceStatus)) {
            fpztMc = FpztEnum.HC.getFpztMc(FpztEnum.HC.getIndex());
        } else if (FpztEnum.SK.getFpztDm().equals(invoiceStatus)) {
            fpztMc = FpztEnum.SK.getFpztMc(FpztEnum.SK.getIndex());
        } else if (FpztEnum.YC.getFpztDm().equals(invoiceStatus)) {
            fpztMc = FpztEnum.YC.getFpztMc(FpztEnum.YC.getIndex());
        } else if (FpztEnum.ZC.getFpztDm().equals(invoiceStatus)) {
            fpztMc = FpztEnum.ZC.getFpztMc(FpztEnum.ZC.getIndex());
        } else if (FpztEnum.ZF.getFpztDm().equals(invoiceStatus)) {
            fpztMc = FpztEnum.ZF.getFpztMc(FpztEnum.ZF.getIndex());
        }
        return fpztMc;
    }

    private CheckVehicleSaleVO convertToVehicleSaleVo(TDxVehicleSaleInvoice vehicleSaleInfo) {
        String taxRate = StringHelper.trimEnter(vehicleSaleInfo.getTaxRate());
        CheckVehicleSaleVO checkVehicleSaleVo = new CheckVehicleSaleVO();
        checkVehicleSaleVo.setBuyerBank(StringHelper.trimEnter(vehicleSaleInfo.getBuyerBank()));
        checkVehicleSaleVo.setBuyerIdNum(StringHelper.trimEnter(vehicleSaleInfo.getBuyerIdNum()));
        checkVehicleSaleVo.setCertificate(StringHelper.trimEnter(vehicleSaleInfo.getCertificate()));
        checkVehicleSaleVo.setCertificateImport(StringHelper.trimEnter(vehicleSaleInfo.getCertificateImport()));
        checkVehicleSaleVo.setEngineNo(StringHelper.trimEnter(vehicleSaleInfo.getEngineNo()));
        checkVehicleSaleVo.setFactoryModel(StringHelper.trimEnter(vehicleSaleInfo.getFactoryModel()));
        checkVehicleSaleVo.setInspectionNum(StringHelper.trimEnter(vehicleSaleInfo.getInspectionNum()));
        checkVehicleSaleVo.setLimitPeople(StringHelper.trimEnter(vehicleSaleInfo.getLimitPeople()));
        checkVehicleSaleVo.setPhone(StringHelper.trimEnter(vehicleSaleInfo.getPhone()));
        checkVehicleSaleVo.setProductPlace(StringHelper.trimEnter(vehicleSaleInfo.getProductPlace()));
        checkVehicleSaleVo.setTaxBureauCode(StringHelper.trimEnter(vehicleSaleInfo.getTaxBureauCode()));
        checkVehicleSaleVo.setTaxBureauName(StringHelper.trimEnter(vehicleSaleInfo.getTaxBureauName()));
        checkVehicleSaleVo.setTaxRate(taxRate);
        checkVehicleSaleVo.setTaxRecords(StringHelper.trimEnter(vehicleSaleInfo.getTaxRecords()));
        checkVehicleSaleVo.setTonnage(StringHelper.trimEnter(vehicleSaleInfo.getTonnage()));
        checkVehicleSaleVo.setVehicleNo(StringHelper.trimEnter(vehicleSaleInfo.getVehicleNo()));
        checkVehicleSaleVo.setVehicleType(StringHelper.trimEnter(vehicleSaleInfo.getVehicleType()));
        return checkVehicleSaleVo;
    }

    private CheckRecordInvoiceDetailVO convertToRecordDetailVo(TDxRecordInvoiceDetail tDxRecordInvoiceDetail) {
        CheckRecordInvoiceDetailVO checkRecordDetailVo = new CheckRecordInvoiceDetailVO();
        if (StringHelper.trimEnter(tDxRecordInvoiceDetail.getTaxRate()).matches("[0-9]{1,}")) {
            checkRecordDetailVo.setTaxRate(StringHelper.trimEnter(tDxRecordInvoiceDetail.getTaxRate()) + "%");
        } else {
            checkRecordDetailVo.setTaxRate(StringHelper.trimEnter(tDxRecordInvoiceDetail.getTaxRate()));
        }
        checkRecordDetailVo.setCph(StringHelper.trimEnter(tDxRecordInvoiceDetail.getCph()));
        checkRecordDetailVo.setDetailAmount(StringHelper.trimEnter(tDxRecordInvoiceDetail.getDetailAmount()));
        checkRecordDetailVo.setDetailNo(StringHelper.trimEnter(tDxRecordInvoiceDetail.getDetailNo()));
        checkRecordDetailVo.setGoodsName(StringHelper.trimEnter(tDxRecordInvoiceDetail.getGoodsName()));
        checkRecordDetailVo.setGoodsNum(StringHelper.trimEnter(tDxRecordInvoiceDetail.getGoodsNum()));
        checkRecordDetailVo.setLx(StringHelper.trimEnter(tDxRecordInvoiceDetail.getLx()));
        checkRecordDetailVo.setModel(StringHelper.trimEnter(tDxRecordInvoiceDetail.getModel()));
        checkRecordDetailVo.setNum(StringHelper.trimEnter(tDxRecordInvoiceDetail.getNum()));
        checkRecordDetailVo.setTaxAmount(StringHelper.trimEnter(tDxRecordInvoiceDetail.getTaxAmount()));

        checkRecordDetailVo.setTxrqq(StringHelper.trimEnter(tDxRecordInvoiceDetail.getTxrqq()));
        checkRecordDetailVo.setTxrqz(StringHelper.trimEnter(tDxRecordInvoiceDetail.getTxrqz()));
        checkRecordDetailVo.setUnit(StringHelper.trimEnter(tDxRecordInvoiceDetail.getUnit()));
        checkRecordDetailVo.setUnitPrice(StringHelper.trimEnter(tDxRecordInvoiceDetail.getUnitPrice()));
        return checkRecordDetailVo;
    }

    @Override
    public TDxVehicleSaleInvoice vehicleInvoice(JSONObject queryInvoiceResult) {
        String invoiceType = queryInvoiceResult.getString("invoiceType");
        if (FplxEnum.ESC.getFplxDm().equals(invoiceType)) {
            String invoiceCode = queryInvoiceResult.getString("invoiceCode");
            String invoiceNo = queryInvoiceResult.getString("invoiceNo");
            String uuid = invoiceCode + invoiceNo;

            TDxVehicleSaleInvoice vehicleSaleInvoice = new TDxVehicleSaleInvoice();
            vehicleSaleInvoice.setUuid(uuid);
            vehicleSaleInvoice.setPlateNo(queryInvoiceResult.getString("licensePlate"));
            vehicleSaleInvoice.setRegistrationNo(queryInvoiceResult.getString("registrationNo"));
            if(StringUtils.isNotBlank(queryInvoiceResult.getString("vehicleType"))){
                vehicleSaleInvoice.setVehicleType(queryInvoiceResult.getString("vehicleType"));
            }
            if(StringUtils.isNotBlank(queryInvoiceResult.getString("bandModel"))){
                vehicleSaleInvoice.setFactoryModel(queryInvoiceResult.getString("bandModel"));
            }
            if(StringUtils.isNotBlank(queryInvoiceResult.getString("vehicleIdentificationNo"))){
                vehicleSaleInvoice.setVehicleNo(queryInvoiceResult.getString("vehicleIdentificationNo"));
            }
            vehicleSaleInvoice.setCarPrice(queryInvoiceResult.getString("carPrice"));
            vehicleSaleInvoice.setVehicleAdminOffice(queryInvoiceResult.getString("vehicleAdminOffice"));
            vehicleSaleInvoice.setBuyerUnit(queryInvoiceResult.getString("buyerUnitOrIndividual"));
            vehicleSaleInvoice.setBuyerUnitCode(queryInvoiceResult.getString("buyerUnitCodeOrIdNo"));
            vehicleSaleInvoice.setBuyerUnitAddress(queryInvoiceResult.getString("buyerUnitOrIndividualAddress"));
            vehicleSaleInvoice.setBuyerPhone(queryInvoiceResult.getString("buyerPhone"));
            vehicleSaleInvoice.setSellerUnit(queryInvoiceResult.getString("sellerUnitOrIndividual"));
            vehicleSaleInvoice.setSellerUnitCode(queryInvoiceResult.getString("sellerUnitCodeOrIdNo"));
            vehicleSaleInvoice.setSellerUnitAddress(queryInvoiceResult.getString("sellerUnitOrIndividualAddress"));
            vehicleSaleInvoice.setSellerPhone(queryInvoiceResult.getString("sellerPhone"));
            vehicleSaleInvoice.setAuctionUnit(queryInvoiceResult.getString("businessUnit"));
            vehicleSaleInvoice.setAuctionAddress(queryInvoiceResult.getString("businessUnitAddress"));
            vehicleSaleInvoice.setAuctionTaxNo(queryInvoiceResult.getString("businessUnitTaxNo"));
            vehicleSaleInvoice.setAuctionBank(queryInvoiceResult.getString("businessUnitBankAndAccount"));
            vehicleSaleInvoice.setAuctionPhone(queryInvoiceResult.getString("businessUnitPhone"));
            vehicleSaleInvoice.setCarMarket(queryInvoiceResult.getString("lemonMarket"));
            vehicleSaleInvoice.setCarMarketTaxNo(queryInvoiceResult.getString("lemonMarketTaxNo"));
            vehicleSaleInvoice.setCarMarketAddress(queryInvoiceResult.getString("lemonMarketAddress"));
            vehicleSaleInvoice.setCarMarketBank(queryInvoiceResult.getString("lemonMarketBankAndAccount"));
            vehicleSaleInvoice.setCarMarketPhone(queryInvoiceResult.getString("lemonMarketPhone"));
            vehicleSaleInvoice.setCompany(queryInvoiceResult.getString("company"));
            return vehicleSaleInvoice;
        } else {
            return null;
        }
    }
}
