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

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.dxhy.api.model.config.UserInfo;
import com.dxhy.api.model.invoice.invoiceCheck.TDxCheckLog;
import com.dxhy.api.model.sign.*;
import com.dxhy.api.model.sign.openservice.OpenServiceInvokeException;
import com.dxhy.api.model.sign.openservice.OpenServiceSingleInvoiceCheckJxpt;
import com.dxhy.api.model.sign.openservice.OpenServiceSingleInvoiceCheckRequest;
import com.dxhy.common.constant.DbConstant;
import com.dxhy.common.datasource.config.DynamicContextHolder;
import com.dxhy.common.enums.FplxEnum;
import com.dxhy.common.enums.ValidEnum;
import com.dxhy.common.service.TabulateRedisService;
import com.dxhy.common.service.impl.MpBaseServiceImpl;
import com.dxhy.common.util.*;
import com.dxhy.common.utils.DateUtils;
import com.dxhy.common.utils.LocalTrmSeqNum;
import com.dxhy.jxpt.baseService.sign.dao.SignCheckLogDao;
import com.dxhy.jxpt.baseService.sign.service.elec.SignElecInvoiceService;
import com.dxhy.jxpt.baseService.sign.service.elec.SignInvoiceImgService;
import com.dxhy.jxpt.baseService.sign.service.invoicequery.SignInvoiceQueryService;
import com.dxhy.jxpt.baseService.sign.service.openservice.IOpenServicePlatformService;
import com.dxhy.jxpt.baseService.sign.service.singletable.SignCheckRecordService;
import com.dxhy.jxpt.baseService.sign.service.singletable.SignSaveCheckInfoService;
import com.dxhy.jxpt.baseService.sign.service.singletable.SignScanInvoiceLogService;
import com.dxhy.jxpt.baseService.util.FpzlChangeUtil;
import com.dxhy.jxpt.baseService.util.InvoiceQueryUtil;
import com.dxhy.jxpt.baseService.util.XmlUtil;
import com.dxhy.jxptutils.OfdUtils;
import com.dxhy.jxptutils.model.sdxml.EInvoice;
import com.dxhy.jxptutils.model.sdxml.TaxSupervisionInfo.TaxSupervisionInfo;
import com.dxhy.jxptutils.model.sdxml.eInvoiceData.EInvoiceData;
import com.dxhy.model.OfdInvoice;
import com.dxhy.ofd.service.OfdService;
import com.dxhy.oss.model.FileModel;
import com.dxhy.oss.service.FileService;
import com.dxhy.pdf.entity.PdfInvoiceModel;
import com.dxhy.pdf.utils.PdfUtil;
import com.dxhy.utils.FileUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.InputStream;
import java.math.BigDecimal;
import java.nio.file.Files;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author ld
 */
@SuppressWarnings({"AlibabaUndefineMagicConstant", "AlibabaMethodTooLong", "AlibabaStringConcat",
    "AlibabaAvoidComplexCondition", "AlibabaCollectionInitShouldAssignCapacity"})
@Service("signInvoiceQueryService")
@Slf4j
public class SignInvoiceQueryServiceImpl extends MpBaseServiceImpl<SignCheckLogDao, TDxCheckLog>
    implements SignInvoiceQueryService {

    @Resource
    private SignSaveCheckInfoService signSaveCheckInfoService;

    @Resource
    private IOpenServicePlatformService openServicePlatformService;

    @Resource
    private InvoiceQueryUtil invoiceQueryUtil;

    @Resource
    private SignScanInvoiceLogService signScanInvoiceLogService;

    @Resource
    private SignCheckRecordService signCheckRecordService;
    @Resource
    private SignInvoiceImgService signInvoiceImgService;
    @Resource
    private SignElecInvoiceService signElecInvoiceService;
    @Resource
    private OfdService ofdService;
    @Resource
    private ScanIdUtils scanIdUtils;

    @Resource
    private TabulateRedisService tabulateRedisService;
    @Resource
    private FileService fileService;

    /**
     * 下载文件的本地默认存储根路径
     */
    @Value("${ftp.connection.localpathprefix}")
    public String localPathDefault;

    protected final String PDF_SUFFIX = ".pdf";

    @Override
    public JSONObject saveUploadElecFile(List<File> pdffiles, List<File> ofdfiles, List<File> xmlFile, UserInfo userInfo,
                                         String pdfFileName, String tempPath, String saveHistory, String taxNo) {
        JSONObject result;
        // 导入结果返回jsonsetCheckMassege
        String[] titlelist = new String[] {"查验结果描述", "发票代码", "发票号码","数电号码", "开票日期", "购方名称", "销方名称", "金额", "税额", "校验码"};
        String[] titleprop = new String[] {"checkMassege", "invoiceCode", "invoiceNo","eleInvoiceNo", "invoiceDate", "gfmc", "xfmc",
            "invoiceAmount", "taxAmount", "checkCode"};
        result = super.setTitleList(titlelist, titleprop);
        // 返回的list
        List<ElecCheckVO> vos = new ArrayList<>();

        if (pdffiles != null && pdffiles.size() > 0) {

            // 解析并保存电票信息
            vos = this.analysisElectronFile(pdffiles, userInfo, pdfFileName, saveHistory, taxNo);
        }

        if (ofdfiles != null && ofdfiles.size() > 0) {
            List<ElecCheckVO> analysisOfdFile = this.analysisOfdFile(ofdfiles, userInfo, tempPath, saveHistory, taxNo);
            vos.addAll(analysisOfdFile);
        }

        if (xmlFile != null && xmlFile.size() > 0) {
            List<ElecCheckVO> analysisXmlFile = this.analysisXmlFile(xmlFile, userInfo, tempPath, saveHistory, taxNo);
            vos.addAll(analysisXmlFile);
        }

        result.put("datalist", vos);
        //都处理完后，删除临时目录
        FileUtils.deleteDir(new File(tempPath));
        log.debug("电票导入结果：" + result.toJSONString());
        return super.succResult(result);
    }

    /**
    * @Description xml电子源文件查验
    * @param xmlFiles
    * @param user
    * @param tempPath
    * @param saveHistory
    * @param taxNo
    * @Return java.util.List<com.dxhy.api.model.sign.ElecCheckVO>
    * @Author wangruwei
    * @Date 2024/5/11 15:38
    **/
    private List<ElecCheckVO> analysisXmlFile(List<File> xmlFiles, UserInfo user, String tempPath, String saveHistory, String taxNo) {
        List<ElecCheckVO> invoices = new ArrayList<>();
        // 图片存储路径
        String uploadImg = "";
        // 连接远程ftp服务器，上传xml
        PdfInvoiceModel pdfInvoiceModel = new PdfInvoiceModel();
        //如果只有一条，且出错的话，抛出去提示
        try {
            // 连接远程服务器
            for (File file : xmlFiles) {
                // 解析pdf文件中二维码4种信息放进map========@1=========
                String sourceFolder = fileService.getPathPrefix() + "elec/source/"
                        + new SimpleDateFormat("yyyyMMdd").format(new Date()) + "/";
                String pdfFilePath = "";
                String imgFolder = fileService.getPathPrefix() + "elec/image/"
                        + new SimpleDateFormat("yyyyMMdd").format(new Date()) + "/";
                FileModel fileModel;
                // 扫描图片唯一识别id
                String scanId = UUID.randomUUID().toString().replace("-", "");

                Map<String, String> pathMap = new HashMap<>(5);
                pathMap.put("scanId", scanId);

                try {
                    String xmlStr = cn.hutool.core.io.FileUtil.readUtf8String(file);
                    log.info("xml内容为:{}",xmlStr);
                    //如果是 05铁路  06航空。不生成pdf
                    EInvoice allEleInvoice = XmlUtil.xmlToObject(xmlStr, EInvoice.class);
                    String invoiceType = allEleInvoice.getHeader().getInherentLabel().getGeneralOrSpecialVAT().getLabelCode();
                    if("05".equals(invoiceType)||"06".equals(invoiceType)){
                        log.info("数电铁路航空不转图片，直接以xml四要素调开放平台");
                        pathMap.put("path", "");
                        //源文件
                        pathMap.put("sourcePath", sourceFolder + file.getName());
                        saveInvoiceImg(pathMap);
                        //用四要素直接调开放平台
                        ElecCheckVO invoiceEntity = this.getElectronByXml(allEleInvoice, scanId, user);
                        //用xml数据，调开放平台
                        checkKfptAndGetResult(false,invoiceEntity,user,pathMap,saveHistory,taxNo,file,scanId,invoices);
                    }else{
                        //生成PDF文件
                        Map<String, Object> pdfMap = null;
                        try {
                            pdfMap = OfdUtils.xmlToPdf(xmlStr);
                        } catch (Exception e) {
                            log.info("xml转换为pdf失败");
                            log.info("业务处理异常：{}", e);
                        }

                        if (pdfMap != null && pdfMap.get("fileByte") != null) {
                            byte[] data = (byte[]) pdfMap.get("fileByte");
                            InputStream pdfInput = new ByteArrayInputStream(data);
                            String uuid = UUID.randomUUID().toString().replace("-", "");
                            pdfFilePath = tempPath + uuid + cn.hutool.core.io.FileUtil.mainName(file.getName()) + PDF_SUFFIX;
                            cn.hutool.core.io.FileUtil.writeFromStream(pdfInput, new File(pdfFilePath));
                            log.info("pdf文件已生成，位置:{}", pdfFilePath);
                            //解析pdf为结构化数据
                            pdfInvoiceModel = PdfUtil.pdfAnalysis(new File(pdfFilePath));
                            FileModel fileModelPng = fileService.uploadFile(
                                    imgFolder + new File(pdfInvoiceModel.getPngPath()).getName(), pdfInvoiceModel.getPngPath());
                            //图片
                            pathMap.put("path", fileModelPng.getFilePath());
                        }

                        //上传xml源文件
                        fileModel = fileService.uploadFile(sourceFolder + file.getName(), file.getPath());
                        //源文件
                        pathMap.put("sourcePath", fileModel.getFilePath());
                        saveInvoiceImg(pathMap);

                        // 获取解析的发票信息
                        ElecCheckVO invoiceEntity = this.getElectronInvoice(pdfInvoiceModel, scanId, user);
                        //用解析pdf后的数据，调开放平台
                        checkKfptAndGetResult(true,invoiceEntity,user,pathMap,saveHistory,taxNo,file,scanId,invoices);
                    }

                } catch (Exception e) {
                    log.info("处理发票解析失败:{}",e);
                    pathMap.put("path", "");
                    // 处理发票解析失败
                    ElecCheckVO expectionPdf = new ElecCheckVO();
                    expectionPdf.setPdfName(file.getName());
                    //expectionPdf.setFilePath(file.getPath());
                    //expectionPdf.setFileParentPath(file.getParent());
                    expectionPdf.setReadPdfSuccess(false);
                    expectionPdf.setReadPdfSuccessDesc(file.getName()+"解析发票失败");
                    expectionPdf.setCompany(user.getCompany());
                    //失败的不返回
                    invoices.add(expectionPdf);
                    continue;
                }finally {
                    if(StringUtils.isNotBlank(pdfFilePath)){
                        log.info("删除文件:{}",pdfFilePath);
                        FileUtil.deleteFile(pdfFilePath);
                    }
                }
            }
        } catch (Exception e) {
            log.info("业务处理异常：{}", e);
            log.debug("-----------------上传xml异常------------------");
        }
        return invoices;
    }

    /**
    * @Description 调开放平台，并处理返回结果
    * @param
    * @param isCreatePic 数电铁路航空不生成，其他生成
     * @param invoiceEntity
     * @param user
     * @param pathMap
     * @param saveHistory
     * @param taxNo
     * @param file
     * @param scanId
     * @param invoices
     * @Return void
    * @Author wangruwei
    * @Date 2024/5/22 16:39
    **/
    private void checkKfptAndGetResult(boolean isCreatePic, ElecCheckVO invoiceEntity, UserInfo user, Map<String, String> pathMap, String saveHistory, String taxNo, File file, String scanId, List<ElecCheckVO> invoices) {
        Map<String,Object> notes = checkingInvoiceInfo(user.getDbName(),
                invoiceEntity.getInvoiceCode() + invoiceEntity.getInvoiceNo(), user);
        if (notes.get("notes") != null) {
            invoiceEntity.setCheckMassege(notes.get("notes").toString());
            invoiceEntity.setEditState(true);
            invoiceEntity.setDelState(true);
            if("31".equals(invoiceEntity.getInvoiceType())){
                invoiceEntity.setInvoiceAmount("");
            }
            //重置代码号码，数电号码
            resetInvoiceCodeNo(invoiceEntity,notes);
        }else{
            log.info("调开放平台查验发票");
            //开放平台
            OpenServiceSingleInvoiceCheckRequest req = new OpenServiceSingleInvoiceCheckRequest();
            req.setFpdm(invoiceEntity.getInvoiceCode());
            req.setFphm(invoiceEntity.getInvoiceNo());
            req.setFpje(invoiceEntity.getTotalAmount());
            req.setJym(invoiceEntity.getCheckCode());
            req.setKprq(invoiceEntity.getInvoiceDate().replace("-", ""));
            req.setFpzl(invoiceEntity.getInvoiceType());
            try {
                OpenServiceSingleInvoiceCheckJxpt checkData = openServicePlatformService.checkSingleInvoice(req);
                pathMap.put("invoiceType", invoiceEntity.getInvoiceType());
                pathMap.put("invoiceCode", invoiceEntity.getInvoiceCode());
                pathMap.put("invoiceNo", invoiceEntity.getInvoiceNo());
                pathMap.put("invoiceDate", invoiceEntity.getInvoiceDate());
                pathMap.put("invoiceAmount", invoiceEntity.getInvoiceAmount());
                if("31".equals(invoiceEntity.getInvoiceType())&&invoiceEntity.getInvoiceNo().length()==20){
                    if(StringUtils.isNotEmpty(invoiceEntity.getTotalAmount())){
                        pathMap.put("invoiceAmount", invoiceEntity.getTotalAmount());
                    }
                }
                pathMap.put("checkCode", invoiceEntity.getCheckCode());
                pathMap.put("saveHistory", saveHistory);
                pathMap.put("dbName", user.getDbName());
                pathMap.put("company", user.getCompany());
                pathMap.put("taxNo", taxNo);
                pathMap.put("userid", user.getLoginname());
                //保存查验记录表t_dx_check_log,记录查验表 t_dx_check_record_invoice
                TDxCheckLog checkLog = saveCheckRecordInvoice(pathMap,checkData);

                //重置代码号码数电号码，发票种类
                invoiceEntity.setInvoiceCode(checkLog.getInvoiceCode());
                invoiceEntity.setInvoiceNo(checkLog.getInvoiceNo());
                invoiceEntity.setEleInvoiceNo(checkLog.getEleInvoiceNo());
                //如果是09，赋值31。否则，用查验回来的返回
                if("09".equals(checkLog.getInvoiceType())){
                    invoiceEntity.setInvoiceType("31");
                }else{
                    invoiceEntity.setInvoiceType(checkLog.getInvoiceType());
                }
                invoiceEntity.setInvoiceDate(DateUtils.strToStrDate(invoiceEntity.getInvoiceDate()));
                invoiceEntity.setXfmc(checkData.getXhfmc());
                invoiceEntity.setGfmc(checkData.getGmfmc());
                invoiceEntity.setCheckMassege(checkLog.getCheckMassege());
                invoiceEntity.setInvoiceAmount(AmountFormatUtil.fmtMicrometer2(checkData.getFpje()));
                invoiceEntity.setTaxAmount(AmountFormatUtil.fmtMicrometer2(checkData.getFpse()));

                boolean detailFlag = true;
                boolean editState = true;
                boolean delState = true;
                if ("0001".equals(checkLog.getHandleCode())) {
                    editState = false;
                    delState = false;
                } else {
                    detailFlag = false;
                }
                invoiceEntity.setDetailState(detailFlag);
                invoiceEntity.setEditState(editState);
                invoiceEntity.setDelState(delState);
            } catch (OpenServiceInvokeException e) {
                log.info("调开放平台查验出错:{}",e);
            }
        }

        invoiceEntity.setReadPdfSuccess(true);
        invoiceEntity.setReadPdfSuccessDesc(file.getName()+"解析xml成功");
        // 设置序列号
        invoiceEntity.setScanId(scanId);

        invoiceEntity.setPdfName(file.getName());
        invoiceEntity.setImgState(isCreatePic);

        //invoiceEntity.setFilePath(file.getPath());
        //invoiceEntity.setFileParentPath(file.getParent());
        invoices.add(invoiceEntity);
    }

    /**
    * @Description 通过xml转换的数据体设置为展示数据体
    * @param allEleInvoice
    * @param scanId
    * @param user
    * @Return com.dxhy.api.model.sign.ElecCheckVO
    * @Author wangruwei
    * @Date 2024/5/22 16:58
    **/
    private ElecCheckVO getElectronByXml(EInvoice allEleInvoice, String scanId, UserInfo user) {
        ElecCheckVO invoiceEntity = new ElecCheckVO();
        TaxSupervisionInfo taxSupervisionInfo = allEleInvoice.getTaxSupervisionInfo();
        EInvoiceData eInvoiceData = allEleInvoice.getEInvoiceData();
        //invoiceEntity.setId(model.getInvoiceCode() + "_" + model.getInvoiceNo());
        invoiceEntity.setId("" + "_" + taxSupervisionInfo.getInvoiceNumber());
        String userAccount = user.getId();
        String userName = user.getUsername();
        String issueTime = taxSupervisionInfo.getIssueTime();
        if(issueTime.length()>=10){
            invoiceEntity.setInvoiceDate(taxSupervisionInfo.getIssueTime().substring(0,10).replace("-", ""));
        }else{
            invoiceEntity.setInvoiceDate(eInvoiceData.getBasicInformation().getRequestTime().replace("-", ""));
        }
        invoiceEntity.setInvoiceCode("");
        invoiceEntity.setInvoiceNo(taxSupervisionInfo.getInvoiceNumber());
        invoiceEntity.setUuid(taxSupervisionInfo.getInvoiceNumber());
        invoiceEntity.setScanId(scanId);
        invoiceEntity.setUserAccount(userAccount);
        invoiceEntity.setUserName(userName);
        invoiceEntity.setCreateDate(DateTime.now().toDate());
        invoiceEntity.setUpdateDate(DateTime.now().toDate());
        //invoiceEntity.setCheckCode(model.getCheckCode());
        invoiceEntity.setInvoiceAmount(eInvoiceData.getBasicInformation().getTotalAmWithoutTax());
        invoiceEntity.setTotalAmount(eInvoiceData.getBasicInformation().getTotalTaxIncludedAmount());
        return invoiceEntity;
    }


    private List<ElecCheckVO> analysisOfdFile(List<File> files, UserInfo user, String tempPath, String saveHistory,
        String taxNo) {

        List<ElecCheckVO> invoices = new ArrayList<>();
        try {

            String sourceFolder = fileService.getPathPrefix() + "elec/source/"
                + new SimpleDateFormat("yyyyMMdd").format(new Date()) + "/";
            String imgFolder =
                fileService.getPathPrefix() + "elec/image/" + new SimpleDateFormat("yyyyMMdd").format(new Date()) + "/";
            for (File file : files) {
                String fileName = file.getName();
                String name = fileName.substring(0, fileName.length() - 4);
                String userAccount = user.getId();
                String userName = user.getUsername();
                String scanId = UUID.randomUUID().toString().replace("-", "");
                String ofdTempPath = tempPath + name + "/";
                signElecInvoiceService.createFileDir(ofdTempPath);
                Files.copy(file.toPath(), new File(ofdTempPath + name + "_" + scanId + ".ofd").toPath());
                // 上传保存源文件
                String pushName = name + "_" + scanId + ".ofd";
                FileModel fileModel = fileService.uploadFile(sourceFolder + pushName, file.getPath());
                // ofd解析发票
                OfdInvoice ofdInvoice =
                    ofdService.ofdAnalysis(FileUtils.findFile(ofdTempPath, "ofd").get(0), false, false, false);
                signElecInvoiceService.createFileDir(tempPath.substring(0, tempPath.lastIndexOf("/")) + "_photo/");
                String photoPath =
                    tempPath.substring(0, tempPath.lastIndexOf("/")) + "_photo/" + name + "_" + scanId + ".png";
                Files.copy(new File(ofdInvoice.getPngPath()).toPath(), new File(photoPath).toPath());
                // 上传图片
                FileModel fileModelPng = fileService.uploadFile(imgFolder + new File(photoPath).getName(), photoPath);
                // 获取解析的发票信息
                ElecCheckVO invoiceEntity = new ElecCheckVO();
                String checkCode = ofdInvoice.getInvoiceCheckCode();

                Map<String, String> pathMap = new HashMap<>(5);
                pathMap.put("scanId", scanId);
                pathMap.put("path", fileModelPng.getFilePath());
                pathMap.put("sourcePath", fileModel.getFilePath());
                DynamicContextHolder.push(user.getDbName() + DbConstant.BUSINESS_WRITE);
                saveInvoiceImg(pathMap);
                invoiceEntity.setId(ofdInvoice.getInvoiceCode() + "_" + ofdInvoice.getInvoiceNo());
                invoiceEntity.setInvoiceDate(DateUtils.strToStrDate2(ofdInvoice.getIssueDate()));
                invoiceEntity.setInvoiceCode(ofdInvoice.getInvoiceCode());
                invoiceEntity.setInvoiceNo(ofdInvoice.getInvoiceNo());
                invoiceEntity.setUuid(ofdInvoice.getInvoiceCode() + ofdInvoice.getInvoiceNo());
                invoiceEntity.setScanId(scanId);
                invoiceEntity.setUserAccount(userAccount);
                invoiceEntity.setUserName(userName);
                invoiceEntity.setCreateDate(DateTime.now().toDate());
                invoiceEntity.setUpdateDate(DateTime.now().toDate());
                invoiceEntity.setInvoiceAmount(ofdInvoice.getTaxExclusiveTotalAmount());
                invoiceEntity.setTotalAmount(ofdInvoice.getTaxInclusiveTotalAmount());
                if (org.apache.commons.lang.StringUtils.isNotBlank(checkCode)) {
                    invoiceEntity.setCheckCode(checkCode.substring(checkCode.length() - 6));
                } else {
                    invoiceEntity.setCheckCode(null);
                }
                SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
                SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");
                String invoiceDate = "";
                try {
                    invoiceDate = invoiceEntity.getInvoiceDate();
                } catch (Exception e) {
                    invoiceDate = invoiceEntity.getInvoiceDate();
                }
                invoiceEntity.setInvoiceDate(invoiceDate);
                invoiceEntity.setCompany(user.getCompany());
                invoiceEntity.setLocalTrmSeqNum(LocalTrmSeqNum.getLocalTrmSeqNum());
                // 设置序列号
                invoiceEntity.setScanId(scanId);
                InvoiceUtil iu = new InvoiceUtil(invoiceEntity.getInvoiceCode());
                String fpType = iu.getFplxdm();
                if (fpType != null) {

                    invoiceEntity.setInvoiceType(fpType);
                } else {
                    invoiceEntity.setInvoiceType("10");
                }
                if("09".equals(ofdInvoice.getInvoiceType())){
                    invoiceEntity.setInvoiceType("31");
                }
                invoiceEntity.setReadPdfSuccess(true);
                Map<String,Object> notes = checkingInvoiceInfo(user.getDbName(),
                    invoiceEntity.getInvoiceCode() + invoiceEntity.getInvoiceNo(), user);
                if (notes.get("notes") != null) {
                    invoiceEntity.setCheckMassege(notes.get("notes").toString());
                    invoiceEntity.setEditState(true);
                    invoiceEntity.setDelState(true);
                    if("31".equals(invoiceEntity.getInvoiceType())){
                        invoiceEntity.setInvoiceAmount("");
                    }
                    //重置代码号码，数电号码
                    resetInvoiceCodeNo(invoiceEntity,notes);
                } else {
                    pathMap.put("invoiceType", invoiceEntity.getInvoiceType());
                    pathMap.put("invoiceCode", invoiceEntity.getInvoiceCode());
                    pathMap.put("invoiceNo", invoiceEntity.getInvoiceNo());
                    pathMap.put("invoiceDate", invoiceEntity.getInvoiceDate());
                    pathMap.put("invoiceAmount", invoiceEntity.getInvoiceAmount());
                    if("31".equals(invoiceEntity.getInvoiceType())&&invoiceEntity.getInvoiceNo().length()==20){
                        if(StringUtils.isNotEmpty(invoiceEntity.getTotalAmount())){
                            pathMap.put("invoiceAmount", invoiceEntity.getTotalAmount());
                        }
                    }
                    pathMap.put("checkCode", invoiceEntity.getCheckCode());
                    pathMap.put("saveHistory", saveHistory);
                    pathMap.put("dbName", user.getDbName());
                    pathMap.put("company", user.getCompany());
                    pathMap.put("taxNo", taxNo);
                    pathMap.put("userid", user.getLoginname());
                    TDxCheckLog checkLog = new TDxCheckLog();
                    if(true){
                        //开放平台查验接口
                        if(true){
                            //开放平台
                            OpenServiceSingleInvoiceCheckRequest req = new OpenServiceSingleInvoiceCheckRequest();
                            req.setFpdm(pathMap.get("invoiceCode"));
                            req.setFphm(pathMap.get("invoiceNo"));
                            req.setFpje(pathMap.get("invoiceAmount"));
                            req.setJym(pathMap.get("checkCode"));
                            req.setKprq(pathMap.get("invoiceDate"));
                            req.setFpzl(pathMap.get("invoiceType"));
                            try {
                                OpenServiceSingleInvoiceCheckJxpt checkData = openServicePlatformService.checkSingleInvoice(req);
                                //保存查验记录表t_dx_check_log,记录查验表 t_dx_check_record_invoice
                                checkLog = saveCheckRecordInvoice(pathMap,checkData);
                            } catch (OpenServiceInvokeException e) {
                                log.info("调开放平台查验出错:{}",e);
                            }
                        }
                    }else{
                        //大企业查验 7.1.2需求 2024年5月9日18:24:35 发票查验目录下所有菜单不用大企业查验，后续看需求
                        checkLog = this.checkSingleInvioce(pathMap);
                    }

                    invoiceEntity.setCheckMassege(checkLog.getCheckMassege());
                    if (checkLog.getInvoiceAmount() != null) {
                        invoiceEntity.setInvoiceAmount(AmountFormatUtil
                            .fmtMicrometer(MathUtil.round(checkLog.getInvoiceAmount().toPlainString())));
                    } else {
                        invoiceEntity.setInvoiceAmount("");
                    }
                    if (checkLog.getTaxAmount() != null) {
                        invoiceEntity.setTaxAmount(
                            AmountFormatUtil.fmtMicrometer(MathUtil.round(checkLog.getTaxAmount().toPlainString())));
                    } else {
                        invoiceEntity.setTaxAmount("");
                    }
                    if (StringUtils.isNoneBlank(checkLog.getCheckCode())) {
                        invoiceEntity.setCheckCode(checkLog.getCheckCode());
                    } else {
                        invoiceEntity.setCheckCode("");
                    }
                    if (StringUtils.isNoneBlank(checkLog.getBuyerName())) {
                        invoiceEntity.setGfmc(checkLog.getBuyerName());
                    } else {
                        invoiceEntity.setGfmc("");
                    }
                    if (StringUtils.isNoneBlank(checkLog.getSalerName())) {
                        invoiceEntity.setXfmc(checkLog.getSalerName());
                    } else {
                        invoiceEntity.setXfmc("");
                    }

                    //重置代码号码数电号码，发票种类
                    invoiceEntity.setInvoiceCode(checkLog.getInvoiceCode());
                    invoiceEntity.setInvoiceNo(checkLog.getInvoiceNo());
                    invoiceEntity.setEleInvoiceNo(checkLog.getEleInvoiceNo());
                    //如果是09，赋值31。否则，用查验回来的返回
                    if("09".equals(checkLog.getInvoiceType())){
                        invoiceEntity.setInvoiceType("31");
                    }else{
                        invoiceEntity.setInvoiceType(checkLog.getInvoiceType());
                    }
                    //查验需要时间是yyyyMMdd。返回前端再返回去
                    invoiceEntity.setInvoiceDate(DateUtils.strToStrDate(invoiceDate));

                    invoiceEntity.setHandleCode(checkLog.getHandleCode());
                    boolean detailFlag = true;
                    boolean editState = true;
                    boolean delState = true;
                    if ("0001".equals(checkLog.getHandleCode())) {
                        editState = false;
                        delState = false;
                    } else {
                        detailFlag = false;
                    }
                    invoiceEntity.setDetailState(detailFlag);
                    invoiceEntity.setEditState(editState);
                    invoiceEntity.setDelState(delState);
                }

                invoiceEntity.setReadPdfSuccessDesc("解析ofd成功");
                invoiceEntity.setPdfName(fileName);
                invoiceEntity.setImgState(true);
                invoices.add(invoiceEntity);

                // 删除临时文件
                FileUtils.deleteDir(file);
            }
        } catch (Exception e) {
           log.info("业务处理异常：{}", e);
        }
        return invoices;
    }

    /**
     * 解析上传的电票文件  pdf
     *
     * @param files
     *            电票文件
     * @param user
     *            当前登录人信息
     * @param pdfFileName
     *            当用户上传pdf文件的名称
     */

    private List<ElecCheckVO> analysisElectronFile(List<File> files, UserInfo user, String pdfFileName,
        String saveHistory, String taxNo) {
        List<ElecCheckVO> invoices = new ArrayList<>();
        // 存放文件解析的数据
        // Map<String, Object> erWeiMaInfomap = null;
        // 图片存储路径
        String uploadImg = "";
        // 连接远程ftp服务器，上传电票图片
        PdfInvoiceModel pdfInvoiceModel;
        try {
            // 连接远程服务器
            for (File file : files) {
                // 解析pdf文件中二维码4种信息放进map========@1=========
                String sourceFolder = fileService.getPathPrefix() + "elec/source/"
                    + new SimpleDateFormat("yyyyMMdd").format(new Date()) + "/";
                String imgFolder = fileService.getPathPrefix() + "elec/image/"
                    + new SimpleDateFormat("yyyyMMdd").format(new Date()) + "/";
                FileModel fileModel;
                try {

                    pdfInvoiceModel = PdfUtil.pdfAnalysis(file);

                    fileModel = fileService.uploadFile(sourceFolder + file.getName(), file.getPath());

                    if (pdfInvoiceModel == null) {
                        // 处理发票解析失败
                        ElecCheckVO expectionPdf = new ElecCheckVO();
                        if (pdfFileName.endsWith("pdf")) {
                            expectionPdf.setPdfName(pdfFileName);
                        }
                        expectionPdf.setReadPdfSuccess(false);
                        expectionPdf.setReadPdfSuccessDesc("解析发票失败");
                        invoices.add(expectionPdf);
                        continue;
                    }
                } catch (Exception e) {
                    log.info("发票解析失败,{}",e);
                    // 处理发票解析失败
                    ElecCheckVO expectionPdf = new ElecCheckVO();
                    if (pdfFileName.endsWith("pdf")) {
                        expectionPdf.setPdfName(pdfFileName);
                    }
                    expectionPdf.setReadPdfSuccess(false);
                    expectionPdf.setReadPdfSuccessDesc("解析发票失败");
                    expectionPdf.setCompany(user.getCompany());
                    invoices.add(expectionPdf);
                    continue;
                }

                FileModel fileModelPng = fileService.uploadFile(
                    imgFolder + new File(pdfInvoiceModel.getPngPath()).getName(), pdfInvoiceModel.getPngPath());

                // 扫描图片唯一识别id
                String scanId = UUID.randomUUID().toString().replace("-", "");

                Map<String, String> pathMap = new HashMap<>(5);
                pathMap.put("scanId", scanId);
                pathMap.put("path", fileModelPng.getFilePath());
                pathMap.put("sourcePath", fileModel.getFilePath());
                DynamicContextHolder.push(user.getDbName() + DbConstant.BUSINESS_WRITE);
                saveInvoiceImg(pathMap);
                // 获取解析的发票信息
                ElecCheckVO invoiceEntity = this.getElectronInvoice(pdfInvoiceModel, scanId, user);
                // =======================
                // 设置图片上传路径
                invoiceEntity.setPdfName(file.getName());
                invoiceEntity.setImgPath(uploadImg + new File(pdfInvoiceModel.getPngPath()).getName());
                if (pdfFileName.endsWith("pdf")) {
                    invoiceEntity.setPdfName(pdfFileName);
                } else {
                    invoiceEntity.setPdfName(file.getName());
                }
                // =======================
                invoiceEntity.setScanId(scanId);
                invoiceEntity.setCompany(user.getCompany());
                invoiceEntity.setLocalTrmSeqNum(LocalTrmSeqNum.getLocalTrmSeqNum());
                InvoiceUtil iu = new InvoiceUtil(invoiceEntity.getInvoiceCode());
                String fpType = iu.getFplxdm();
                if (fpType != null) {

                    invoiceEntity.setInvoiceType(fpType);
                } else {
                    invoiceEntity.setInvoiceType("10");
                }
                if("09".equals(pdfInvoiceModel.getInvoiceType())){
                    invoiceEntity.setInvoiceType("31");
                }
                SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
                SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");
                String invoiceDate = "";
                try {
                    invoiceDate = sdf1.format(sdf.parse(invoiceEntity.getInvoiceDate()));
                } catch (Exception e) {
                    invoiceDate = invoiceEntity.getInvoiceDate();
                }
                invoiceEntity.setInvoiceDate(invoiceDate);
                invoiceEntity.setReadPdfSuccess(true);
                Map<String,Object> notes = checkingInvoiceInfo(user.getDbName(),
                    invoiceEntity.getInvoiceCode() + invoiceEntity.getInvoiceNo(), user);
                if (notes.get("notes") != null) {
                    invoiceEntity.setCheckMassege(notes.get("notes").toString());
                    invoiceEntity.setEditState(true);
                    invoiceEntity.setDelState(true);
                    if("09".equals(pdfInvoiceModel.getInvoiceType())){
                        invoiceEntity.setInvoiceAmount("");
                    }
                    //重置代码号码，数电号码
                    resetInvoiceCodeNo(invoiceEntity,notes);
                } else {
                    if("09".equals(pdfInvoiceModel.getInvoiceType())){
                        pathMap.put("invoiceType", "31");
                    }else {
                        pathMap.put("invoiceType", fpType);
                    }
                    pathMap.put("invoiceCode", invoiceEntity.getInvoiceCode());
                    pathMap.put("invoiceNo", invoiceEntity.getInvoiceNo());
                    pathMap.put("invoiceDate", invoiceEntity.getInvoiceDate());
                    pathMap.put("invoiceAmount", invoiceEntity.getInvoiceAmount());
                    pathMap.put("checkCode", invoiceEntity.getCheckCode());
                    pathMap.put("saveHistory", saveHistory);
                    pathMap.put("dbName", user.getDbName());
                    pathMap.put("company", user.getCompany());
                    pathMap.put("taxNo", taxNo);
                    pathMap.put("userid", user.getLoginname());
                    log.info("开始调查验接口");
                    TDxCheckLog checkLog = new TDxCheckLog();
                    if(true){
                        //开放平台
                        OpenServiceSingleInvoiceCheckRequest req = new OpenServiceSingleInvoiceCheckRequest();
                        req.setFpdm(invoiceEntity.getInvoiceCode());
                        req.setFphm(invoiceEntity.getInvoiceNo());
                        req.setFpje(invoiceEntity.getInvoiceAmount());
                        req.setJym(invoiceEntity.getCheckCode());
                        req.setKprq(invoiceEntity.getInvoiceDate());
                        req.setFpzl(pathMap.get("invoiceType"));
                        try {
                            OpenServiceSingleInvoiceCheckJxpt checkData = openServicePlatformService.checkSingleInvoice(req);
                            //保存查验记录表t_dx_check_log,记录查验表 t_dx_check_record_invoice
                            checkLog = saveCheckRecordInvoice(pathMap,checkData);
                        } catch (OpenServiceInvokeException e) {
                            log.info("调开放平台查验出错:{}",e);
                        }
                    }else{
                        //大企业查验 7.1.2需求 2024年5月9日18:24:35 发票查验目录下所有菜单不用大企业查验，后续看需求
                        checkLog = this.checkSingleInvioce(pathMap);
                    }

                    invoiceEntity.setCheckMassege(checkLog.getCheckMassege());
                    if (checkLog.getInvoiceAmount() != null) {
                        invoiceEntity.setInvoiceAmount(AmountFormatUtil
                            .fmtMicrometer(MathUtil.round(checkLog.getInvoiceAmount().toPlainString())));
                    } else {
                        invoiceEntity.setInvoiceAmount("");
                    }
                    if (checkLog.getTaxAmount() != null) {
                        invoiceEntity.setTaxAmount(
                            AmountFormatUtil.fmtMicrometer(MathUtil.round(checkLog.getTaxAmount().toPlainString())));
                    } else {
                        invoiceEntity.setTaxAmount("");
                    }
                    if (StringUtils.isNoneBlank(checkLog.getCheckCode())) {
                        invoiceEntity.setCheckCode(checkLog.getCheckCode());
                    } else {
                        invoiceEntity.setCheckCode("");
                    }
                    if (StringUtils.isNoneBlank(checkLog.getBuyerName())) {
                        invoiceEntity.setGfmc(checkLog.getBuyerName());
                    } else {
                        invoiceEntity.setGfmc("");
                    }
                    if (StringUtils.isNoneBlank(checkLog.getSalerName())) {
                        invoiceEntity.setXfmc(checkLog.getSalerName());
                    } else {
                        invoiceEntity.setXfmc("");
                    }
                    invoiceEntity.setHandleCode(checkLog.getHandleCode());
                    boolean detailFlag = true;
                    boolean editState = true;
                    boolean delState = true;
                    if ("0001".equals(checkLog.getHandleCode())) {
                        editState = false;
                        delState = false;
                    } else {
                        detailFlag = false;
                    }
                    //重置代码号码数电号码
                    invoiceEntity.setInvoiceCode(checkLog.getInvoiceCode());
                    invoiceEntity.setInvoiceNo(checkLog.getInvoiceNo());
                    invoiceEntity.setEleInvoiceNo(checkLog.getEleInvoiceNo());
                    //如果是09，赋值31。否则，用查验回来的返回
                    if("09".equals(checkLog.getInvoiceType())){
                        invoiceEntity.setInvoiceType("31");
                    }else{
                        invoiceEntity.setInvoiceType(checkLog.getInvoiceType());
                    }
                    //查验需要时间是yyyyMMdd。返回前端再返回去
                    invoiceEntity.setInvoiceDate(DateUtils.strToStrDate(invoiceDate));

                    invoiceEntity.setDetailState(detailFlag);
                    invoiceEntity.setEditState(editState);
                    invoiceEntity.setDelState(delState);
                    if (checkLog.getTotalAmount() != null) {
                        invoiceEntity.setTotalAmount(
                                AmountFormatUtil.fmtMicrometer(MathUtil.round(checkLog.getTotalAmount().toPlainString())));
                    } else {
                        invoiceEntity.setTotalAmount("");
                    }
                    if(StringUtils.isNotBlank(checkLog.getInvoiceType())){
                        invoiceEntity.setInvoiceType(checkLog.getInvoiceType());
                    }
                }

                invoiceEntity.setReadPdfSuccessDesc("解析pdf成功");
                // 设置序列号
                invoiceEntity.setScanId(scanId);
                if (pdfFileName.endsWith("pdf")) {
                    invoiceEntity.setPdfName(pdfFileName);
                } else {
                    invoiceEntity.setPdfName(file.getName());
                }
                invoiceEntity.setImgState(true);
                invoices.add(invoiceEntity);
                // 删除临时文件
                FileUtils.deleteDir(file);
            }
        } catch (Exception e) {
            log.info("业务处理异常：{}", e);
            log.debug("-----------------上传图片异常------------------");
        }
        return invoices;
    }

    private void resetInvoiceCodeNo(ElecCheckVO invoiceEntity, Map<String, Object> notes) {
        //如果checkRecordInvoice不为空，用checkRecordInvoice的数据。主要有这数据，都是查验成功
        if(notes.get("checkRecordInvoice") != null){
            TDxCheckRecordInvoice checkRecordTmp = (TDxCheckRecordInvoice) notes.get("checkRecordInvoice");
            invoiceEntity.setInvoiceType(checkRecordTmp.getFpzl());
            invoiceEntity.setInvoiceCode(checkRecordTmp.getFpdm());
            invoiceEntity.setInvoiceNo(checkRecordTmp.getFphm());
            invoiceEntity.setEleInvoiceNo(checkRecordTmp.getEleInvoiceNo());
            invoiceEntity.setInvoiceAmount(checkRecordTmp.getJe());
            if(StringUtils.isNotBlank(checkRecordTmp.getKprq())&&checkRecordTmp.getKprq().length()==8){
                invoiceEntity.setInvoiceDate(DateUtils.strToStrDate(checkRecordTmp.getKprq()));
            }
        }else{
            //如果今天没查验成功结果，且是20位发票号码，拆封
            if(invoiceEntity.getInvoiceNo().length()==20){
                invoiceEntity.setEleInvoiceNo(invoiceEntity.getInvoiceNo());
                invoiceEntity.setInvoiceCode(invoiceEntity.getInvoiceNo().substring(0, 12));
                invoiceEntity.setInvoiceNo(invoiceEntity.getInvoiceNo().substring(12, 20));
            }
        }
    }

    private void saveInvoiceImg(Map<String, String> invoiceImgMap) {
        if (invoiceImgMap == null || invoiceImgMap.size() == 0) {
            return;
        }

        TDxInvoiceImg invoiceImg = new TDxInvoiceImg();
        // uuid
        invoiceImg.setScanId(invoiceImgMap.get("scanId"));
        // 图片路径
        invoiceImg.setImagePath(invoiceImgMap.get("path"));
        // 源文件
        invoiceImg.setImage(invoiceImgMap.get("sourcePath"));
        // 是否有效设为有效
        invoiceImg.setValid(ValidEnum.YX.getYxztDm());
        // 创建时间
        invoiceImg.setCreateDate(DateUtils.getSqlDateLong());
        // 更新时间
        invoiceImg.setUpdateDate(DateUtils.getSqlDateLong());

        signInvoiceImgService.insertOrUpdate(invoiceImg);

    }

    private ElecCheckVO getElectronInvoice(PdfInvoiceModel model, String scanId, UserInfo user) {
        ElecCheckVO invoiceEntity = new ElecCheckVO();
        invoiceEntity.setId(model.getInvoiceCode() + "_" + model.getInvoiceNo());
        String userAccount = user.getId();
        String userName = user.getUsername();
        invoiceEntity.setInvoiceDate(model.getInvoiceDate());
        invoiceEntity.setInvoiceCode(model.getInvoiceCode());
        invoiceEntity.setInvoiceNo(model.getInvoiceNo());
        invoiceEntity.setUuid(model.getInvoiceCode() + model.getInvoiceNo());
        invoiceEntity.setScanId(scanId);
        invoiceEntity.setUserAccount(userAccount);
        invoiceEntity.setUserName(userName);
        invoiceEntity.setCreateDate(DateTime.now().toDate());
        invoiceEntity.setUpdateDate(DateTime.now().toDate());
        invoiceEntity.setCheckCode(model.getCheckCode());
        invoiceEntity.setInvoiceAmount(model.getAmount());
        if("09".equals(model.getInvoiceType())){
            invoiceEntity.setTotalAmount(model.getAmount());
        }
        return invoiceEntity;
    }

    private ExtSmycyVO convertMapToElecView(Map<String, String> pramsMap, String xh) {
        String errmsg = pramsMap.get("errmsg");
        String buyerName = pramsMap.get("buyerName");
        String invoiceAmount = pramsMap.get("invoiceAmount");
        String invoiceCode = pramsMap.get("invoiceCode");
        String invoiceDate = pramsMap.get("invoiceDate");
        String invoiceNo = pramsMap.get("invoiceNo");
        String salerName = pramsMap.get("salerName");
        String checkCode = pramsMap.get("checkCode");
        String taxAmount = pramsMap.get("taxAmount");

        ExtSmycyVO smycyVo = new ExtSmycyVO();
        smycyVo.setXh(xh);
        smycyVo.setCheckMassege((StringHelper.isBlank(errmsg)) ? "" : errmsg);
        smycyVo.setGfmc((StringHelper.isBlank(buyerName)) ? "" : buyerName);
        smycyVo.setInvoiceAmount(
            (StringHelper.isBlank(invoiceAmount)) ? "" : AmountFormatUtil.fmtMicrometer(invoiceAmount));
        smycyVo.setInvoiceCode((StringHelper.isBlank(invoiceCode)) ? "" : invoiceCode);
        smycyVo.setInvoiceDate((StringHelper.isBlank(invoiceDate)) ? "" : invoiceDate);
        smycyVo.setInvoiceNo((StringHelper.isBlank(invoiceNo)) ? "" : invoiceNo);
        smycyVo.setXfmc((StringHelper.isBlank(salerName)) ? "" : salerName);
        smycyVo.setCheckCode((StringHelper.isBlank(checkCode)) ? "" : checkCode);
        smycyVo.setTaxAmount((StringHelper.isBlank(taxAmount)) ? "" : AmountFormatUtil.fmtMicrometer(taxAmount));

        InvoiceUtil iu = new InvoiceUtil(invoiceCode);
        String invoiceType = iu.getFplxdm();
        smycyVo.setInvoiceType(invoiceType);

        smycyVo.setHandleCode("2011");
        smycyVo.setDetailFlag(false);
        smycyVo.setEditState(true);
        smycyVo.setDelState(true);
        return smycyVo;
    }

    @Override
    public String smQueryInvoice(Map<String, String> pramsMap) {

        String[] titlelist = {"查验结果描述", "发票代码", "发票号码", "数电号码", "开票日期", "发票金额", "校验码"};
        String[] titleprop =
            {"checkMassege", "invoiceCode", "invoiceNo", "eleInvoiceNo", "invoiceDate", "invoiceAmount", "checkCode", "invoiceType"};
        // 需要设置返回列表标题时调用
        JSONObject json = super.setTitleList(titlelist, titleprop);
        List<ExtSmcyVO> returnList = new ArrayList<>();
        if(true){
            //开放平台
            OpenServiceSingleInvoiceCheckRequest req = new OpenServiceSingleInvoiceCheckRequest();
            req.setFpdm(pramsMap.get("invoiceCode"));
            req.setFphm(pramsMap.get("invoiceNo"));
            req.setFpje(pramsMap.get("invoiceAmount"));
            req.setJym(pramsMap.get("checkCode"));
            req.setKprq(pramsMap.get("invoiceDate"));
            req.setFpzl(pramsMap.get("invoiceType"));
            try {
                OpenServiceSingleInvoiceCheckJxpt checkData = openServicePlatformService.checkSingleInvoice(req);
                //保存查验记录表t_dx_check_log,记录查验表 t_dx_check_record_invoice
                TDxCheckLog checkLog = saveCheckRecordInvoice(pramsMap,checkData);
                //组织前端展示的方法
                ExtSmcyVO smcyVo = this.convertToSmcyViewKfpt(checkLog);
                returnList.add(smcyVo);
            } catch (OpenServiceInvokeException e) {
                log.info("调开放平台查验出错:{}",e);
            }
        }else{
            //大企业查验 7.1.2需求 2024年5月9日18:24:35 发票查验目录下所有菜单不用大企业查验，后续看需求
            TDxCheckLog checkLog = this.checkSingleInvioce(pramsMap);
            ExtSmcyVO smcyVo = this.convertToSmcyView(checkLog);
            returnList.add(smcyVo);
        }



        json.put("datalist", returnList);

        return super.responseResult(json);
    }
    /**
    * @Description 保存查验记录，开放平台查验
    * @param
    * @param pramsMap       页面发起的请求参数
     * @param checkData     查验返回的数据实体
     * @Return void
    * @Author wangruwei
    * @Date 2024/5/9 11:30
    **/
    private TDxCheckLog saveCheckRecordInvoice(Map<String, String> pramsMap, OpenServiceSingleInvoiceCheckJxpt checkData) {

        TDxCheckLog checkLog = new TDxCheckLog();

        String userId = pramsMap.get("userid");
        String invoiceType = pramsMap.get("invoiceType");
        String invoiceCode = pramsMap.get("invoiceCode");
        checkLog.setXdpbz(checkData.getXdpbz());
        if(StringUtils.isNotBlank(checkData.getJym())){
            checkLog.setCheckCode(checkData.getJym());
        }
        if (StringHelper.isBlank(invoiceType)) {
            if(FplxEnum.QDZZP.getFplxDm().equals(invoiceType) || FplxEnum.QDPP.getFplxDm().equals(invoiceType)){
                invoiceType = "31";
            }else {
                InvoiceUtil iu = new InvoiceUtil(invoiceCode);
                invoiceType = iu.getFplxdm();
            }
        }

        // 通行费发票二维码中的发票类型代码为10“电子发票”，需要单独根据发票代码判断发票类型
        if (FplxEnum.DZP.getFplxDm().equals(invoiceType)) {
            InvoiceUtil iu = new InvoiceUtil(invoiceCode);
            if (FplxEnum.TXF.getFplxDm().equals(iu.getFplxdm())) {
                invoiceType = FplxEnum.TXF.getFplxDm();
            }
        }
        String invoiceNo = pramsMap.get("invoiceNo");
        String invoiceDate = pramsMap.get("invoiceDate");
        String invoiceAmount = pramsMap.getOrDefault("invoiceAmount", "");
        String taxAmount = pramsMap.getOrDefault("taxAmount", "");
        String checkCode = pramsMap.getOrDefault("checkCode", "");
        String gfmc = pramsMap.getOrDefault("gfmc", "");
        String xfmc = pramsMap.getOrDefault("xfmc", "");
        String saveHistory = pramsMap.getOrDefault("saveHistory", "");
        String taxNo = pramsMap.getOrDefault("taxNo", "");
        String company = pramsMap.get("company");
        checkLog.setCheckUser(userId);
        if(FplxEnum.QDZZP.getFplxDm().equals(invoiceType) || FplxEnum.QDPP.getFplxDm().equals(invoiceType)){
            checkLog.setInvoiceType(pramsMap.get("invoiceType"));
            if (!StringHelper.isBlank(invoiceAmount)) {
                try {
                    checkLog.setTotalAmount(BigDecimal.valueOf(new DecimalFormat().parse(invoiceAmount).doubleValue()));
                    checkLog.setInvoiceAmount(null);
                } catch (Exception e) {
                    checkLog.setTotalAmount(new BigDecimal("0"));
                }
            }
        }else {
            if (!StringHelper.isBlank(invoiceAmount)) {
                try {
                    checkLog.setInvoiceAmount(BigDecimal.valueOf(new DecimalFormat().parse(invoiceAmount).doubleValue()));
                } catch (Exception e) {
                    checkLog.setInvoiceAmount(new BigDecimal("0"));
                }
            }
            checkLog.setInvoiceCode(invoiceCode);
            checkLog.setInvoiceType(invoiceType);
        }

        checkLog.setInvoiceNo(invoiceNo);

        if (!StringHelper.isBlank(invoiceDate)) {
            checkLog.setInvoiceDate(DateUtils.strToDate(invoiceDate));
        }
        checkLog.setHandleDate(DateUtils.getSqlDateLong());

        if (!StringHelper.isBlank(taxAmount)) {
            try {
                checkLog.setTaxAmount(BigDecimal.valueOf(new DecimalFormat().parse(taxAmount).doubleValue()));
            } catch (Exception e) {
                checkLog.setTaxAmount(new BigDecimal("0"));
            }
        }
        if (!StringHelper.isBlank(checkCode)) {
            checkLog.setCheckCode(checkCode);
        }
        checkLog.setBuyerName(gfmc);
        checkLog.setSalerName(xfmc);
        checkLog.setUuid((StringUtils.isBlank(checkLog.getInvoiceCode())?"":checkLog.getInvoiceCode())+checkLog.getInvoiceNo());

        //JSONObject queryInvoiceResult =
        //        invoiceQueryUtil.queryInvoice(invoiceCode, invoiceNo, invoiceDate, invoiceAmount, checkCode, taxNo,invoiceType);
        if (!"0001".equals(checkData.getCyjg())) {
            // 查验出错
            checkLog.setHandleCode(checkData.getCyjg());
            checkLog.setCheckMassege(checkData.getCyjgxx());
            //只要查验失败，而且发票号码是20位，就设置为31
            if(invoiceNo.length()==20){
                checkLog.setInvoiceType("31");
            }
            if ("Y".equals(saveHistory)) {
                log.info("查验返回代码:{}。返回信息:{}。保存查验主表", checkData.getCyjg(),checkData.getCyjgxx());
                TDxCheckRecordInvoice checkRecordInvoice = new TDxCheckRecordInvoice();
                checkRecordInvoice.setScanId(pramsMap.get("scanId"));
                checkRecordInvoice.setUuid((StringUtils.isBlank(invoiceCode)?"":invoiceCode) + invoiceNo);
                checkRecordInvoice.setCheckUser(userId);
                checkRecordInvoice.setFphm(invoiceNo);
                checkRecordInvoice.setFpzl(invoiceType);
                checkRecordInvoice.setCompany(pramsMap.get("company"));
                if (!StringHelper.isBlank(invoiceDate)) {
                    if(invoiceDate.length()==10){
                        checkRecordInvoice.setKprq(DateUtils.strToStrDate2(invoiceDate));
                    }else{
                        checkRecordInvoice.setKprq(invoiceDate);
                    }
                }
                if(FplxEnum.QDZZP.getFplxDm().equals(invoiceType) || FplxEnum.QDPP.getFplxDm().equals(invoiceType)){
                    if (!StringHelper.isBlank(invoiceAmount)) {
                        checkRecordInvoice.setJshj(invoiceAmount);
                    }
                }else {
                    checkRecordInvoice.setFpdm(invoiceCode);
                    if (!StringHelper.isBlank(invoiceAmount)) {
                        checkRecordInvoice.setJe(invoiceAmount);
                    }
                }
                //如果号码是20位，代码号码拆开
                if(invoiceNo.length()==20){
                    checkRecordInvoice.setFpdm(invoiceNo.substring(0, 12));
                    checkRecordInvoice.setFphm(invoiceNo.substring(12, 20));
                    checkRecordInvoice.setEleInvoiceNo(invoiceNo);

                    //checkLog同样处理
                    checkLog.setInvoiceCode(invoiceNo.substring(0, 12));
                    checkLog.setInvoiceNo(invoiceNo.substring(12, 20));
                    checkLog.setEleInvoiceNo(invoiceNo);
                }

                if (!StringHelper.isBlank(taxAmount)) {
                    checkRecordInvoice.setSe(taxAmount);
                }
                if (!StringHelper.isBlank(checkCode)) {
                    checkRecordInvoice.setJym(checkCode);
                }
                checkRecordInvoice.setPdfMd5(Long.valueOf(scanIdUtils.createSerialNum()));
                checkRecordInvoice.setCreateDate(DateUtils.getSqlDateLong());
                checkRecordInvoice.setCyjgCode(checkData.getCyjg());
                checkRecordInvoice.setCyjgTip(checkData.getCyjgxx());
                signCheckRecordService.saveCheckRecordInvoice(checkRecordInvoice, pramsMap.get("dbName"));
            }
        } else {
            // 查验成功
            if ("Y".equals(saveHistory)) {
                log.info("开放平台查验调用，保存查验记录");
                signSaveCheckInfoService.saveCheckInfoKfpt(checkData, pramsMap.get("userid"),
                        pramsMap.get("dbName"),pramsMap.get("scanId"),pramsMap.get("company"));
                if(StringUtils.isNotBlank(checkData.getFpzl())){
                    checkLog.setInvoiceType(checkData.getFpzl());
                }
            }
            //查验成功，重置代码号码数电号码为查验回来的
            checkLog.setInvoiceCode(checkData.getFpdm());
            checkLog.setInvoiceNo(checkData.getFphm());
            checkLog.setEleInvoiceNo(checkData.getEleInvoiceNo());

            checkLog.setHandleCode(checkData.getCyjg());
            checkLog.setCheckMassege(checkData.getCyjgxx());
            try {
                checkLog.setTaxAmount(new BigDecimal(checkData.getFpse()));
            } catch (Exception e) {
                checkLog.setTaxAmount(new BigDecimal(0));
            }
            try {
                checkLog.setTotalAmount(new BigDecimal(checkData.getJshj()));
            } catch (Exception e) {
                checkLog.setTotalAmount(new BigDecimal(0));
            }
            try {
                if (FplxEnum.ESC.getFplxDm().equals(invoiceType)) {
                    checkLog.setInvoiceAmount(new BigDecimal(checkData.getCjhj()));
                } else {
                    checkLog.setInvoiceAmount(new BigDecimal(checkData.getFpje()));
                }
            } catch (Exception e) {
                checkLog.setInvoiceAmount(new BigDecimal(0));
            }
            checkLog.setBuyerName(checkData.getGmfmc());
            checkLog.setSalerName(checkData.getXhfmc());
            if(FplxEnum.ESC.getFplxDm().equals(invoiceType)){
                checkLog.setBuyerName(checkData.getMfdwgr());
                checkLog.setSalerName(checkData.getSmfdwgr());
            }
        }
        // 查验调用，保存查验日志
        if ("Y".equals(saveHistory)) {
            DynamicContextHolder.push(pramsMap.get("dbName") + DbConstant.BUSINESS_WRITE);
            super.save(checkLog);
        }

        return checkLog;
    }

    /**
    * @Description 开放平台返回结果组装扫码查验显示数据
    * @param checkLog
    * @Return com.dxhy.api.model.sign.ExtSmcyVO
    * @Author wangruwei
    * @Date 2024/5/8 11:31
    **/
    private ExtSmcyVO convertToSmcyViewKfpt(TDxCheckLog checkLog) {
        ExtSmcyVO smcyVo = new ExtSmcyVO();
        String id = checkLog.getInvoiceCode() + "-" + checkLog.getInvoiceNo();
        smcyVo.setId(id);
        smcyVo.setCheckMassege(checkLog.getCheckMassege());
        smcyVo.setInvoiceCode(checkLog.getInvoiceCode());
        smcyVo.setInvoiceNo(checkLog.getInvoiceNo());
        smcyVo.setEleInvoiceNo(checkLog.getEleInvoiceNo());
        //如果返回的号码是20位，拆分代码号码重新赋值
        if(checkLog.getInvoiceNo().length()==20){
            smcyVo.setInvoiceCode(checkLog.getInvoiceNo().substring(0, 12));
            smcyVo.setInvoiceNo(checkLog.getInvoiceNo().substring(12, 20));
        }
        if (checkLog.getInvoiceDate() != null) {
            smcyVo.setInvoiceDate(DateUtils.dateToStr(checkLog.getInvoiceDate(),"yyyy-MM-dd"));
        }
        if (checkLog.getTotalAmount()!= null) {
            smcyVo.setTotalAmount(
                    AmountFormatUtil.fmtMicrometer(MathUtil.round(checkLog.getTotalAmount().toPlainString())));
        }else {
            smcyVo.setTotalAmount("");
        }
        if (checkLog.getInvoiceAmount() != null) {
            smcyVo.setInvoiceAmount(
                    AmountFormatUtil.fmtMicrometer(MathUtil.round(checkLog.getInvoiceAmount().toPlainString())));
        } else {
            smcyVo.setInvoiceAmount("");
        }

        if (checkLog.getCheckCode() != null) {
            smcyVo.setCheckCode(checkLog.getCheckCode());
        } else {
            smcyVo.setCheckCode("");
        }
        smcyVo.setInvoiceType(FpzlChangeUtil.getInvoiceTypeKfptToJxpt(checkLog.getInvoiceType(),checkLog.getXdpbz()));
        smcyVo.setHandleCode(checkLog.getHandleCode());
        smcyVo.setGfmc(checkLog.getBuyerName());
        smcyVo.setXfmc(checkLog.getSalerName());
        if ("0001".equals(checkLog.getHandleCode())) {
            smcyVo.setDetailState(true);
            smcyVo.setDelState(false);
            smcyVo.setEditState(false);
        } else {
            smcyVo.setDelState(true);
            smcyVo.setEditState(true);
            smcyVo.setDetailState(false);
        }
        return smcyVo;
    }

    /**
     * 大企业-查验一张发票信息，此方法为公共方法，多种查验方式公用
     *
     * @param pramsMap
     *            请求参数
     * @return 返回结果
     *
     */
    private TDxCheckLog checkSingleInvioce(Map<String, String> pramsMap) {

        TDxCheckLog checkLog = new TDxCheckLog();

        String userId = pramsMap.get("userid");
        String invoiceType = pramsMap.get("invoiceType");
        String invoiceCode = pramsMap.get("invoiceCode");
        if (StringHelper.isBlank(invoiceType)) {
            if(FplxEnum.QDZZP.getFplxDm().equals(invoiceType) || FplxEnum.QDPP.getFplxDm().equals(invoiceType)){
                invoiceType = "31";
            }else {
                InvoiceUtil iu = new InvoiceUtil(invoiceCode);
                invoiceType = iu.getFplxdm();
            }
        }

        // 通行费发票二维码中的发票类型代码为10“电子发票”，需要单独根据发票代码判断发票类型
        if (FplxEnum.DZP.getFplxDm().equals(invoiceType)) {
            InvoiceUtil iu = new InvoiceUtil(invoiceCode);
            if (FplxEnum.TXF.getFplxDm().equals(iu.getFplxdm())) {
                invoiceType = FplxEnum.TXF.getFplxDm();
            }
        }
        String invoiceNo = pramsMap.get("invoiceNo");
        String invoiceDate = pramsMap.get("invoiceDate");
        String invoiceAmount = pramsMap.getOrDefault("invoiceAmount", "");
        String taxAmount = pramsMap.getOrDefault("taxAmount", "");
        String checkCode = pramsMap.getOrDefault("checkCode", "");
        String gfmc = pramsMap.getOrDefault("gfmc", "");
        String xfmc = pramsMap.getOrDefault("xfmc", "");
        String saveHistory = pramsMap.getOrDefault("saveHistory", "");
        String taxNo = pramsMap.getOrDefault("taxNo", "");
        String company = pramsMap.get("company");
        checkLog.setCheckUser(userId);
        if(FplxEnum.QDZZP.getFplxDm().equals(invoiceType) || FplxEnum.QDPP.getFplxDm().equals(invoiceType)){
            checkLog.setInvoiceType(pramsMap.get("invoiceType"));
            if (!StringHelper.isBlank(invoiceAmount)) {
                try {
                    checkLog.setTotalAmount(BigDecimal.valueOf(new DecimalFormat().parse(invoiceAmount).doubleValue()));
                    checkLog.setInvoiceAmount(null);
                } catch (Exception e) {
                    checkLog.setTotalAmount(new BigDecimal("0"));
                }
            }
        }else {
            if (!StringHelper.isBlank(invoiceAmount)) {
                try {
                    checkLog.setInvoiceAmount(BigDecimal.valueOf(new DecimalFormat().parse(invoiceAmount).doubleValue()));
                } catch (Exception e) {
                    checkLog.setInvoiceAmount(new BigDecimal("0"));
                }
            }
            checkLog.setInvoiceCode(invoiceCode);
            checkLog.setInvoiceType(invoiceType);
        }

        checkLog.setInvoiceNo(invoiceNo);

        if (!StringHelper.isBlank(invoiceDate)) {
            checkLog.setInvoiceDate(DateUtils.strToDate(invoiceDate));
        }
        checkLog.setHandleDate(DateUtils.getSqlDateLong());

        if (!StringHelper.isBlank(taxAmount)) {
            try {
                checkLog.setTaxAmount(BigDecimal.valueOf(new DecimalFormat().parse(taxAmount).doubleValue()));
            } catch (Exception e) {
                checkLog.setTaxAmount(new BigDecimal("0"));
            }
        }
        if (!StringHelper.isBlank(checkCode)) {
            checkLog.setCheckCode(checkCode);
        }
        checkLog.setBuyerName(gfmc);
        checkLog.setSalerName(xfmc);

        JSONObject queryInvoiceResult =
            invoiceQueryUtil.queryInvoice(invoiceCode, invoiceNo, invoiceDate, invoiceAmount, checkCode, taxNo,invoiceType);
        queryInvoiceResult.put("scanId", pramsMap.get("scanId"));
        queryInvoiceResult.put("company", pramsMap.get("company"));
        if (queryInvoiceResult.containsKey("returnCode")) {
            // 查验出错
            checkLog.setHandleCode(queryInvoiceResult.getString("returnCode"));
            checkLog.setCheckMassege(queryInvoiceResult.getString("returnMessage"));
            if ("Y".equals(saveHistory)) {
                // 保存查验主表
                TDxCheckRecordInvoice checkRecordInvoice = new TDxCheckRecordInvoice();
                checkRecordInvoice.setScanId(pramsMap.get("scanId"));
                checkRecordInvoice.setUuid((StringUtils.isBlank(invoiceCode)?"":invoiceCode) + invoiceNo);
                checkRecordInvoice.setCheckUser(userId);
                checkRecordInvoice.setFphm(invoiceNo);
                checkRecordInvoice.setFpzl(invoiceType);
                checkRecordInvoice.setCompany(pramsMap.get("company"));
                if (!StringHelper.isBlank(invoiceDate)) {
                    checkRecordInvoice.setKprq(DateUtils.strToStrDate2(invoiceDate));
                }
                if(FplxEnum.QDZZP.getFplxDm().equals(invoiceType) || FplxEnum.QDPP.getFplxDm().equals(invoiceType)){
                    if (!StringHelper.isBlank(invoiceAmount)) {
                        checkRecordInvoice.setJshj(invoiceAmount);
                    }
                }else {
                    checkRecordInvoice.setFpdm(invoiceCode);
                    if (!StringHelper.isBlank(invoiceAmount)) {
                        checkRecordInvoice.setJe(invoiceAmount);
                    }
                }

                if (!StringHelper.isBlank(taxAmount)) {
                    checkRecordInvoice.setSe(taxAmount);
                }
                if (!StringHelper.isBlank(checkCode)) {
                    checkRecordInvoice.setJym(checkCode);
                }
                checkRecordInvoice.setPdfMd5(Long.valueOf(scanIdUtils.createSerialNum()));
                checkRecordInvoice.setCreateDate(DateUtils.getSqlDateLong());
                checkRecordInvoice.setCyjgCode(queryInvoiceResult.getString("returnCode"));
                checkRecordInvoice.setCyjgTip(queryInvoiceResult.getString("returnMessage"));
                signCheckRecordService.saveCheckRecordInvoice(checkRecordInvoice, pramsMap.get("dbName"));
            }
        } else {
            // 查验成功
            if ("Y".equals(saveHistory)) {
                // 查验调用，保存查验记录
                signSaveCheckInfoService.saveCheckInfo(queryInvoiceResult, pramsMap.get("userid"),
                    pramsMap.get("dbName"));
                if(StringUtils.isNotBlank(queryInvoiceResult.getString("invoiceType"))){
                    checkLog.setInvoiceType(queryInvoiceResult.getString("invoiceType"));
                }
            }
            checkLog.setHandleCode(queryInvoiceResult.getString("resultCode"));
            checkLog.setCheckMassege(queryInvoiceResult.getString("resultTip"));
            try {
                checkLog.setTaxAmount(queryInvoiceResult.getBigDecimal("taxAmount"));
            } catch (Exception e) {
                checkLog.setTaxAmount(new BigDecimal(0));
            }
            try {
                checkLog.setTotalAmount(queryInvoiceResult.getBigDecimal("totalAmount"));
            } catch (Exception e) {
                checkLog.setTotalAmount(new BigDecimal(0));
            }
            try {
                if (FplxEnum.ESC.getFplxDm().equals(invoiceType)) {
                    checkLog.setInvoiceAmount(queryInvoiceResult.getBigDecimal("carPrice"));
                } else {
                    checkLog.setInvoiceAmount(queryInvoiceResult.getBigDecimal("invoiceAmount"));
                }
            } catch (Exception e) {
                checkLog.setInvoiceAmount(new BigDecimal(0));
            }
            checkLog.setBuyerName(queryInvoiceResult.getString("buyerName"));
            checkLog.setSalerName(queryInvoiceResult.getString("salerName"));
            if(FplxEnum.ESC.getFplxDm().equals(invoiceType)){
                checkLog.setBuyerName(queryInvoiceResult.getString("buyerUnitOrIndividual"));
                checkLog.setSalerName(queryInvoiceResult.getString("sellerUnitOrIndividual"));
            }
        }
        // 查验调用，保存查验日志
        if ("Y".equals(saveHistory)) {
            DynamicContextHolder.push(pramsMap.get("dbName") + DbConstant.BUSINESS_WRITE);
            super.save(checkLog);
        }

        return checkLog;
    }

    /**
     * 转换扫描查验显示对象
     *
     * @param checkLog
     *            扫描查验结果
     * @return 返回结果
     *
     */
    private ExtSmcyVO convertToSmcyView(TDxCheckLog checkLog) {
        ExtSmcyVO smcyVo = new ExtSmcyVO();
        String id = checkLog.getInvoiceCode() + "-" + checkLog.getInvoiceNo();
        smcyVo.setId(id);
        smcyVo.setCheckMassege(checkLog.getCheckMassege());
        smcyVo.setInvoiceCode(checkLog.getInvoiceCode());
        smcyVo.setInvoiceNo(checkLog.getInvoiceNo());
        if (checkLog.getInvoiceDate() != null) {
            smcyVo.setInvoiceDate(DateUtils.dateToStr(checkLog.getInvoiceDate()));
        }
        if (checkLog.getTotalAmount()!= null) {
            smcyVo.setTotalAmount(
                    AmountFormatUtil.fmtMicrometer(MathUtil.round(checkLog.getTotalAmount().toPlainString())));
        }else {
            smcyVo.setTotalAmount("");
        }
        if (checkLog.getInvoiceAmount() != null) {
            smcyVo.setInvoiceAmount(
                    AmountFormatUtil.fmtMicrometer(MathUtil.round(checkLog.getInvoiceAmount().toPlainString())));
        } else {
            smcyVo.setInvoiceAmount("");
        }

        if (checkLog.getCheckCode() != null) {
            smcyVo.setCheckCode(checkLog.getCheckCode());
        } else {
            smcyVo.setCheckCode("");
        }
        smcyVo.setInvoiceType(checkLog.getInvoiceType());
        smcyVo.setHandleCode(checkLog.getHandleCode());
        smcyVo.setGfmc(checkLog.getBuyerName());
        smcyVo.setXfmc(checkLog.getSalerName());
        if ("0001".equals(checkLog.getHandleCode())) {
            smcyVo.setDetailState(true);
            smcyVo.setDelState(false);
            smcyVo.setEditState(false);
        } else {
            smcyVo.setDelState(true);
            smcyVo.setEditState(true);
            smcyVo.setDetailState(false);
        }
        return smcyVo;
    }

    @Override
    public String getFpmx(String invoiceCode, String invoiceNo, String dbName) {
        DynamicContextHolder.push(dbName + DbConstant.BUSINESS_READ);
        JSONObject json = signSaveCheckInfoService.getCheckInfo(invoiceCode, invoiceNo, dbName);

        if (json != null) {
            return super.responseResult(json);
        } else {
            return null;
        }
    }

    @Override
    public String smyQueryInvoice(Map<String, String> pramsMapAll, String saveHistory, UserInfo userInfo) {

        String[] titlelist = {"查验结果描述", "发票代码", "发票号码","数电号码", "开票日期", "购方名称", "销方名称", "金额", "税额", "校验码"};
        String[] titleprop = {"checkMassege", "invoiceCode", "invoiceNo", "eleInvoiceNo", "invoiceDate", "gfmc", "xfmc",
            "invoiceAmount", "taxAmount", "checkCode","invoiceType"};
        // 需要设置返回列表标题时调用
        JSONObject json = super.setTitleList(titlelist, titleprop);
        String dbName = pramsMapAll.get("dbName");

        DynamicContextHolder.push(dbName + DbConstant.BUSINESS_READ);
        QueryWrapper<TDxScanInvoiceLog> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("pch", pramsMapAll.get("pch"));
        TDxScanInvoiceLog scanInvoiceLog = signScanInvoiceLogService.getOne(queryWrapper);
        if (scanInvoiceLog == null) {
            json.put("datalist", "");
            return super.responseResult(json);
        }
        String invoiceText = scanInvoiceLog.getInvoiceText();
        List<Map<String, String>> pramsMapList = this.validateScanInfo(invoiceText, pramsMapAll);
        List<ExtSmycyVO> returnList = new ArrayList<>();
        for (int i = 0; i < pramsMapList.size(); i++) {
            String xh = String.valueOf(i + 1);
            Map<String, String> pramsMap = pramsMapList.get(i);
            String scanId = pramsMap.get("scanId");
            if (StringHelper.isBlank(scanId)) {
                scanId = "";
            }
            pramsMap.put("saveHistory", saveHistory);

            String invoiceCode = pramsMap.get("invoiceCode");
            String invoiceNo = pramsMap.get("invoiceNo");
            String uuid = (StringUtils.isBlank(invoiceCode)?"":invoiceCode)+invoiceNo;
            Map<String,Object> notes = checkingInvoiceInfo(dbName, uuid, userInfo);
            if (notes.get("notes") != null) {
                pramsMap.put("errmsg", notes.get("notes").toString());
                ExtSmycyVO smycyVo = this.convertMapToSmycyView(pramsMap, xh,notes);
                smycyVo.setScanId(scanId);
                returnList.add(smycyVo);
            } else {
                if (!pramsMap.containsKey("errmsg")) {
                    log.info("开始调查验接口获取发票数据");
                    if(true){
                        try {
                            //开放平台查验
                            OpenServiceSingleInvoiceCheckRequest req = new OpenServiceSingleInvoiceCheckRequest();
                            req.setFpdm(pramsMap.get("invoiceCode"));
                            req.setFphm(pramsMap.get("invoiceNo"));
                            req.setFpje(pramsMap.get("invoiceAmount"));
                            req.setJym(pramsMap.get("checkCode"));
                            req.setKprq(pramsMap.get("invoiceDate"));
                            req.setFpzl(pramsMap.get("invoiceType"));
                            OpenServiceSingleInvoiceCheckJxpt checkData = openServicePlatformService.checkSingleInvoice(req);
                            //保存查验记录表t_dx_check_log,记录查验表 t_dx_check_record_invoice
                            TDxCheckLog checkLog = saveCheckRecordInvoice(pramsMap,checkData);
                            ExtSmycyVO smycyVo = this.convertToSmycyView(checkLog, xh);
                            smycyVo.setScanId(scanId);
                            returnList.add(smycyVo);
                        } catch (OpenServiceInvokeException e) {
                            log.info("调开放平台出错:{}",e);
                        }
                    }else{
                        //大企业查验 7.1.2需求 2024年5月9日18:24:35 发票查验目录下所有菜单不用大企业查验，后续看需求
                        TDxCheckLog checkLog = this.checkSingleInvioce(pramsMap);
                    }
                } else {
                    ExtSmycyVO smycyVo = this.convertMapToSmycyView(pramsMap, xh, notes);
                    smycyVo.setScanId(scanId);
                    returnList.add(smycyVo);
                }
            }
        }
        json.put("datalist", returnList);

        return super.responseResult(json);
    }

    /**
     * code 9999 吐司提示
     * code 0000 代表成功
     **/
    @Override
    public Map<String,String> smyUpdateQueryInvoice(Map<String, String> pramsMap,UserInfo user) {
        Map<String,String> result = new HashMap();
        Map<String,Object> notes = checkingInvoiceInfo("",
                (StringUtils.isBlank(pramsMap.get("invoiceCode"))?"":pramsMap.get("invoiceCode")) + pramsMap.get("invoiceNo"), user);
        if (notes.get("notes") != null) {
            result.put("code", "9999");
            result.put("msg", notes.get("notes").toString());
            return result;
        }

        TDxCheckLog checkLog = new TDxCheckLog();
        if(true){
            //开放平台查验
            //开放平台
            OpenServiceSingleInvoiceCheckRequest req = new OpenServiceSingleInvoiceCheckRequest();
            req.setFpdm(StringUtils.isBlank(pramsMap.get("invoiceCode"))?"":pramsMap.get("invoiceCode"));
            req.setFphm(pramsMap.get("invoiceNo"));
            req.setFpje(pramsMap.get("invoiceAmount"));
            req.setJym(pramsMap.get("checkCode"));
            req.setKprq(pramsMap.get("invoiceDate").replace("-", ""));
            req.setFpzl(pramsMap.get("invoiceType"));
            try {
                OpenServiceSingleInvoiceCheckJxpt checkData = openServicePlatformService.checkSingleInvoice(req);
                //保存查验记录表t_dx_check_log,记录查验表 t_dx_check_record_invoice
                checkLog = saveCheckRecordInvoice(pramsMap,checkData);
            } catch (OpenServiceInvokeException e) {
                log.info("调开放平台查验出错:{}",e);
            }
        }else{
            checkLog = this.checkSingleInvioce(pramsMap);
        }
        JSONObject json = new JSONObject();
        ExtSmycyVO smcyVo = this.convertToSmycyView(checkLog, pramsMap.get("xh"));
        json.put("datalist", smcyVo);
        result.put("code", "0000");
        result.put("data", super.responseResult(json));
        result.put("msg", "success");
        return result;
    }

    /**
     * 把ocr信息校验失败的参数转换为页面显示对象
     *
     * @param pramsMap
     *            请求参数
     * @param xh
     *            序号
     * @param notes
     * @return 返回结果
     *
     */
    private ExtSmycyVO convertMapToSmycyView(Map<String, String> pramsMap, String xh, Map<String, Object> notes) {
        String errmsg = pramsMap.get("errmsg");
        String buyerName = pramsMap.get("buyerName");
        String invoiceAmount = pramsMap.get("invoiceAmount");
        String invoiceCode = pramsMap.get("invoiceCode");
        String invoiceDate = pramsMap.get("invoiceDate");
        String invoiceNo = pramsMap.get("invoiceNo");
        String salerName = pramsMap.get("salerName");
        String checkCode = pramsMap.get("checkCode");
        String taxAmount = pramsMap.get("taxAmount");
        String invoiceType = pramsMap.get("invoiceType");

        ExtSmycyVO smycyVo = new ExtSmycyVO();
        smycyVo.setXh(xh);
        smycyVo.setCheckMassege((StringHelper.isBlank(errmsg)) ? "" : errmsg);
        smycyVo.setGfmc((StringHelper.isBlank(buyerName)) ? "" : buyerName);
        smycyVo.setInvoiceCode((StringHelper.isBlank(invoiceCode)) ? "" : invoiceCode);
        smycyVo.setInvoiceDate((StringHelper.isBlank(invoiceDate)) ? "" : invoiceDate);
        smycyVo.setInvoiceNo((StringHelper.isBlank(invoiceNo)) ? "" : invoiceNo);
        smycyVo.setXfmc((StringHelper.isBlank(salerName)) ? "" : salerName);
        smycyVo.setCheckCode((StringHelper.isBlank(checkCode)) ? "" : checkCode);
        if(FplxEnum.QDZZP.getFplxDm().equals(invoiceType) || FplxEnum.QDPP.getFplxDm().equals(invoiceType)){
            smycyVo.setTotalAmount(
                    (StringHelper.isBlank(invoiceAmount)) ? "" : AmountFormatUtil.fmtMicrometer(invoiceAmount));
        }else {
            InvoiceUtil iu = new InvoiceUtil(invoiceCode);
            invoiceType = iu.getFplxdm();
            smycyVo.setInvoiceAmount(
                    (StringHelper.isBlank(invoiceAmount)) ? "" : AmountFormatUtil.fmtMicrometer(invoiceAmount));
            smycyVo.setTaxAmount((StringHelper.isBlank(taxAmount)) ? "" : AmountFormatUtil.fmtMicrometer(taxAmount));
        }
        smycyVo.setInvoiceType(invoiceType);

        //如果checkRecordInvoice不为空，用checkRecordInvoice的数据
        if(notes.get("checkRecordInvoice") != null){
            TDxCheckRecordInvoice checkRecordTmp = (TDxCheckRecordInvoice) notes.get("checkRecordInvoice");
            smycyVo.setInvoiceType(checkRecordTmp.getFpzl());
            smycyVo.setInvoiceCode(checkRecordTmp.getFpdm());
            smycyVo.setInvoiceNo(checkRecordTmp.getFphm());
            smycyVo.setEleInvoiceNo(checkRecordTmp.getEleInvoiceNo());
        }else{
            //如果是20位发票号码，拆封
            if(smycyVo.getInvoiceNo().length()==20){
                smycyVo.setEleInvoiceNo(smycyVo.getInvoiceNo());
                smycyVo.setInvoiceCode(smycyVo.getInvoiceNo().substring(0, 12));
                smycyVo.setInvoiceNo(smycyVo.getInvoiceNo().substring(12, 20));
            }
        }

        smycyVo.setHandleCode("2011");
        smycyVo.setDetailFlag(false);
        smycyVo.setEditState(true);
        smycyVo.setDelState(true);
        return smycyVo;
    }

    /**
     * 校验发票ocr信息是否正确，并把扫描信息封装为页面展示对象，用于校验失败时直接返回
     *
     * @param invoiceText
     *            请求参数
     * @param pramsMap
     *            请求参数
     * @return 返回结果
     *
     */
    private List<Map<String, String>> validateScanInfo(String invoiceText, Map<String, String> pramsMap) {

        List<Map<String, String>> pramsMapList = new ArrayList<>();
        String taxNo = pramsMap.getOrDefault("taxNo", "");
        JSONObject ocrData = JSONObject.parseObject(invoiceText);
        JSONArray datas = ocrData.getJSONArray("invoiceList");
        for (int i = 0; i < datas.size(); i++) {
            Map<String, String> validateMap = new HashMap<>();
            validateMap.put("userid", pramsMap.get("userid"));
            validateMap.put("dbName", pramsMap.get("dbName"));

            JSONObject data = (JSONObject)ocrData.getJSONArray("invoiceList").get(i);
            String invoiceCode = data.getString("fpdm");
            String invoiceNo = data.getString("fphm");
            String invoiceDate = data.getString("kprq");
            String invoiceAmount = data.getString("je");
            String taxAmount = data.getString("se");
            String totalAmount = data.getString("jshj");
            String checkCode = data.getString("jym");
            String buyerName = data.getString("gfmc");
            String salerName = data.getString("xfmc");
            String scanId = data.getString("scanid");
            String invoiceType = data.getString("fplx");
            if (!(FplxEnum.QDZZP.getFplxDm().equals(invoiceType) || FplxEnum.QDPP.getFplxDm().equals(invoiceType))){
                if (StringUtils.isBlank(invoiceCode)) {
                    invoiceCode = "F" + LocalTrmSeqNum.getSeqNum();
                }
            }
            if (StringUtils.isBlank(invoiceNo)) {
                invoiceNo = "F" + LocalTrmSeqNum.getSeqNum();
            }
            validateMap.put("invoiceCode", invoiceCode);
            validateMap.put("invoiceNo", invoiceNo);
            validateMap.put("invoiceAmount", invoiceAmount);
            validateMap.put("taxAmount", taxAmount);
            validateMap.put("totalAmount", totalAmount);
            validateMap.put("checkCode", checkCode);
            //如果是186 且校验码有值，则用校验码后6位
            if("186".equals(invoiceType)){
                if(StringUtils.isNotBlank(checkCode)&&checkCode.length()>=6){
                    validateMap.put("checkCode", checkCode.substring(checkCode.length()-6, checkCode.length()));
                }
            }

            validateMap.put("buyerName", buyerName);
            validateMap.put("salerName", salerName);
            validateMap.put("scanId", scanId);
            validateMap.put("company", pramsMap.get("company"));
            validateMap.put("taxNo", taxNo);

            String errmsg = null;

            InvoiceUtil iu = new InvoiceUtil(invoiceCode);
            boolean fpdmValid = iu.fpdmValid();
            if(!(FplxEnum.QDZZP.getFplxDm().equals(invoiceType) || FplxEnum.QDPP.getFplxDm().equals(invoiceType)
                ||FplxEnum.ZZDZ.getFplxDm().equals(invoiceType)||FplxEnum.ZZPP.getFplxDm().equals(invoiceType)
            )
            ){
                invoiceType = iu.getFplxdm();
            }
            validateMap.put("invoiceType", invoiceType);
            if (FplxEnum.ESC.getFplxDm().equals(invoiceType) ||FplxEnum.QDZZP.getFplxDm().equals(invoiceType)
                 ||FplxEnum.QDPP.getFplxDm().equals(invoiceType)  ) {
                invoiceAmount = totalAmount;
                validateMap.put("invoiceAmount", invoiceAmount);
            }
            if(FplxEnum.ESC.getFplxDm().equals(invoiceType)){
                if(StringUtils.isEmpty(invoiceDate)){
                    invoiceDate = DateUtils.getStringDateShort();
                }
            }
            if (!(FplxEnum.QDZZP.getFplxDm().equals(invoiceType) || FplxEnum.QDPP.getFplxDm().equals(invoiceType))
                    && (!fpdmValid || invoiceType == null)) {
                errmsg = "发票代码识别错误！";
            } else {

                iu.setFphm(invoiceNo);
                if (!(FplxEnum.QDZZP.getFplxDm().equals(invoiceType) || FplxEnum.QDPP.getFplxDm().equals(invoiceType))
                        && !iu.fphmValid()) {
                    errmsg = "发票号码识别错误！";
                } else {
                    iu.setKprq(invoiceDate);
                    if (iu.kprqValid("yyyyMMdd") || iu.kprqValid(null)) {
                        // 转换为统一的日期格式
                        invoiceDate = invoiceDate.replaceAll("-", "");
                        String kprq = invoiceDate.substring(0, 4) + "-" + invoiceDate.substring(4, 6) + "-"
                            + invoiceDate.substring(6);
                        boolean status = checkValiDate(kprq);
                        if (status) {
                            validateMap.put("invoiceDate", kprq);
                        } else {
                            validateMap.put("invoiceDate", DateUtils.getStringDateShort());
                        }
                        iu.setJe(invoiceAmount);
                        if (!iu.jeValid()) {
                            errmsg = "金额识别错误！";
                        }
                    } else {
                        errmsg = "开票日期识别错误！";
                    }
                }
            }

            if (errmsg != null) {
                validateMap.put("errmsg", errmsg);
            }
            pramsMapList.add(validateMap);
        }
        return pramsMapList;
    }

    /**
     * 转换扫描仪查验显示对象
     *
     * @param checkLog
     *            扫描查验结果
     * @param xh
     *            序号
     * @return 返回结果
     *
     */
    private ExtSmycyVO convertToSmycyView(TDxCheckLog checkLog, String xh) {
        ExtSmycyVO smcyVo = new ExtSmycyVO();
        smcyVo.setXh(xh);
        smcyVo.setId(checkLog.getHandleCode());
        smcyVo.setCheckMassege(checkLog.getCheckMassege());
        smcyVo.setInvoiceCode(checkLog.getInvoiceCode());
        smcyVo.setInvoiceNo(checkLog.getInvoiceNo());
        if(StringUtils.isNotBlank(checkLog.getEleInvoiceNo())){
            smcyVo.setEleInvoiceNo(checkLog.getEleInvoiceNo());
        }
        if (checkLog.getInvoiceDate() != null) {
            smcyVo.setInvoiceDate(DateUtils.dateToStr(checkLog.getInvoiceDate()));
        }
        if (checkLog.getInvoiceAmount() != null) {
            smcyVo.setInvoiceAmount(
                AmountFormatUtil.fmtMicrometer(MathUtil.round(checkLog.getInvoiceAmount().toPlainString())));
        } else {
            smcyVo.setInvoiceAmount("");
        }
        if (checkLog.getCheckCode() != null) {
            smcyVo.setCheckCode(checkLog.getCheckCode());
        } else {
            smcyVo.setCheckCode("");
        }
        if (checkLog.getTaxAmount() != null) {
            smcyVo
                .setTaxAmount(AmountFormatUtil.fmtMicrometer(MathUtil.round(checkLog.getTaxAmount().toPlainString())));
        } else {
            smcyVo.setTaxAmount("");
        }

        if (checkLog.getBuyerName() != null) {
            smcyVo.setGfmc(checkLog.getBuyerName());
        } else {
            smcyVo.setGfmc("");
        }
        if (checkLog.getSalerName() != null) {
            smcyVo.setXfmc(checkLog.getSalerName());
        } else {
            smcyVo.setXfmc("");
        }
        smcyVo.setInvoiceType(checkLog.getInvoiceType());
        smcyVo.setHandleCode(checkLog.getHandleCode());
        boolean detailFlag = true;
        boolean editState = true;
        boolean delState = true;
        if ("0001".equals(checkLog.getHandleCode())) {
            editState = false;
            delState = false;
        } else {
            detailFlag = false;
        }
        smcyVo.setDetailFlag(detailFlag);
        smcyVo.setEditState(editState);
        smcyVo.setDelState(delState);
        return smcyVo;
    }

    @Override
    public String checkExcelFp(JSONArray detailArray, UserInfo userInfo, String dbName) {
        String msg = null;
        for (int i = 0; i < detailArray.size(); i++) {
            JSONObject invoice = detailArray.getJSONObject(i);
            String invoiceCode = invoice.getString("invoiceCode");
            String invoiceNo = invoice.getString("invoiceNo");
            String invoiceDate = invoice.getString("invoiceDate");
            String invoiceAmount = invoice.getString("invoiceAmount");
            String checkCode = invoice.getString("checkCode");
            //如果发票号码是20位，不验证此方法
            if(invoiceNo.length()!=20){
                msg = validateInvoiceInfo(invoiceCode, invoiceNo, invoiceDate);
            }
            if (msg == null) {
                InvoiceUtil invoiceUtil = new InvoiceUtil(invoiceCode);
                if (FplxEnum.ZP.getFplxDm().equals(invoiceUtil.getFplxdm())
                    || FplxEnum.JDC.getFplxDm().equals(invoiceUtil.getFplxdm())
                    || FplxEnum.DZZP.getFplxDm().equals(invoiceUtil.getFplxdm())
                    || FplxEnum.ESC.getFplxDm().equals(invoiceUtil.getFplxdm())) {
                    invoiceUtil.setJe(invoiceAmount);
                    if (!invoiceUtil.jeValid()) {
                        msg = "金额不正确！";
                    }
                } else {
                    invoiceUtil.setJym(checkCode);
                    //如果发票号码是20位，不验证此方法
                    if(invoiceNo.length()!=20){
                        if (!invoiceUtil.jymValid()) {
                            msg = "校验码不正确！";
                        }
                    }

                }
                Map<String,Object> notes = checkingInvoiceInfo(dbName, StringUtils.isEmpty(invoiceCode)?"":invoiceCode + invoiceNo, userInfo);
                if (notes.get("notes") != null) {
                    msg = notes.get("notes").toString();
                }
            }
            if (msg != null) {
                msg = "发票号码" + invoiceNo + "：" + msg;
                break;
            }
        }
        return msg;
    }

    /**
     * 校验扫描基本信息是否正确
     *
     * @param invoiceDate
     *            开票日期
     * @param invoiceNo
     *            发票号码
     * @param invoiceCode
     *            发票代码
     *
     * @return 返回结果
     *
     */
    private String validateInvoiceInfo(String invoiceCode, String invoiceNo, String invoiceDate) {
        String notes = null;
        InvoiceUtil invoiceUtil = new InvoiceUtil(invoiceCode);
        if (!invoiceUtil.fpdmValid() || invoiceUtil.getFplxdm() == null) {
            notes = "发票代码不正确！";
        } else {
            invoiceUtil.setFphm(invoiceNo);
            if (!invoiceUtil.fphmValid()) {
                notes = "发票号码不正确！";
            } else {
                invoiceUtil.setKprq(invoiceDate);
                if (!invoiceUtil.kprqValid(null)) {
                    notes = "开票日期不正确！";
                }
            }
        }
        return notes;
    }

    @Override
    public List<Map<String, String>> convertExcelFp(JSONArray detailArray, String userId, String userName,
        String dbName) {
        List<Map<String, String>> excelFpList = new ArrayList<>(detailArray.size());
        for (int i = 0; i < detailArray.size(); i++) {
            JSONObject excelFp = detailArray.getJSONObject(i);
            // 入参统一在入口处理
            Map<String, String> pramsMap = new HashMap<>(16);
            pramsMap.put("userid", userId);
            pramsMap.put("username", userName);
            pramsMap.put("dbName", dbName);
            pramsMap.put("checkCode", excelFp.getString("checkCode"));
            pramsMap.put("invoiceCode", excelFp.getString("invoiceCode"));
            pramsMap.put("invoiceNo", excelFp.getString("invoiceNo"));
            pramsMap.put("invoiceType", (new InvoiceUtil(excelFp.getString("invoiceCode"))).getFplxdm());
            pramsMap.put("invoiceDate", excelFp.getString("invoiceDate"));
            pramsMap.put("invoiceAmount", excelFp.getString("invoiceAmount"));
            excelFpList.add(pramsMap);
        }
        return excelFpList;
    }

    @Override
    public String cyExcelfp(List<Map<String, String>> detailList, String saveHistory, String company, String taxNo,
        String menuId) {
        String[] titlelist = {"查验结果描述", "发票代码", "发票号码","数电号码", "开票日期", "金额", "校验码"};
        String[] titleprop = {"checkMassege", "invoiceCode", "invoiceNo","eleInvoiceNo", "invoiceDate", "invoiceAmount", "checkCode"};
        // 需要设置返回列表标题时调用
        JSONObject json = super.setTitleList(titlelist, titleprop);
        List<ExtSmcyVO> returnList = new ArrayList<>();
        for (Map<String, String> pramsMap : detailList) {
            pramsMap.put("saveHistory", saveHistory);
            pramsMap.put("company", company);
            pramsMap.put("taxNo", taxNo);
            if(true){
                //开放平台查验
                OpenServiceSingleInvoiceCheckRequest req = new OpenServiceSingleInvoiceCheckRequest();
                req.setFpdm(pramsMap.get("invoiceCode"));
                req.setFphm(pramsMap.get("invoiceNo"));
                req.setFpje(pramsMap.get("invoiceAmount"));
                req.setJym(pramsMap.get("checkCode"));
                req.setKprq(pramsMap.get("invoiceDate"));
                req.setFpzl(pramsMap.get("invoiceType"));
                try {
                    OpenServiceSingleInvoiceCheckJxpt checkData = openServicePlatformService.checkSingleInvoice(req);
                    //保存查验记录表t_dx_check_log,记录查验表 t_dx_check_record_invoice
                    TDxCheckLog checkLog = saveCheckRecordInvoice(pramsMap,checkData);
                    //组织前端展示的方法
                    ExtSmcyVO smcyVo = this.convertToSmcyViewKfpt(checkLog);
                    returnList.add(smcyVo);
                } catch (OpenServiceInvokeException e) {
                    log.info("调大企业平台出错:{}",e);
                }
            }else{
                //大企业查验 7.1.2需求 2024年5月9日18:24:35 发票查验目录下所有菜单不用大企业查验，后续看需求
                TDxCheckLog checkLog = this.checkSingleInvioce(pramsMap);
                ExtSmcyVO smcyVo = this.convertToSmcyView(checkLog);
                returnList.add(smcyVo);
            }

        }
        json.put("datalist", returnList);
        return super.responseResult(json);
    }

    @Override
    public String getCheckHistory(Map<String, String> pramsMap, int curr, int size) {
        String company = pramsMap.get("company");
        String menuId = pramsMap.get("menuId");
        JSONObject json = tabulateRedisService.getTabulateMenu(company, menuId);

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

        // 合计信息,仅第一页时需要统计，减少数据库压力
        if (curr == 1) {
            long hjsl;
            String hjje = "0.00";
            String hjse = "0.00";
            List<TDxCheckLog> hjList = super.baseMapper.selectCheckHistoryHj(pramsMap);
            TDxCheckLog hjxx = hjList.get(0);
            hjsl = hjxx.getId();
            if (hjsl > 0) {
                hjje = hjxx.getInvoiceAmount() == null ? "0.00"
                    : AmountFormatUtil.fmtMicrometer(MathUtil.round(hjxx.getInvoiceAmount().toPlainString()));
                hjse = hjxx.getTaxAmount() == null ? "0.00"
                    : AmountFormatUtil.fmtMicrometer(MathUtil.round(hjxx.getTaxAmount().toPlainString()));

            }
            json.put("hjsl", hjsl);
            json.put("hjje", hjje);
            json.put("hjse", hjse);
        }
        // 分页获取明细列表
        PageHelper.startPage(curr, size);
        List<TDxCheckLog> pageList = super.baseMapper.selectCheckHistory(pramsMap);
        PageInfo<TDxCheckLog> pageInfo = new PageInfo<>(pageList);
        List<TDxCheckLog> resultList = pageInfo.getList();

        // 设置记录总数
        json.put("total", pageInfo.getTotal());

        List<Object> returnList = new ArrayList<>();
        if (resultList != null && resultList.size() > 0) {
            int start = new Long(pageInfo.getStartRow()).intValue();
            for (int i = 0; i < resultList.size(); i++) {
                CheckHistoryVO mxlb = this.convertToCheckHistoryView(resultList.get(i), start + i);
                returnList.add(mxlb);
            }
        }
        json.put("datalist", returnList);
        return super.responseResult(json);
    }

    private CheckHistoryVO convertToCheckHistoryView(TDxCheckLog tDxCheckLog, int i) {
        CheckHistoryVO checkHistory = new CheckHistoryVO();
        checkHistory.setId(tDxCheckLog.getId());
        checkHistory.setXh(String.valueOf(i));
        checkHistory.setInvoiceCode(tDxCheckLog.getInvoiceCode());
        checkHistory.setInvoiceNo(tDxCheckLog.getInvoiceNo());
        checkHistory.setEleInvoiceNo(tDxCheckLog.getEleInvoiceNo());
        checkHistory.setInvoiceDate(
            (tDxCheckLog.getInvoiceDate() == null) ? "" : DateUtils.dateToStr(tDxCheckLog.getInvoiceDate()));
        checkHistory.setInvoiceAmount((tDxCheckLog.getInvoiceAmount() == null) ? ""
            : AmountFormatUtil.fmtMicrometer(MathUtil.round(tDxCheckLog.getInvoiceAmount().toPlainString())));
        checkHistory.setTaxAmount((tDxCheckLog.getTaxAmount() == null) ? ""
            : AmountFormatUtil.fmtMicrometer(MathUtil.round(tDxCheckLog.getTaxAmount().toPlainString())));
        checkHistory.setTotalAmount((tDxCheckLog.getTotalAmount() == null) ? ""
            : AmountFormatUtil.fmtMicrometer(MathUtil.round(tDxCheckLog.getTotalAmount().toPlainString())));
        checkHistory.setGfmc((tDxCheckLog.getBuyerName() == null) ? "" : tDxCheckLog.getBuyerName());
        checkHistory.setXfmc((tDxCheckLog.getSalerName() == null) ? "" : tDxCheckLog.getSalerName());
        checkHistory.setScanId((tDxCheckLog.getScanId() == null) ? "" : tDxCheckLog.getScanId());

        if (tDxCheckLog.getScanId() != null && !"".equals(tDxCheckLog.getScanId())) {
            checkHistory.setImgState(true);
        } else {
            checkHistory.setImgState(false);
        }

        if (tDxCheckLog.getInvoiceStatus() != null) {

            if ("N".equals(tDxCheckLog.getInvoiceStatus()) || "0".equals(tDxCheckLog.getInvoiceStatus())) {
                checkHistory.setInvoiceStatus("正常");
            } else if ("Y".equals(tDxCheckLog.getInvoiceStatus()) || "2".equals(tDxCheckLog.getInvoiceStatus())) {
                checkHistory.setInvoiceStatus("作废");
            } else if ("3".equals(tDxCheckLog.getInvoiceStatus())) {
                checkHistory.setInvoiceStatus("红冲");
            }
        }
        checkHistory.setCheckMassege((tDxCheckLog.getCheckMassege() == null) ? "" : tDxCheckLog.getCheckMassege());
        checkHistory.setInvoiceType(tDxCheckLog.getInvoiceType());
        checkHistory.setHandleCode((tDxCheckLog.getHandleCode() == null) ? "" : tDxCheckLog.getHandleCode());
        checkHistory.setCheckCode((tDxCheckLog.getCheckCode() == null) ? "" : tDxCheckLog.getCheckCode());
        checkHistory
            .setHandleDate(tDxCheckLog.getHandleDate() == null ? "" : DateUtils.dateToStr(tDxCheckLog.getHandleDate()));
        checkHistory.setCheckUser(tDxCheckLog.getCheckUser());
        return checkHistory;
    }

    private CheckHistoryVO convertToCheckHistoryDetailView(TDxCheckLog tDxCheckLog, int i) {
        CheckHistoryVO checkHistory = new CheckHistoryVO();
        checkHistory.setId(tDxCheckLog.getId());
        checkHistory.setXh(String.valueOf(i));
        checkHistory.setInvoiceCode(tDxCheckLog.getInvoiceCode());
        checkHistory.setInvoiceNo(tDxCheckLog.getInvoiceNo());
        checkHistory.setInvoiceDate(
            (tDxCheckLog.getInvoiceDate() == null) ? "" : DateUtils.dateToStr(tDxCheckLog.getInvoiceDate()));
        checkHistory.setInvoiceAmount((tDxCheckLog.getInvoiceAmount() == null) ? ""
            : AmountFormatUtil.fmtMicrometer(MathUtil.round(tDxCheckLog.getInvoiceAmount().toPlainString())));
        checkHistory.setTaxAmount((tDxCheckLog.getTaxAmount() == null) ? ""
            : AmountFormatUtil.fmtMicrometer(MathUtil.round(tDxCheckLog.getTaxAmount().toPlainString())));
        checkHistory.setTotalAmount((tDxCheckLog.getTotalAmount() == null) ? ""
            : AmountFormatUtil.fmtMicrometer(MathUtil.round(tDxCheckLog.getTotalAmount().toPlainString())));
        checkHistory.setGfmc((tDxCheckLog.getBuyerName() == null) ? "" : tDxCheckLog.getBuyerName());
        checkHistory.setCheckMassege((tDxCheckLog.getCheckMassege() == null) ? "" : tDxCheckLog.getCheckMassege());
        checkHistory.setInvoiceType(tDxCheckLog.getInvoiceType());
        checkHistory.setHandleCode((tDxCheckLog.getHandleCode() == null) ? "" : tDxCheckLog.getHandleCode());
        checkHistory.setHandleDate(
            (tDxCheckLog.getHandleDate() == null) ? "" : DateUtils.dateToStrLong(tDxCheckLog.getHandleDate()));
        return checkHistory;
    }

    /**
     * 判断日期是否合法
     *
     * @param date
     *            请求参数
     * @return 返回结果
     */
    public static boolean checkValiDate(String date) {
        try {
            int year = Integer.parseInt(date.substring(0, 4));
            if (year < 1901) {
                return false;
            }
            int month = Integer.parseInt(date.substring(5, 7));
            if (month > 12) {
                return false;
            }
            int day = Integer.parseInt(date.substring(8, 10));
            if (day > 31) {
                return false;
            }
        } catch (Exception e) {
            return false;
        }
        return true;
    }

    @Override
    public void delCheckHistory(Map<String, String> pramsMap) {
        DynamicContextHolder.push(pramsMap.get("dbName") + DbConstant.BUSINESS_WRITE);
        QueryWrapper<TDxCheckRecordInvoice> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("check_user", pramsMap.get("userid"));
        queryWrapper.eq("uuid", pramsMap.get("uuid"));
        signCheckRecordService.remove(queryWrapper);
    }

    @Override
    public String checkHistoryStatistics(Map<String, String> pramsMap) {
        String company = (String)pramsMap.get("company");
        String menuId = (String)pramsMap.get("menuId");
        JSONObject json = tabulateRedisService.getTabulateMenu(company, menuId);
        DynamicContextHolder.push(pramsMap.get("dbName") + DbConstant.BUSINESS_READ);

        // 需要设置返回列表标题时调用
        List<TDxCheckLog> resultList = super.baseMapper.selectCheckStatisticsCount(pramsMap);

        List<Object> returnList = new ArrayList<>();
        if (resultList != null && resultList.size() > 0) {
            int xh = 0;
            for (TDxCheckLog tDxCheckLog : resultList) {
                xh++;
                CheckStatisticsVO checkStatistics = new CheckStatisticsVO();
                checkStatistics.setId(tDxCheckLog.getCheckMonth());
                checkStatistics.setXh(String.valueOf(xh));
                checkStatistics.setCheckMonth(tDxCheckLog.getCheckMonth());
                checkStatistics.setCheckCount(tDxCheckLog.getCheckCount());
                checkStatistics.setCheckSucc(tDxCheckLog.getCheckSuccessCount());
                checkStatistics.setCheckFail(tDxCheckLog.getCheckErrorCount());
                returnList.add(checkStatistics);
            }
        }
        json.put("datalist", returnList);
        return super.responseResult(json);
    }

    @Override
    public String getCheckHistoryDetail(Map<String, String> pramsMap) {

        String[] titlelist = {"序号", "发票代码", "发票号码", "开票日期", "购方名称", "金额", "税额", "价税合计", "查验结果", "查验时间"};
        String[] titleprop = {"xh", "invoiceCode", "invoiceNo", "invoiceDate", "gfmc", "invoiceAmount", "taxAmount",
            "totalAmount", "checkMassege", "handleDate"};

        // 需要设置返回列表标题时调用
        JSONObject json = super.setTitleList(titlelist, titleprop);

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

        // 分页获取明细列表
        PageHelper.startPage(Integer.parseInt(pramsMap.get("curr")), Integer.parseInt(pramsMap.get("size")));
        List<TDxCheckLog> pageList = super.baseMapper.selectCheckHistoryDetail(pramsMap);
        PageInfo<TDxCheckLog> pageInfo = new PageInfo<>(pageList);
        List<TDxCheckLog> resultList = pageInfo.getList();

        // 设置记录总数
        json.put("total", pageInfo.getTotal());

        List<Object> returnList = new ArrayList<>();
        if (resultList != null && resultList.size() > 0) {
            int start = new Long(pageInfo.getStartRow()).intValue();

            for (int i = 0; i < resultList.size(); i++) {
                CheckHistoryVO mxlb = this.convertToCheckHistoryDetailView(resultList.get(i), start + i);
                returnList.add(mxlb);
            }
        }
        json.put("datalist", returnList);
        return super.responseResult(json);
    }

    @Override
    public Map<String,Object> checkingInvoiceInfo(String dbName, String uuid, UserInfo userInfo) {
        Map<String,Object> result = new HashMap();
        String notes = null;
        DynamicContextHolder.push(dbName + DbConstant.BUSINESS_READ);
        TDxCheckRecordInvoice checkRecordTmp = signCheckRecordService.getCheckInvoiceByUuid(uuid);
        if (checkRecordTmp != null) {
            if (!StringUtils.isBlank(checkRecordTmp.getCheckUser())
                && !userInfo.getLoginname().equals(checkRecordTmp.getCheckUser())&&"0001".equals(checkRecordTmp.getCyjgCode())) {
                notes = "该发票已被他人查验，不可重复查验！";
                result.put("notes", notes);
                result.put("checkRecordInvoice", checkRecordTmp);
                return result;
            }
            if ("0001".equals(checkRecordTmp.getCyjgCode())) {
                if (DateUtils.getStringDateShort().equals(DateUtils.dateToStr(checkRecordTmp.getCreateDate()))) {
                    notes = "该发票今日已查验成功，不可重复查验！";
                    result.put("notes", notes);
                    result.put("checkRecordInvoice", checkRecordTmp);
                    return result;
                }
            }
        }
        result.put("notes", notes);
        result.put("checkRecordInvoice", checkRecordTmp);
        return result;
    }

    @Override
    public String getCheckList(Map<String, Object> pramsMap, int curr, int size) {

        String company = (String)pramsMap.get("company");
        String menuId = (String)pramsMap.get("menuId");
        JSONObject json = tabulateRedisService.getTabulateMenu(company, menuId);
        DynamicContextHolder.push(pramsMap.get("dbName") + DbConstant.BUSINESS_READ);

        // 合计信息,仅第一页时需要统计，减少数据库压力
        if (curr == 1) {
            long hjsl;
            String hjje = "0.00";
            String hjse = "0.00";
            List<TDxCheckLog> hjList = super.baseMapper.getCheckListHj(pramsMap);
            TDxCheckLog hjxx = hjList.get(0);
            hjsl = hjxx.getId();
            if (hjsl > 0) {
                hjje = hjxx.getInvoiceAmount() == null ? "0.00"
                    : AmountFormatUtil.fmtMicrometer(MathUtil.round(hjxx.getInvoiceAmount().toPlainString()));
                hjse = hjxx.getTaxAmount() == null ? "0.00"
                    : AmountFormatUtil.fmtMicrometer(MathUtil.round(hjxx.getTaxAmount().toPlainString()));

            }
            json.put("hjsl", hjsl);
            json.put("hjje", hjje);
            json.put("hjse", hjse);
        }
        // 分页获取明细列表
        PageHelper.startPage(curr, size);
        List<TDxCheckLog> pageList = super.baseMapper.getCheckList(pramsMap);
        PageInfo<TDxCheckLog> pageInfo = new PageInfo<>(pageList);
        List<TDxCheckLog> resultList = pageInfo.getList();

        // 设置记录总数
        json.put("total", pageInfo.getTotal());

        List<Object> returnList = new ArrayList<>();
        if (resultList != null && resultList.size() > 0) {
            int start = new Long(pageInfo.getStartRow()).intValue();

            for (int i = 0; i < resultList.size(); i++) {
                CheckHistoryVO mxlb = this.convertToCheckHistoryView(resultList.get(i), start + i);
                returnList.add(mxlb);
            }
        }
        json.put("datalist", returnList);
        return super.responseResult(json);
    }
}
