package com.dxhy.core.service.invoicedetail;

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.dxhy.common.constant.DbConstant;
import com.dxhy.common.constant.DictConstant;
import com.dxhy.common.datasource.config.DynamicContextHolder;
import com.dxhy.common.enums.*;
import com.dxhy.common.service.DictdetaServcice;
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.DateUtils;
import com.dxhy.core.dao.InvoiceDetailDao;
import com.dxhy.core.dao.TDxInvoiceImgDao;
import com.dxhy.core.dao.TDxRecordInvoiceDao;
import com.dxhy.core.entity.TDxInvoiceImg;
import com.dxhy.core.entity.TDxRecordInvoice;
import com.dxhy.core.job.entity.TDxRecordInvoiceDetail;
import com.dxhy.core.job.entity.TDxVehicleSaleInvoice;
import com.dxhy.core.model.*;
import com.dxhy.core.service.singletable.IInvoiceDetail;
import com.dxhy.core.service.singletable.IJdcService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author user
 * @Auto xiexuedi
 * @date 2019/05/24 11:21
 */
@SuppressWarnings("AlibabaUndefineMagicConstant")
@Service("invoiceDetailService")
@Slf4j

public class InvoiceDetailServiceImpl extends MpBaseServiceImpl<TDxRecordInvoiceDao, TDxRecordInvoice>
        implements InvoiceDetailService {
    @Resource
    private InvoiceDetailDao invoiceDetailDao;

    @Resource
    private IJdcService jdcService;

    @Resource
    private IInvoiceDetail invoiceDetail;
    @Resource
    private TDxInvoiceImgDao tDxInvoiceImgDao;
    @Resource
    private DictdetaServcice dictdetaServcice;

    @Override
    public List<CertifiedInvoiceVo> queryInvoiceSubject(String invoiceNo, String invoiceCode, String dbNmae) {
        DynamicContextHolder.push(dbNmae + DbConstant.BUSINESS_READ);
        Map<String, Object> map = new HashMap<>(2);
        map.put("invoiceNo", invoiceNo);
        map.put("invoiceCode", invoiceCode);
        return invoiceDetailDao.queryInvoiceSubject(map);
    }

    @Override
    public List<InvoiceDetails> selectInvoiceDetails(String invoiceNo, String invoiceCode, String dbName) {
        DynamicContextHolder.push(dbName + DbConstant.DETAIL_READ);
        Map<String, Object> map = new HashMap<>(3);
        map.put("invoiceNo", invoiceNo);
        map.put("invoiceCode", invoiceCode);
        return invoiceDetailDao.selectInvoiceDetails(map);
    }

    @Override
    public List<InvoiceDetails> selectInspectionDetails(String uuid, String dbName) {
        DynamicContextHolder.push(dbName + DbConstant.BUSINESS_READ);
        return invoiceDetailDao.selectInspectionDetails(uuid);
    }

    @Override
    public List<TDxVehicleSaleInvoice> selectVehicleSaleInvoice(String uuid, String dbName) {
        DynamicContextHolder.push(dbName + DbConstant.BUSINESS_READ);
        return invoiceDetailDao.selectVehicleSaleInvoice(uuid);
    }

    @Override
    public String getInvoiceInfo(Map<String, String> pramsMap) {
        JSONObject checkInfo = null;
        String invoiceCode = pramsMap.get("invoiceCode");
        String invoiceNo = pramsMap.get("invoiceNo");
        String uuid = (StringUtils.isEmpty(invoiceCode) ? "" : invoiceCode) + invoiceNo;

        DynamicContextHolder.push(pramsMap.get("dbName") + DbConstant.BUSINESS_READ);
        QueryWrapper<TDxRecordInvoice> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("uuid", uuid);
        TDxRecordInvoice invoiceRecord = super.getOne(queryWrapper);

        if (invoiceRecord != null) {
            checkInfo = this.createInvoiceInfo(invoiceRecord, pramsMap.get("dbName"));
            return super.responseResult(checkInfo);
        } else {
            return null;
        }
    }

    private 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) || FplxEnum.ESC.getFplxDm().equals(invoiceType)) {
            QueryWrapper<TDxVehicleSaleInvoice> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("uuid", uuid);
            vehicleSaleInfo = jdcService.getOne(queryWrapper);
        } else {
            DynamicContextHolder.push(dbName + DbConstant.DETAIL_READ);
            QueryWrapper<TDxRecordInvoiceDetail> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("uuid", uuid);
            queryWrapper.orderByAsc("detail_no");
            invoiceDetailList = invoiceDetail.list(queryWrapper);
        }
        String scanId = invoiceRecord.getScanId();
        TDxInvoiceImg img = null;
        if (StringUtils.isNotBlank(scanId)) {
            DynamicContextHolder.push(dbName + DbConstant.BUSINESS_READ);
            QueryWrapper<TDxInvoiceImg> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("scan_id", scanId);
            img = tDxInvoiceImgDao.selectOne(queryWrapper);

        }
        return this.createCheckInfo(invoiceRecord, vehicleSaleInfo, invoiceDetailList, img);
    }

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

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

        // 取发票上的价税合计
        String totalAmount = checkRecordVo.getTotalAmount();
        if(totalAmount != null && StringUtils.isNoneBlank(totalAmount)) {
            log.info("totalAmount={}",totalAmount);
            // 价税合计小写
            checkInfo.put("detailAmountTotal", totalAmount);
            // 价税合计大写
            checkInfo.put("stringTotalAmount", NumberToCN.number2CNMontrayUnit(new BigDecimal(totalAmount)));
        }else{
            // 价税合计小写
            checkInfo.put("detailAmountTotal", "0");
            // 价税合计大写
            checkInfo.put("stringTotalAmount", "零");
        }
        // 发票票面信息
        checkInfo.put("invoiceSubjectList", JSON.toJSON(checkRecordVo));
        // 机动车部分信息
        if (vehicleSaleInfo != null) {
            CheckVehicleSaleVO checkVehicleSaleVo = this.convertToVehicleSaleVo(vehicleSaleInfo,
                    invoiceRecord.getInvoiceType(), invoiceRecord.getInvoicer());
            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);
            if ("11".equals(invoiceRecord.getInvoiceType())) {
                checkInfo.put("detailAmountSum", totalAmount);
                checkInfo.put("taxAmountSum", checkRecordVo.getTaxAmount());
            } else {
                checkInfo.put("detailAmountSum", MathUtil.round(invoiceRecord.getInvoiceAmount().toPlainString()));
                if (StringUtils.isNotBlank(se) && invoiceRecord.getTaxAmount().compareTo(new BigDecimal(0)) == 0) {
                    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, TDxInvoiceImg img, List<TDxRecordInvoiceDetail> invoiceDetailList) {
        InvoiceSubjectVO checkRecordVo = new InvoiceSubjectVO();
        // 字典值转换
        String fpzt = dictdetaServcice.queryDictName(DictConstant.INVOICE_STATUS, invoiceRecord.getInvoiceStatus());
        String rzzt = dictdetaServcice.queryDictName(DictConstant.AUTH_STATUS_ALL, invoiceRecord.getAuthStatus());
        String fpzlMc = dictdetaServcice.queryDictName(DictConstant.INVOICE_TYPE_VAT, invoiceRecord.getInvoiceType());
        String rzType = dictdetaServcice.queryDictName(DictConstant.DEDU_TYPE, invoiceRecord.getRzhType());
        String qsStatus = dictdetaServcice.queryDictName(DictConstant.QS_STATUS, invoiceRecord.getQsStatus());
        String qsType = dictdetaServcice.queryDictName(DictConstant.QS_TYPE, invoiceRecord.getQsType());
        String rzlx = this.getRzlx(invoiceRecord.getRzlx());
        String rzhYesorno = this.getRzhYesorno(invoiceRecord.getRzhYesorno());
        String gxUserName = invoiceRecord.getConfirmUser();
        String dqskssq = invoiceRecord.getRzhBelongDate();

        checkRecordVo.setConfirmDate(
                (invoiceRecord.getConfirmDate() == null) ? "" : DateUtils.dateToStrLong(invoiceRecord.getConfirmDate()));

        checkRecordVo
                .setGxDate((invoiceRecord.getGxDate() == null) ? "" : DateUtils.dateToStrLong(invoiceRecord.getGxDate()));

        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("");
        }
        if ("01".equals(invoiceRecord.getInvoiceType()) || "03".equals(invoiceRecord.getInvoiceType())
                || "14".equals(invoiceRecord.getInvoiceType())) {
            if ("0".equals(invoiceRecord.getInvoiceStatus())) {
                if (StringUtils.isNotBlank(invoiceRecord.getGxUserAccount())) {
                    checkRecordVo.setGxState("是");
                } else {
                    checkRecordVo.setGxState("否");
                }
            } else {
                checkRecordVo.setGxState("否");
            }
        } else {
            checkRecordVo.setGxState("否");
        }
        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());
        checkRecordVo.setEleInvoiceNo(invoiceRecord.getEleInvoiceNo());
        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 ("11".equals(invoiceRecord.getInvoiceType())) {
            BigDecimal detailAmount = new BigDecimal(0);
            if (CollectionUtils.isNotEmpty(invoiceDetailList)) {
                for (TDxRecordInvoiceDetail tdxRecordInvoiceDetail : invoiceDetailList) {
                    if (tdxRecordInvoiceDetail.getDetailAmount() != null) {
                        detailAmount = detailAmount.add(new BigDecimal(tdxRecordInvoiceDetail.getDetailAmount()));
                    }
                }
            }
            checkRecordVo.setTotalAmount(MathUtil.round(detailAmount.toPlainString()));
        } else {
            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);
        if (img != null) {
            checkRecordVo.setScanId(img.getScanId());
            String filePath = img.getImage();
            if (StringUtils.isNotBlank(filePath)) {
                String path = filePath.substring(filePath.lastIndexOf("/") + 1);
                checkRecordVo.setFilePath(path);
            }
            String imgPath = img.getImagePath();
            if (StringUtils.isNotBlank(imgPath)) {
                String path = imgPath.substring(imgPath.lastIndexOf("/") + 1);
                checkRecordVo.setImgPath(path);
            }
        }
        //触发企业管控规则 0-否 1-是
        checkRecordVo.setIllegalEnterprise(invoiceRecord.getIllegalEnterprise());
        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());
        } else if (FplxEnum.DZZP.getFplxDm().equals(invoiceType)) {
            fplx = FplxEnum.DZZP.getFplxMc(FplxEnum.DZZP.getIndex());
        } else if (FplxEnum.ESC.getFplxDm().equals(invoiceType)) {
            fplx = FplxEnum.ESC.getFplxMc(FplxEnum.ESC.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 invoiceType,
                                                      String invoicer) {
        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()));
        // 二手车相关信息
        if (FplxEnum.ESC.getFplxDm().equals(invoiceType)) {
            checkVehicleSaleVo.setLicensePlate(StringHelper.trimEnter(vehicleSaleInfo.getPlateNo()));
            checkVehicleSaleVo.setRegistrationNo(StringHelper.trimEnter(vehicleSaleInfo.getRegistrationNo()));
            checkVehicleSaleVo.setVehicleAdminOffice(StringHelper.trimEnter(vehicleSaleInfo.getVehicleAdminOffice()));
            checkVehicleSaleVo.setAuctionUnit(StringHelper.trimEnter(vehicleSaleInfo.getAuctionUnit()));
            checkVehicleSaleVo.setAuctionAddress(StringHelper.trimEnter(vehicleSaleInfo.getAuctionAddress()));
            checkVehicleSaleVo.setAuctionTaxNo(StringHelper.trimEnter(vehicleSaleInfo.getAuctionTaxNo()));
            checkVehicleSaleVo.setAuctionBank(StringHelper.trimEnter(vehicleSaleInfo.getAuctionBank()));
            checkVehicleSaleVo.setAuctionPhone(StringHelper.trimEnter(vehicleSaleInfo.getAuctionPhone()));
            checkVehicleSaleVo.setCarMarket(StringHelper.trimEnter(vehicleSaleInfo.getCarMarket()));
            checkVehicleSaleVo.setCarMarketTaxNo(StringHelper.trimEnter(vehicleSaleInfo.getCarMarketTaxNo()));
            checkVehicleSaleVo.setCarMarketAddress(StringHelper.trimEnter(vehicleSaleInfo.getCarMarketAddress()));
            checkVehicleSaleVo.setCarMarketBank(StringHelper.trimEnter(vehicleSaleInfo.getCarMarketBank()));
            checkVehicleSaleVo.setCarMarketPhone(StringHelper.trimEnter(vehicleSaleInfo.getCarMarketPhone()));
            checkVehicleSaleVo.setCarPrice(StringHelper.trimEnter(vehicleSaleInfo.getCarPrice()));
            checkVehicleSaleVo.setBuyerUnitOrIndividual(StringHelper.trimEnter(vehicleSaleInfo.getBuyerUnit()));
            checkVehicleSaleVo.setBuyerUnitCodeOrIdNo(StringHelper.trimEnter(vehicleSaleInfo.getBuyerUnitCode()));
            checkVehicleSaleVo
                    .setBuyerUnitOrIndividualAddress(StringHelper.trimEnter(vehicleSaleInfo.getBuyerUnitAddress()));
            checkVehicleSaleVo.setBuyerPhone(StringHelper.trimEnter(vehicleSaleInfo.getBuyerPhone()));
            checkVehicleSaleVo.setSellerUnitOrIndividual(StringHelper.trimEnter(vehicleSaleInfo.getSellerUnit()));
            checkVehicleSaleVo.setSellerUnitCodeOrIdNo(StringHelper.trimEnter(vehicleSaleInfo.getSellerUnitCode()));
            checkVehicleSaleVo
                    .setSellerUnitOrIndividualAddress(StringHelper.trimEnter(vehicleSaleInfo.getSellerUnitAddress()));
            checkVehicleSaleVo.setSellerPhone(StringHelper.trimEnter(vehicleSaleInfo.getSellerPhone()));
            if (StringUtils.isNotBlank(invoicer)) {
                checkVehicleSaleVo.setInvoicer(StringHelper.trimEnter(invoicer));
            }
        }
        return checkVehicleSaleVo;
    }

    private CheckRecordInvoiceDetailVO convertToRecordDetailVo(TDxRecordInvoiceDetail tDxRecordInvoiceDetail) {
        CheckRecordInvoiceDetailVO checkRecordDetailVo = new CheckRecordInvoiceDetailVO();
        if (StringHelper.trimEnter(tDxRecordInvoiceDetail.getTaxRate()).matches("[0-9]+")) {
            checkRecordDetailVo.setTaxRate(StringHelper.trimEnter(tDxRecordInvoiceDetail.getTaxRate()) + "%");
        } else if (tDxRecordInvoiceDetail.getTaxRate().contains(".")) {
            String taxRate = StringHelper.trimEnter(tDxRecordInvoiceDetail.getTaxRate());
            if (taxRate.contains(".")) {
                taxRate = taxRate.replace(".", "").replace("0", "");
            }
            checkRecordDetailVo.setTaxRate(taxRate + "%");
        } else {
            checkRecordDetailVo.setTaxRate(StringHelper.trimEnter(tDxRecordInvoiceDetail.getTaxRate()));
        }

        if (checkRecordDetailVo.getTaxRate() != null)
            checkRecordDetailVo.setTaxCode(getZSM(checkRecordDetailVo.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 String getSaleInvoiceInfo(Map<String, String> pramsMap) {
        JSONObject checkInfo = null;
        String invoiceCode = pramsMap.get("invoiceCode");
        String invoiceNo = pramsMap.get("invoiceNo");
        String uuid = (StringUtils.isEmpty(invoiceCode) ? "" : invoiceCode) + invoiceNo;

        DynamicContextHolder.push(pramsMap.get("dbName") + DbConstant.BUSINESS_READ);

        TDxRecordInvoice invoiceRecord = invoiceDetailDao.getSaleInvoiceByUuid(uuid);

        if (invoiceRecord != null) {
            checkInfo = this.createInvoiceSalesInfo(invoiceRecord, pramsMap.get("dbName"));
            return super.responseResult(checkInfo);
        } else {
            return null;
        }
    }

    private JSONObject createInvoiceSalesInfo(TDxRecordInvoice invoiceRecord, String dbName) {
        String uuid = invoiceRecord.getUuid();
        String invoiceType = invoiceRecord.getInvoiceType();

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

        if (FplxEnum.JDC.getFplxDm().equals(invoiceType)) {
            vehicleSaleInfo = invoiceDetail.getVehicleDetailSales(dbName, uuid);
        } else {
            invoiceDetailList = invoiceDetail.getSalesInvoiceDetail(dbName, uuid);
        }
        String scanId = invoiceRecord.getScanId();
        TDxInvoiceImg img = null;
        if (StringUtils.isNotBlank(scanId)) {
            DynamicContextHolder.push(dbName + DbConstant.BUSINESS_READ);
            QueryWrapper<TDxInvoiceImg> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("scan_id", scanId);
            img = tDxInvoiceImgDao.selectOne(queryWrapper);

        }
        return this.createCheckInfo(invoiceRecord, vehicleSaleInfo, invoiceDetailList, img);
    }

    private String getZSM(String taxRate) {

        String sm = "";

        switch (taxRate) {
            // 发票采集
            case "0":
                sm = "J0";
                break;
            case "0.00":
                sm = "J0";
                break;
            case "免税":
                sm = "J0";
                break;
            case "不征税":
                sm = "J0";
                break;
            case "0.16":
                sm = "J1";
                break;
            case "0.13":
                sm = "J2";
                break;
            case "0.10":
                sm = "J3";
                break;
            case "0.09":
                sm = "J4";
                break;
            case "0.06":
                sm = "J5";
                break;
            case "0.05":
                sm = "J6";
                break;
            case "0.03":
                sm = "J7";
                break;
            case "0.02":
                sm = "J8";
                break;
            case "0.01":
                sm = "J9";
                break;
            case "0.17":
                sm = "JC";
                break;
            case "0.000":
                sm = "J0";
                break;
            case "16":
                sm = "J1";
                break;
            case "13":
                sm = "J2";
                break;
            case "10":
                sm = "J3";
                break;
            case "9":
                sm = "J4";
                break;
            case "6":
                sm = "J5";
                break;
            case "5":
                sm = "J6";
                break;
            case "3":
                sm = "J7";
                break;
            case "2":
                sm = "J8";
                break;
            case "1.5":
                sm = "JA";
                break;
            case "1":
                sm = "J9";
                break;
            case "17":
                sm = "JC";
                break;
            default:
                sm = "";
                break;

        }
        return sm;
    }
}
