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

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.dxhy.api.model.config.Business;
import com.dxhy.api.model.config.UserInfo;
import com.dxhy.api.model.db.TDxInvoiceFileEntity;
import com.dxhy.api.model.db.TdxSaleRecordInvoiceEntity;
import com.dxhy.api.model.invoice.TDxRecordInvoice;
import com.dxhy.api.model.sign.*;
import com.dxhy.common.constant.DbConstant;
import com.dxhy.common.constant.DictConstant;
import com.dxhy.common.datasource.config.DynamicContextHolder;
import com.dxhy.common.enums.FplxEnum;
import com.dxhy.common.enums.FpqsjgEnum;
import com.dxhy.common.enums.QsfsEnum;
import com.dxhy.common.enums.ValidEnum;
import com.dxhy.common.service.DictdetaServcice;
import com.dxhy.common.service.TabulateRedisService;
import com.dxhy.common.service.impl.MpBaseServiceImpl;
import com.dxhy.common.util.AmountFormatUtil;
import com.dxhy.common.util.FileUtils;
import com.dxhy.common.util.InvoiceUtil;
import com.dxhy.common.util.MathUtil;
import com.dxhy.common.utils.CommonUtil;
import com.dxhy.common.utils.DateUtils;
import com.dxhy.common.utils.LocalTrmSeqNum;
import com.dxhy.common.utils.R;
import com.dxhy.jxpt.baseService.dao.TdxInvoiceFileDao;
import com.dxhy.jxpt.baseService.dao.TdxSaleRecordInvoiceDao;
import com.dxhy.jxpt.baseService.sign.dao.SignInvoiceImgDao;
import com.dxhy.jxpt.baseService.sign.dao.SignRecordInvoiceDao;
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.elec.SignInvoiceScanService;
import com.dxhy.jxpt.baseService.sign.service.fpqs.FpqsService;
import com.dxhy.jxptutils.OfdUtils;
import com.dxhy.model.OfdInvoice;
import com.dxhy.ofd.service.OfdService;
import com.dxhy.oss.config.OssReturnConfig;
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.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.InputStream;
import java.nio.file.Files;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author peipei.li
 * @date 2019-04-29 电票管理模块，抵账表操作service
 */
@SuppressWarnings({"AlibabaUndefineMagicConstant", "AlibabaMethodTooLong"})
@Service("signElecInvoiceService")
@Slf4j

public class SignElecInvoiceServiceImpl extends MpBaseServiceImpl<SignRecordInvoiceDao, TDxRecordInvoice>
    implements SignElecInvoiceService {

    @Resource
    private SignInvoiceScanService signInvoiceScanService;
    @Resource
    private SignInvoiceImgService signInvoiceImgService;

    @Resource
    private FileService fileService;
    @Resource
    private OfdService ofdService;

    @Resource
    private TabulateRedisService tabulateRedisService;

    @Resource
    private FpqsService fpqsService;

    @Resource
    private DictdetaServcice dictdetaServcice;

    @Autowired
    private SignRecordInvoiceDao signRecordInvoiceDao;

    @Resource
    private TdxSaleRecordInvoiceDao tdxSaleRecordInvoiceDao;

    @Resource
    private TdxInvoiceFileDao tdxInvoiceFileDao;

    @Resource
    private SignInvoiceImgDao signInvoiceImgDao;


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

    protected final String PDF_SUFFIX = ".pdf";

    protected final String PNG_SUFFIX = ".png";

    /**
     * 电票查询list
     *
     * @param reqVO
     *            请求参数
     * @return 返回结果
     */
    @Override
    public String listPageElecInvoice(ElecQueryReqVO reqVO) {
        DynamicContextHolder.push(reqVO.getUserInfo().getDbName() + DbConstant.BUSINESS_READ);
        String company = reqVO.getCompany();
        String menuId = reqVO.getMenuId();
        JSONObject result = tabulateRedisService.getTabulateMenu(company, menuId);

        // 查询参数
        Map<String, Object> queryWrapper = createElecQueryWrapper(reqVO);
        PageHelper.startPage(reqVO.getCurr(), reqVO.getSize());
        // 执行查询
        List<TDxInvoice> pageList = signInvoiceScanService.listElecInvoice(queryWrapper);
        PageInfo<TDxInvoice> pageInfo = new PageInfo<>(pageList);
        List<TDxInvoice> resultList = pageInfo.getList();
        // 查询对应图片地址
        Map<String, String> imgMap = queryImgPath(resultList);
        int start = new Long(pageInfo.getStartRow()).intValue();

        // 查询结果封装为view
        List<ElecQueryRespVO> voList = new ArrayList<>();
        for (int i = 0; i < resultList.size(); i++) {
            ElecQueryRespVO vo = convertToQueryRespVO(resultList.get(i), imgMap);
            vo.setXh(start + i);
            voList.add(vo);
        }

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

        // 合计金额and税额，查询并设置
        querySumForInvoice(result, queryWrapper);

        return super.responseResult(result);
    }

    /**
     * @param records
     *            请求参数
     * @return 返回结果
     */
    private Map<String, String> queryImgPath(List<TDxInvoice> records) {
        Map<String, String> imgMap = null;
        if (records.size() == 0) {
            return imgMap;
        }
        imgMap = new HashMap<>(records.size());
        // 取出uuids
        List<String> uuids = records.stream().map(TDxInvoice::getScanId).collect(Collectors.toList());
        // 根据uuids查询对应的
        LambdaQueryWrapper<TDxInvoiceImg> imgQueryWrapper = new LambdaQueryWrapper<>();
        imgQueryWrapper.in(TDxInvoiceImg::getScanId, uuids);
        List<TDxInvoiceImg> imgList = signInvoiceImgService.list(imgQueryWrapper);
        if (imgList == null || imgList.size() == 0) {
            return imgMap;
        }
        imgMap =
            imgList.stream().collect(HashMap::new, (m, v) -> m.put(v.getScanId(), v.getImagePath()), HashMap::putAll);
        return imgMap;
    }

    /**
     * @param result
     *            请求参数
     * @param queryWrapper
     *            请求参数
     */
    private void querySumForInvoice(JSONObject result, Map<String, Object> queryWrapper) {
        // 合计金额 and 合计税额
        QsInvoiceCount sumList = signInvoiceScanService.selectListCount(queryWrapper);
        if (sumList == null) {
            result.put("sumInvoiceAmount", "0");
            result.put("sumTaxAmount", "0");

        } else {
            result.put("sumInvoiceAmount", AmountFormatUtil.fmtMicrometer(
                StringUtils.isNotBlank(sumList.getSumInvoiceAmount()) ? sumList.getSumInvoiceAmount() : "0"));
            result.put("sumTaxAmount", AmountFormatUtil
                .fmtMicrometer(StringUtils.isNotBlank(sumList.getSumTaxAmount()) ? sumList.getSumTaxAmount() : "0"));

        }
    }

    /**
     * 电票查询list转为vo
     *
     * @param record
     *            请求参数
     * @param imgMap
     *            请求参数
     * @return 返回结果
     */
    private ElecQueryRespVO convertToQueryRespVO(TDxInvoice record, Map<String, String> imgMap) {
        ElecQueryRespVO vo = new ElecQueryRespVO();
        vo.setNotes(record.getNotes());
        // 签收日期
        if (record.getQsDate() != null) {
            vo.setQsDate(DateUtils.dateToStr(record.getQsDate()));

        } else {
            vo.setQsDate("");
        }
        // 签收结果
        vo.setQsStatusName(dictdetaServcice.queryDictName(DictConstant.QS_RESULTS, record.getQsStatus()));
        // 签收方式
        vo.setQsTypeName(dictdetaServcice.queryDictName(DictConstant.QS_TYPE, record.getQsType()));
        // 签收人
        vo.setQsUserName(record.getUserName());
        // 发票代码
        vo.setInvoiceCode(record.getInvoiceCode());
        // 发票号码
        vo.setInvoiceNo(record.getInvoiceNo());
        // 开票日期
        if (record.getInvoiceDate() != null) {
            vo.setInvoiceDate(DateUtils.dateToStr(record.getInvoiceDate()));
        } else {
            vo.setInvoiceDate("");
        }
        if (record.getInvoiceAmount() != null) {
            // 金额
            vo.setAmount(AmountFormatUtil.fmtMicrometer(MathUtil.round(record.getInvoiceAmount().toPlainString())));
        }
        if (record.getTaxAmount() != null) {
            // 税额
            vo.setTaxAmount(AmountFormatUtil.fmtMicrometer(MathUtil.round(record.getTaxAmount().toPlainString())));
        }
        // 发票类型
        vo.setInvoiceType(record.getInvoiceType());
        // 主键id，以下为展示字段或者修改使用字段
        vo.setId(record.getId() + "");
        // 购方税号
        vo.setGfsh(record.getGfTaxNo());
        // 销方税号
        vo.setXfsh(record.getXfTaxNo());
        vo.setGfName(record.getGfName());
        vo.setXfName(record.getXfName());
        // 校验码
        vo.setCheckCode(record.getCheckCode());
        // 图片地址
        vo.setImgPath(imgMap.get(record.getScanId()));
        // uuid
        vo.setUuid(record.getUuid());
        vo.setScanId(record.getScanId());
        vo.setBusinessCode(record.getDeptId());
        vo.setBusinessName(record.getDeptName());
        // 操作列表判断 imgState editState delState
        if ("1".equals(record.getQsStatus())) {
            vo.setDelState(false);
            vo.setEditState(false);
        } else {
            vo.setDelState(true);
            vo.setEditState(true);
        }
        vo.setImgState(StringUtils.isNotBlank(vo.getImgPath()));
        return vo;
    }

    /**
     * 电票查询，condition构建
     *
     * @param reqVO
     *            请求参数
     * @return 返回结果
     */
    private Map<String, Object> createElecQueryWrapper(ElecQueryReqVO reqVO) {
        Map<String, Object> pramsMap = new HashMap<>(7);
        pramsMap.put("userName", reqVO.getUserInfo().getUsername());
        // 购方税号
        if (StringUtils.isNotBlank(reqVO.getGfsh()) && !"99".equals(reqVO.getGfsh())) {
            pramsMap.put("gfsh", reqVO.getGfsh());
        }
        // 发票号码
        if (StringUtils.isNotBlank(reqVO.getInvoiceNo())) {
            pramsMap.put("invoiceNo", reqVO.getInvoiceNo());
        }
        // 签收时间
        if (reqVO.getQsStartDate() != null && reqVO.getQsEndDate() != null) {
            pramsMap.put("qsrqq", DateUtils.getMorning(reqVO.getQsStartDate()));
            pramsMap.put("qsrqz", DateUtils.getNight(reqVO.getQsEndDate()));
        }
        // 业务单元
        if (!"99".equals(reqVO.getBusinessCode())) {
            pramsMap.put("businessCode", reqVO.getBusinessCode());

        }
        if (StringUtils.isNotBlank(reqVO.getCompany())) {
            pramsMap.put("company", reqVO.getCompany());
        }
        return pramsMap;
    }

    @Override
    public JSONObject saveUploadElecFile(List<File> pdffiles, List<File> ofdfiles, List<File> xmlFiles, UserInfo userInfo,
                                         String pdfFileName, String tempPath, String businessName, String businessCode, boolean sourseIsZip, String sourceFileName) {
        JSONObject result;
        // 导入结果返回json
        List<Business> business = userInfo.getBusiness();
        String[] titlelist;
        String[] titleprop;
        if (business != null && business.size() > 0) {
            titlelist = new String[] {"签收状态", "签收描述", "发票代码", "发票号码","数电号码", "开票日期", "校验码", "业务单元"};
            titleprop = new String[] {"qsStatus", "qsStatusName", "invoiceCode", "invoiceNo", "eleInvoiceNo","invoiceDate", "jym",
                "businessName"};
        } else {
            titlelist = new String[] {"签收状态", "签收描述", "发票代码", "发票号码","数电号码", "开票日期", "校验码"};
            titleprop = new String[] {"qsStatus", "qsStatusName", "invoiceCode", "invoiceNo", "eleInvoiceNo","invoiceDate", "jym"};
        }
        result = super.setTitleList(titlelist, titleprop);
        // 返回的list
        List<ElecInvoiceRespVO> vos = new ArrayList<>();

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

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

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

        if (xmlFiles != null && xmlFiles.size() > 0) {
            // 解析并保存电票信息
            List<ElecInvoiceRespVO> analysisXmlFile = this.analysisXmlFile(xmlFiles, userInfo, pdfFileName, businessName, businessCode);
            vos.addAll(analysisXmlFile);
        }
        result.put("dataList", vos);
        log.debug("电票导入结果：" + result.toJSONString());

        if(sourseIsZip){
            log.info("源文件是zip，处理zip里的提示消息");
            List<ParseFileError> showMap = dealReturnMsg(vos, sourseIsZip,tempPath ,sourceFileName);
            if(showMap.size()>0){
                result.put("zipMsg", showMap);
                result.put("sourseIsZip", sourseIsZip);
            }
        }

        return super.succResult(result);
    }

    /**
    * @Description 如果源文件是zip的话，处理
    * @Author wangruwei
    * @Date 2023/8/28 14:00
    **/
    private List<ParseFileError> dealReturnMsg(List<ElecInvoiceRespVO> vos, boolean sourseIsZip, String tempPath, String sourceFileName) {
        sourceFileName = sourceFileName.substring(0, sourceFileName.indexOf("."));
        //筛选所有文件，并按所属位置分组
        LinkedHashMap<String, List<ElecInvoiceRespVO>> collect = vos.stream()
                //.filter(e -> e.getReadPdfSuccess() == false)
                .sorted(Comparator.comparing(item->item.getFileParentPath().length()))
                .collect(Collectors.groupingBy(ElecInvoiceRespVO::getFileParentPath, LinkedHashMap::new, Collectors.toList()));
        log.info("按文件夹分组后的数据结构:{}",JSON.toJSONString(collect));
        //给前端展示的右侧数据结构
        List<ParseFileError> showlist = new LinkedList();
        tempPath = formatePathStr(tempPath);
        for (Map.Entry<String,  List<ElecInvoiceRespVO>> entry : collect.entrySet()) {
            String key = StringUtils.isBlank(entry.getKey())?"":(formatePathStr(entry.getKey()) + "-");
            //key改为目录
            key = key.replace(tempPath, "").replace("-", "");
            List<ElecInvoiceRespVO> value = entry.getValue();

            ParseFileError parseFileError = new ParseFileError();
            String showPath = StringUtils.isBlank(key)?sourceFileName:(sourceFileName + File.separator + key);
            parseFileError.setShowPath(showPath);
            parseFileError.setFileList(value);
            showlist.add(parseFileError);
        }
        log.info("替换key后最终返回的结构体:{}",JSON.toJSONString(showlist));
        return showlist;
    }

    public static String formatePathStr(String str){
        return str.replace("\\","/").replace("/", "-");
    }

    @Data
    public static class ParseFileError {
        //文件所处目录
        private String showPath;
        //文件名
        //目录下的每一个文件处理结果
        private List<ElecInvoiceRespVO> fileList;
    }

    /**
    * @Description 解析xml文件
    * @Author wangruwei
    * @Date 2023/8/14 16:53
    **/
    private List<ElecInvoiceRespVO> analysisXmlFile(List<File> xmlFiles, UserInfo user, String pdfFileName, String businessName, String businessCode) {

        List<ElecInvoiceRespVO> invoices = new ArrayList<>();
        // 图片存储路径
        String uploadImg = "";
        // 连接远程ftp服务器，上传xml
        PdfInvoiceModel pdfInvoiceModel;
        try {
            // 连接远程服务器
            for (File file : xmlFiles) {
                String pdfFilePath = "";
                // 解析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 {
                    String xmlStr = cn.hutool.core.io.FileUtil.readUtf8String(file);
                    log.info("xml内容为:{}",xmlStr);
                    //生成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 = localPathDefault + 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);
                    }

                    pdfInvoiceModel = PdfUtil.pdfAnalysis(new File(pdfFilePath));

                    fileModel = fileService.uploadFile(sourceFolder + file.getName(), file.getPath());
                } catch (Exception e) {
                    log.info("处理发票解析失败:{}",e);
                    // 处理发票解析失败
                    ElecInvoiceRespVO expectionPdf = new ElecInvoiceRespVO();
                    if (pdfFileName.endsWith("xml")) {
                        expectionPdf.setPdfName(pdfFileName);
                    }
                    expectionPdf.setFilePath(file.getPath());
                    expectionPdf.setFileParentPath(file.getParent());
                    expectionPdf.setReadPdfSuccess(false);
                    expectionPdf.setReadPdfSuccessDesc(file.getName()+"解析发票失败");
                    expectionPdf.setBusinessCode(businessCode);
                    expectionPdf.setBusinessName(businessName);
                    expectionPdf.setCompany(user.getCompany());
                    //失败的不返回
                    invoices.add(expectionPdf);
                    continue;
                }finally {
                    if(StringUtils.isNotBlank(pdfFilePath)){
                        FileUtil.deleteFile(pdfFilePath);
                    }
                }

                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());
                // 获取解析的发票信息
                ElecInvoiceRespVO 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.setBusinessCode(businessCode);
                invoiceEntity.setBusinessName(businessName);
                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");
                }
                //数电号码，切割代码号码
                if(FplxEnum.QDPP.getFplxDm().equals(invoiceEntity.getInvoiceType()) || FplxEnum.QDZZP.getFplxDm().equals(invoiceEntity.getInvoiceType())){
                    String invoiceNo = invoiceEntity.getInvoiceNo();
                    invoiceEntity.setEleInvoiceNo(invoiceNo);
                    //invoiceEntity.setInvoiceCode(invoiceNo.substring(0,12));
                    //invoiceEntity.setInvoiceNo(invoiceNo.substring(12,20));
                }
                // 签收查验电子发票并保存相应数据到数据库
                Object[] resultAry = saveElecInvoice(invoiceEntity, user, pathMap);
                // 查验结果构建
                invoiceEntity = convertResult(invoiceEntity, resultAry, fileModelPng.getFilePath(), true,user);
                //如果签收成功，更新电票源文件标志
                if ((Boolean) resultAry[0]) {
                    log.info("签收成功，更新抵账表电票XML源文件标志");
                    gxdzXmlFlag(invoiceEntity.getUuid(),"4");
                }

                invoiceEntity.setReadPdfSuccess(true);
                invoiceEntity.setReadPdfSuccessDesc(file.getName()+"解析xml成功");
                // 设置序列号
                invoiceEntity.setScanId(scanId);
                /*if (pdfFileName.endsWith("pdf")) {
                    invoiceEntity.setPdfName(pdfFileName);
                } else {
                    invoiceEntity.setPdfName(file.getName());
                }*/
                invoiceEntity.setFilePath(file.getPath());
                invoiceEntity.setFileParentPath(file.getParent());
                invoices.add(invoiceEntity);
            }

        } catch (Exception e) {
           log.info("业务处理异常：{}", e);
            log.debug("-----------------上传xml异常------------------");
        }
        return invoices;
    }


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

    private List<ElecInvoiceRespVO> analysisElectronFile(List<File> files, UserInfo user, String pdfFileName,
        String businessName, String businessCode) {

        List<ElecInvoiceRespVO> 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) {
                        // 处理发票解析失败
                        ElecInvoiceRespVO expectionPdf = new ElecInvoiceRespVO();
                        if (pdfFileName.endsWith("pdf")) {
                            expectionPdf.setPdfName(pdfFileName);
                        }
                        expectionPdf.setReadPdfSuccess(false);
                        expectionPdf.setReadPdfSuccessDesc("解析发票失败");
                        expectionPdf.setFilePath(file.getPath());
                        expectionPdf.setFileParentPath(file.getParent());
                        expectionPdf.setBusinessCode(businessCode);
                        expectionPdf.setBusinessName(businessName);
                        invoices.add(expectionPdf);
                        continue;
                    }
                } catch (Exception e) {
                    // 处理发票解析失败
                    ElecInvoiceRespVO expectionPdf = new ElecInvoiceRespVO();
                    if (pdfFileName.endsWith("pdf")) {
                        expectionPdf.setPdfName(pdfFileName);
                    }
                    expectionPdf.setReadPdfSuccess(false);
                    expectionPdf.setReadPdfSuccessDesc("解析发票失败");
                    expectionPdf.setBusinessCode(businessCode);
                    expectionPdf.setFilePath(file.getPath());
                    expectionPdf.setFileParentPath(file.getParent());
                    expectionPdf.setBusinessName(businessName);
                    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());
                // 获取解析的发票信息
                ElecInvoiceRespVO 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.setBusinessCode(businessCode);
                invoiceEntity.setBusinessName(businessName);
                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");
                }
                invoiceEntity.setReadPdfSuccess(true);
                if("09".equals(pdfInvoiceModel.getInvoiceType())){
                    invoiceEntity.setInvoiceType("31");
                }
                //数电号码，切割代码号码
                if(FplxEnum.QDPP.getFplxDm().equals(invoiceEntity.getInvoiceType()) || FplxEnum.QDZZP.getFplxDm().equals(invoiceEntity.getInvoiceType())){
                    String invoiceNo = invoiceEntity.getInvoiceNo();
                    invoiceEntity.setEleInvoiceNo(invoiceNo);
                    //invoiceEntity.setInvoiceCode(invoiceNo.substring(0,12));
                    //invoiceEntity.setInvoiceNo(invoiceNo.substring(12,20));
                }
                log.info("签收查验电子发票并保存相应数据到数据库");
                Object[] resultAry = saveElecInvoice(invoiceEntity, user, pathMap);
                // 查验结果构建
                invoiceEntity = convertResult(invoiceEntity, resultAry, fileModelPng.getFilePath(), true,user);

                //如果签收成功，更新电票源文件标志
                if ((Boolean) resultAry[0]) {
                    log.info("签收成功，更新抵账表电票PDF源文件标志");
                    gxdzXmlFlag(invoiceEntity.getUuid(),"5");
                }

                invoiceEntity.setReadPdfSuccessDesc("解析pdf成功");
                // 设置序列号
                invoiceEntity.setScanId(scanId);
                if (pdfFileName.endsWith("pdf")) {
                    invoiceEntity.setPdfName(pdfFileName);
                } else {
                    invoiceEntity.setPdfName(file.getName());
                }
                invoiceEntity.setReadPdfSuccess(true);
                invoiceEntity.setFilePath(file.getPath());
                invoiceEntity.setFileParentPath(file.getParent());
                invoices.add(invoiceEntity);
            }
            // 上传图片

        } catch (Exception e) {
           log.info("业务处理异常：{}", e);
            log.debug("-----------------上传图片异常------------------");
        }
        return invoices;
    }

    private void gxdzXmlFlag(String uuid, String xmlFlag) {
        TDxRecordInvoice invoiceInfo = signRecordInvoiceDao.selectOne(new QueryWrapper<TDxRecordInvoice>().select("xml_flag").eq("uuid", uuid));
        signRecordInvoiceDao.update(null
                , new UpdateWrapper<TDxRecordInvoice>()
                        .set("xml_flag", CommonUtil.addXmlFlag(invoiceInfo.getXmlFlag(),xmlFlag))
                        .eq("uuid", uuid));
    }

    /**
     * 获取电票的实体
     *
     * @param model
     *            电票文件解析后的数据
     * @param scanId
     *            扫描图片唯一识别id
     * @param user
     *            当前登录人信息
     * @return 电票的实体
     */
    private ElecInvoiceRespVO getElectronInvoice(PdfInvoiceModel model, String scanId, UserInfo user) {
        ElecInvoiceRespVO invoiceEntity = new ElecInvoiceRespVO();
        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;
    }

    /**
     * 创建文件夹
     */
    @Override
    public void createFileDir(String tempPath) {
        // 创建临时存储文件夹
        File tempFileDir = new File(tempPath);
        if (!tempFileDir.exists()) {
            tempFileDir.mkdirs();
        }
        // 创建压缩包存储文件夹
        File zipFileDir = new File(fileService.getLocalPathDefault());
        if (!zipFileDir.exists()) {
            zipFileDir.mkdirs();
        }
    }

    /**
     * 获取上传文件的名称
     *
     * @param filename
     *            文件的原始名称，有可能包含路径
     * @return 返回结果
     */
    @Override
    public String getOriginalFilename(String filename) {

        int unixSep = filename.lastIndexOf("/");
        int winSep = filename.lastIndexOf("\\");
        int pos = Math.max(winSep, unixSep);
        return pos != -1 ? filename.substring(pos + 1) : filename;

    }

    /**
     * 电子发票手工录入保存
     *
     * @param reqVO
     *            请求参数
     * @param userInfo
     *            用户信息
     * @return 返回结果
     */
    @Override
    public JSONObject saveManualElec(ElecInvoiceRespVO reqVO, UserInfo userInfo) {
        JSONObject result;
        // 导入结果返回json
        if (StringUtils.isNotBlank(reqVO.getBusinessCode()) && !"99".equals(reqVO.getBusinessCode())) {
            String[] titlelist = {"签收状态", "签收描述", "发票代码", "发票号码", "开票日期", "校验码", "业务单元"};
            String[] titleprop = {"qsStatus", "qsStatusName", "invoiceCode", "invoiceNo", "invoiceDate", "jym",
                "businessName", "imgState", "editState", "delState"};
            result = super.setTitleList(titlelist, titleprop);
        } else {
            String[] titlelist = {"签收状态", "签收描述", "发票代码", "发票号码", "开票日期", "校验码"};
            String[] titleprop = {"qsStatus", "qsStatusName", "invoiceCode", "invoiceNo", "invoiceDate", "jym",
                "imgState", "editState", "delState"};
            result = super.setTitleList(titlelist, titleprop);
        }
        boolean imgflg = true;
        // 扫描图片唯一识别id
        if (StringUtils.isBlank(reqVO.getScanId())) {
            imgflg = false;
            String scanId = UUID.randomUUID().toString().replace("-", "");
            reqVO.setScanId(scanId);
        }
        //如果票种是空，看抵账库是否有，有则赋值，没有继续往下走
        if(StringUtils.isBlank(reqVO.getInvoiceType())){
            DynamicContextHolder.push("business" + DbConstant.BUSINESS_READ);
            QueryWrapper<TDxRecordInvoice> invoiceWrapper = new QueryWrapper<>();
            invoiceWrapper.lambda().eq(TDxRecordInvoice::getUuid, (StringUtils.isBlank(reqVO.getInvoiceCode())?"":reqVO.getInvoiceCode())+reqVO.getInvoiceNo());
            TDxRecordInvoice recordInvoice = super.getOne(invoiceWrapper);
            if(ObjectUtil.isNotEmpty(recordInvoice)){
                reqVO.setInvoiceType(recordInvoice.getInvoiceType());
            }
        }
        // 签收查验电子发票并保存相应数据到数据库
        Object[] resultAry = saveElecInvoice(reqVO, userInfo, null);
        // 查验结果构建
        ElecInvoiceRespVO respVO = convertResult(reqVO, resultAry, null, imgflg,userInfo);
        // 返回导入结果
        result.put("dataList", respVO);
        return super.succResult(result);
    }

    /**
     * 根据uuid获取电票图片地址
     *
     * @param uuid
     *            uuid
     * @param userInfo
     *            用户信息
     * @return 返回结果
     */
    @Override
    public String getImgByUuid(String uuid, UserInfo userInfo, String localPath) {
        DynamicContextHolder.push(userInfo.getDbName() + DbConstant.BUSINESS_READ);
        String localZipName;
        File localZipFile;
        try {
            TDxInvoiceImg invoiceImg = signInvoiceImgService.selectByUuid(uuid);
            if (invoiceImg == null || StringUtils.isBlank(invoiceImg.getImagePath())) {
                return null;
            }
            // 获取图片在ftp上的全路径
            String imageRemotePath = invoiceImg.getImagePath();
            File file = new File(imageRemotePath);
            String fileName = file.getName();

            log.debug("--- localPath=" + localPath);
            log.debug("---- fileName=" + fileName);
            FileModel fileModel = fileService.downFile(imageRemotePath, localPath + fileName);
            if (!OssReturnConfig.SUCCESS.equals(fileModel.getCode())) {
                log.debug("------ 文件下载失败！----");
                return null;
            }
            // ftp下载后的zip路径
            List<String> pathList = new ArrayList<>();
            localZipName = localPath + fileName;
            localZipFile = new File(localZipName);
            if (fileName.contains(".zip")) {
                // 解压缩到zip当前文件夹
                pathList = FileUtils.unZip(localZipFile, localPath);
            } else {
                pathList.add(localZipName);
            }
            boolean reName = reName(pathList.get(0), userInfo.getUsername() + ".jpeg");
            if (reName) {
                return localPath + userInfo.getUsername() + ".jpeg";
            } else {
                return pathList.get(0);
            }
        } catch (Exception e) {
           log.info("业务处理异常：{}", e);
            return "";
        }

    }

    @Override
    public boolean reName(String path, String newname) {// 文件重命名
        File file = new File(path);
        if (file.exists()) {
            // 创建新名字的抽象文件
            File newfile = new File(file.getParent() + "/" + newname);
            if (file.renameTo(newfile)) {
                log.info("重命名成功！");
                return true;
            } else {
                log.info("重命名失败！新文件名已存在");
                return false;
            }
        } else {
            log.info("重命名文件不存在！");
            return false;
        }

    }

    /**
     * 构建 查验结果返回view ary[0] ：true为签收成功 ，false为签收失败 ary[1] ：签收描述 ary[2] ：发票类型
     *
     * @param reqVO
     *            请求参数
     * @param resultAry
     *            请求参数
     * @param fileSrc
     *            文件夹
     * @return 返回结果
     */
    private ElecInvoiceRespVO convertResult(ElecInvoiceRespVO reqVO, Object[] resultAry, String fileSrc,
        boolean imageflg,UserInfo userInfo) {
        boolean result = (Boolean)resultAry[0];
        String desc = (String)resultAry[1];
        String fpType = "";
        DynamicContextHolder.push(userInfo.getDbName() + DbConstant.BUSINESS_READ);
        String uuid = (StringUtils.isBlank(reqVO.getInvoiceCode())?"":reqVO.getInvoiceCode())+reqVO.getInvoiceNo();
        TDxInvoice scanInvoice = signInvoiceScanService.queryByUuid(uuid, userInfo.getDbName());
        if(ObjectUtil.isEmpty(scanInvoice)||StringUtils.isBlank(scanInvoice.getInvoiceType())){
            // 根据发票代码识别发票类型
            InvoiceUtil iu = new InvoiceUtil(reqVO.getInvoiceCode());
             fpType = iu.getFplxdm();
        }else {
            fpType = scanInvoice.getInvoiceType();
        }
        ElecInvoiceRespVO respVO = new ElecInvoiceRespVO();
        // 发票代码
        respVO.setInvoiceCode(reqVO.getInvoiceCode());
        // 发票号码
        respVO.setInvoiceNo(reqVO.getInvoiceNo());
        if(StringUtils.isNotBlank(reqVO.getEleInvoiceNo())){
            respVO.setEleInvoiceNo(reqVO.getEleInvoiceNo());
        }
        if(StringUtils.isNotBlank(reqVO.getInvoiceNo())&&reqVO.getInvoiceNo().length()==20){
            respVO.setEleInvoiceNo(reqVO.getInvoiceNo());
            respVO.setInvoiceCode(reqVO.getInvoiceNo().substring(0,12));
            respVO.setInvoiceNo(reqVO.getInvoiceNo().substring(12,20));
        }
        // 开票日期
        if (reqVO.getInvoiceDate().length() == 8) {
            String date = reqVO.getInvoiceDate().substring(0, 4) + "-" + reqVO.getInvoiceDate().substring(4, 6) + "-"
                + reqVO.getInvoiceDate().substring(6);
            respVO.setInvoiceDate(date);
        } else {

            respVO.setInvoiceDate(reqVO.getInvoiceDate());
        }
        // 校验码
        respVO.setCheckCode(reqVO.getCheckCode());
        respVO.setInvoiceAmount(reqVO.getInvoiceAmount());
        // 签收结果
        if (result) {
            respVO.setQsStatusName(FpqsjgEnum.YQS.getQsjgMcSmb(FpqsjgEnum.YQS.getIndex()));
        } else {
            respVO.setQsStatusName(FpqsjgEnum.WQS.getQsjgMcSmb(FpqsjgEnum.WQS.getIndex()));
        }
        // 签收描述
        respVO.setQsDesc(desc);
        respVO.setInvoiceType(fpType);
        // 图片路径
        respVO.setImgPath(fileSrc);
        // uuid
        respVO.setUuid(uuid);
        respVO.setBusinessName(reqVO.getBusinessName());
        respVO.setBusinessCode(reqVO.getBusinessCode());
        respVO.setScanId(reqVO.getScanId());
        // 操作列表判断 imgState editState delState
        if (!result) {
            respVO.setDelState(true);
            respVO.setEditState(true);
        } else {
            respVO.setDelState(false);
            respVO.setEditState(false);
        }
        if (StringUtils.isNotBlank(respVO.getImgPath())) {
            respVO.setImgState(true);
        } else {
            respVO.setImgState(imageflg);
        }
        if(StringUtils.isNotBlank(reqVO.getTotalAmount())){
            respVO.setTotalAmount(reqVO.getTotalAmount());
        }
        return respVO;
    }

    /**
     * 电子发票签收 统一入口
     *
     * @param reqVO
     *            请求参数
     * @param userInfo
     *            用户信息
     * @param invoiceImgMap
     *            图片信息
     * @return true 为查验成功并保存入库，false为失败
     */
    private Object[] saveElecInvoice(ElecInvoiceRespVO reqVO, UserInfo userInfo, Map<String, String> invoiceImgMap) {
        Object[] result = new Object[3];
        // 根据发票代码识别发票类型
        String fpType = reqVO.getInvoiceType();

        if (fpType == null) {
            result[0] = false;
            result[1] = "发票类型识别失败！";
            return result;
        }

        if (invoiceImgMap != null) {

            // 图片地址保存
            DynamicContextHolder.push(userInfo.getDbName() + DbConstant.BUSINESS_WRITE);
            saveInvoiceImg(invoiceImgMap);
        }
        // 校验数据拼装
        Map<String, String> pramsMap = new HashMap<String, String>();
        pramsMap.put("invoiceCode", reqVO.getInvoiceCode());
        pramsMap.put("invoiceNo", reqVO.getInvoiceNo());
        String invoiceNo = reqVO.getInvoiceNo();

        if (StringUtils.isNotBlank(reqVO.getInvoiceAmount())) {
            pramsMap.put("invoiceAmount", reqVO.getInvoiceAmount());
        }
        if (StringUtils.isNotBlank(reqVO.getTotalAmount())) {
            pramsMap.put("totalAmount", reqVO.getTotalAmount());
        }

        //如果发票号码为20位，票种为31(在前面方法识别回来后全电票为09，统一转换为31)
        if(invoiceNo.length()==20&&"31".equals(reqVO.getInvoiceType())){
            //如果价税合计有值，赋值查验的钱为价税合计
            if (StringUtils.isNotBlank(reqVO.getTotalAmount())) {
                pramsMap.put("invoiceAmount", reqVO.getTotalAmount());
            }
        }

        if(StringUtils.isNotBlank(reqVO.getInvoiceNo())&&reqVO.getInvoiceNo().length()==20){
            pramsMap.put("eleInvoiceNo", reqVO.getInvoiceNo());
            pramsMap.put("invoiceCode", reqVO.getInvoiceNo().substring(0,12));
            pramsMap.put("invoiceNo", reqVO.getInvoiceNo().substring(12,20));
        }
        pramsMap.put("invoiceDate", reqVO.getInvoiceDate());
        if (StringUtils.isNotBlank(reqVO.getCheckCode())) {
            pramsMap.put("checkCode", reqVO.getCheckCode());
        }

        // if (invoiceImgMap != null) {
        // // pdf上传添加扫描ID
        // pramsMap.put("scanId", reqVO.getScanId());
        // }
        if (StringUtils.isNotBlank(reqVO.getScanId())) {
            pramsMap.put("scanId", reqVO.getScanId());
        }
        pramsMap.put("businessCode", reqVO.getBusinessCode());
        pramsMap.put("businessName", reqVO.getBusinessName());
        pramsMap.put("company", reqVO.getCompany());
        if (StringUtils.isNotBlank(reqVO.getTaxAmount())) {
            pramsMap.put("taxAmount", reqVO.getTaxAmount());
        }
        if (StringUtils.isNotBlank(reqVO.getGfName())) {
            pramsMap.put("gfName", reqVO.getGfName());
        }
        if (StringUtils.isNotBlank(reqVO.getGfsh())) {
            pramsMap.put("gfsh", reqVO.getGfsh());
        }
        if (StringUtils.isNotBlank(reqVO.getXfName())) {
            pramsMap.put("xfName", reqVO.getXfName());
        }
        if (StringUtils.isNotBlank(reqVO.getXfsh())) {
            pramsMap.put("xfsh", reqVO.getXfsh());
        }

        //从抵账库获取种类代码
        DynamicContextHolder.push(userInfo.getDbName() + DbConstant.BUSINESS_READ);
        QueryWrapper<TDxRecordInvoice> invoiceWrapper = new QueryWrapper<>();
        invoiceWrapper.lambda().eq(TDxRecordInvoice::getUuid, (StringUtils.isEmpty(pramsMap.get("invoiceCode"))?"":pramsMap.get("invoiceCode"))+pramsMap.get("invoiceNo"));
        TDxRecordInvoice selrecordInvoice = super.getOne(invoiceWrapper);
        if(ObjectUtil.isNotNull(selrecordInvoice)){
            fpType = selrecordInvoice.getInvoiceType();
            result[0] = true;
        }else{
            result[0] = false;
        }

        JSONObject jsonObject = null;
        if(ObjectUtil.isNull(selrecordInvoice)&&invoiceNo.length()==20){
            log.info("抵账库不存在此发票且是全电专普，走查验验证票种");
            result[0] = true;
            jsonObject = fpqsService.checkInvoice(pramsMap, userInfo, QsfsEnum.PDFQS.getQsfsDm(), fpType);
            String resultCode = jsonObject.getString("resultCode");
            if (jsonObject.containsKey("returnCode")) {
                result[0] = false;
                result[1] = jsonObject.getString("returnMessage");
                return result;
            }
            if (!"0001".equals(resultCode)) {
                result[0] = false;
                result[1] = jsonObject.getString("resultTip");
                return result;
            }
            if(StringUtils.isNotBlank(jsonObject.getString("invoiceType"))){
                fpType = jsonObject.getString("invoiceType");
            }
        }
      
        // 通行费或电子专票对比底账表签收
        if (FplxEnum.TXF.getFplxDm().equals(fpType) || FplxEnum.DZZP.getFplxDm().equals(fpType)
                //|| FplxEnum.TLKP.getFplxDm().equals(fpType)
                //|| FplxEnum.HKDZFP.getFplxDm().equals(fpType)
                || FplxEnum.ZZJDC.getFplxDm().equals(fpType)|| FplxEnum.ZZESC.getFplxDm().equals(fpType)
                || FplxEnum.SDFP_JDCTYXSFP.getFplxDm().equals(fpType)|| FplxEnum.ESCDZ.getFplxDm().equals(fpType)
                || (FplxEnum.QDZZP.getFplxDm().equals(fpType) &&(Boolean) result[0])) {
            return fpqsService.zpSaveInvoice(pramsMap, userInfo, QsfsEnum.PDFQS.getQsfsDm(), fpType,jsonObject);
        }
        if (FplxEnum.DZP.getFplxDm().equals(fpType)) {
            // 电子票查验签收
            return fpqsService.dzpSaveInvoice(pramsMap, userInfo, QsfsEnum.PDFQS.getQsfsDm(), fpType);
        }
        //全电普票
        if(FplxEnum.QDPP.getFplxDm().equals(fpType) && (Boolean) result[0]){
            log.info("全电普票签收");
            if(ObjectUtil.isNotNull(selrecordInvoice)){
                log.info("底账存在，用抵账库信息去签收");
                return fpqsService.zpSaveInvoice(pramsMap, userInfo, QsfsEnum.PDFQS.getQsfsDm(), fpType,jsonObject);
            }else{
                log.info("底账没有，查验成功，开始签收");
                return fpqsService.qdSaveInvoice(pramsMap, userInfo, QsfsEnum.PDFQS.getQsfsDm(), fpType,jsonObject);
            }

        }

        result[0] = false;
        result[1] = "发票类型错误！";

        return result;
    }


    /**
     * 保存图片地址到数据库
     *
     * @param invoiceImgMap
     *            图片参数
     */
    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);

    }

    @Override
    public boolean deleteElec(String scanId, String dbName) {
        DynamicContextHolder.push(dbName + DbConstant.BUSINESS_WRITE);
        try {
            // 根据scanid 删除数据
            baseMapper.deleteBatchInvoice(scanId);
            baseMapper.deleteBatchImg(scanId);
            return true;
        } catch (Exception e) {
           log.info("业务处理异常：{}", e);
            return false;
        }
    }

    private List<ElecInvoiceRespVO> analysisOfdFile(List<File> files, UserInfo user, String tempPath,
        String businessName, String businessCode) {

        List<ElecInvoiceRespVO> 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 + "/";
                this.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);
                this.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);
                // 获取解析的发票信息
                ElecInvoiceRespVO invoiceEntity = new ElecInvoiceRespVO();
                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());

                invoiceEntity.setInvoiceDate(ofdInvoice.getIssueDate());
                invoiceEntity.setInvoiceCode(ofdInvoice.getInvoiceCode());
                invoiceEntity.setInvoiceNo(ofdInvoice.getInvoiceNo());
                if(StringUtils.isNotBlank(ofdInvoice.getInvoiceNo())&&ofdInvoice.getInvoiceNo().length()==20){
                    invoiceEntity.setEleInvoiceNo(ofdInvoice.getInvoiceNo());
                    //invoiceEntity.setInvoiceCode(ofdInvoice.getInvoiceNo().substring(0,12));
                    //invoiceEntity.setInvoiceNo(ofdInvoice.getInvoiceNo().substring(12,20));
                }
                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());
                if (StringUtils.isNotBlank(checkCode)) {
                    invoiceEntity.setCheckCode(checkCode.substring(checkCode.length() - 6));
                } else {
                    invoiceEntity.setCheckCode(null);
                }

                invoiceEntity.setBusinessCode(businessCode);
                invoiceEntity.setBusinessName(businessName);
                invoiceEntity.setCompany(user.getCompany());
                invoiceEntity.setInvoiceAmount(ofdInvoice.getTaxExclusiveTotalAmount());
                invoiceEntity.setTaxAmount(ofdInvoice.getTaxTotalAmount());
                invoiceEntity.setTotalAmount(ofdInvoice.getTaxInclusiveTotalAmount());
                invoiceEntity.setGfsh(ofdInvoice.getBuyerTaxId());
                invoiceEntity.setGfName(ofdInvoice.getBuyerName());
                invoiceEntity.setXfName(ofdInvoice.getSellerName());
                invoiceEntity.setXfsh(ofdInvoice.getSellerTaxId());
                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");
                }
                // 签收查验电子发票并保存相应数据到数据库
                Object[] resultAry = saveElecInvoice(invoiceEntity, user, pathMap);
                // 查验结果构建
                invoiceEntity = convertResult(invoiceEntity, resultAry, fileModelPng.getFilePath(), true,user);

                //如果签收成功，更新电票源文件标志
                if ((Boolean) resultAry[0]) {
                    log.info("签收成功，更新抵账表电票OFD源文件标志");
                    gxdzXmlFlag(invoiceEntity.getUuid(),"6");
                }

                invoiceEntity.setReadPdfSuccessDesc("解析ofd成功");
                invoiceEntity.setPdfName(fileName);
                invoiceEntity.setFilePath(file.getPath());
                invoiceEntity.setFileParentPath(file.getParent());
                invoiceEntity.setReadPdfSuccess(true);
                invoices.add(invoiceEntity);
                // 删除临时文件
            }
            FileUtils.deleteDir(new File(tempPath));
            // 上传图片

        } catch (Exception e) {
           log.info("业务处理异常：{}", e);
        }
        return invoices;
    }

    /**
    * @param scanId
    * @param imgOrFile
    * @param uuid
    * @param downloadType
    * @param pageType       0进项   1销项
    * @param userInfo
    * @param localPath
    * @Return java.lang.Object
    * @Author wangruwei
    * @Date 2024/5/23 9:26
    **/
    @Override
    public Object getFileByScanId(String scanId, String imgOrFile,String uuid,String downloadType,String pageType ,UserInfo userInfo, String localPath) {
        DynamicContextHolder.push(userInfo.getDbName() + DbConstant.BUSINESS_READ);
        JSONObject json = new JSONObject();
        JSONArray imgList = null;
        String file = "";
        String fileType = "1";
        try {
            // 图片
            TDxInvoiceImg invoiceImg = signInvoiceImgService.selectByUuid(scanId);
            if ("1".equals(imgOrFile)) {
                if (invoiceImg == null) {
                    return ResponseEntity.ok(R.error("该发票没有图片！"));
                }
                imgList = new JSONArray();
                // 下载文件，返回base64文件流
                String img = download(invoiceImg.getImagePath(), localPath);
                if (StringUtils.isNotBlank(img)) {
                    imgList.add(img);
                }

            }
            // 原始凭证文件单张
            if ("2".equals(imgOrFile)) {
                if (invoiceImg == null || StringUtils.isBlank(invoiceImg.getImage())) {
                    return ResponseEntity.ok(R.error("该发票没有原始凭证！"));
                }
                // 获取文件类型
                String fileName = invoiceImg.getImage();
                String fileNameType = fileName.substring(fileName.lastIndexOf("."));
                if (".pdf".equals(fileNameType) || ".PDF".equals(fileNameType)) {
                    fileType = "2";
                }
                if (".ofd".equals(fileNameType) || ".OFD".equals(fileNameType)) {
                    fileType = "3";
                }
                // 下载文件，返回base64文件流
                file = download(invoiceImg.getImage(), localPath);
            }

            //电子源文件下载
            if ("3".equals(imgOrFile)) {
                //通过uuid去查找
                TDxRecordInvoice tDxRecordInvoice = new TDxRecordInvoice();
                //0进项  1销项
                if("0".equals(pageType)){
                    tDxRecordInvoice = signRecordInvoiceDao.selectOne(new LambdaQueryWrapper<TDxRecordInvoice>().eq(TDxRecordInvoice::getUuid,uuid));
                }else{
                    TdxSaleRecordInvoiceEntity tdxSaleRecordInvoice = tdxSaleRecordInvoiceDao.selectOne(new LambdaQueryWrapper<TdxSaleRecordInvoiceEntity>().eq(TdxSaleRecordInvoiceEntity::getUuid, uuid));
                    BeanUtils.copyProperties(tdxSaleRecordInvoice, tDxRecordInvoice);
                }

                String xmlFlag = tDxRecordInvoice.getXmlFlag();
                log.info("当前数据xml_flag:{}",xmlFlag);

                //根据传进来的downloadType，去判断应该下载哪一个。传来的格式是  1@1  前面代表发票类型 1xml 2pdf  3ofd  后面0代表税局，1代表自己上传的
                //销项票的下载 后面参数只会是0
                String[] typeSplit = downloadType.split("@");
                if("1".equals(typeSplit[1])){
                    log.info("下载自己上传的文件invoice_img表");
                    TDxInvoiceImg tDxInvoiceImg = signInvoiceImgDao.selectOne(new LambdaQueryWrapper<TDxInvoiceImg>().eq(TDxInvoiceImg::getScanId, tDxRecordInvoice.getScanId()));
                    if(ObjectUtils.isEmpty(tDxInvoiceImg)){
                        log.info("未找到自己上传的图片数据");
                    }else{
                        file = download(tDxInvoiceImg.getImage(), localPath);
                        String fileNameType = tDxInvoiceImg.getImage().substring(tDxInvoiceImg.getImage().lastIndexOf("."));
                        if (".xml".equals(fileNameType) || ".XML".equals(fileNameType)) {
                            fileType = "1";
                        }
                        if (".pdf".equals(fileNameType) || ".PDF".equals(fileNameType)) {
                            fileType = "2";
                        }
                        if (".ofd".equals(fileNameType) || ".OFD".equals(fileNameType)) {
                            fileType = "3";
                        }
                    }
                }else{
                    log.info("查询电子税局下载源文件表invoice_file");
                    TDxInvoiceFileEntity tDxInvoiceFileEntity = tdxInvoiceFileDao.selectOne(new LambdaQueryWrapper<TDxInvoiceFileEntity>().eq(TDxInvoiceFileEntity::getUuid, uuid));
                    if(ObjectUtils.isEmpty(tDxInvoiceFileEntity)){
                        log.info("未找到电子税局下载源文件");
                    }else{
                        if("1".equals(typeSplit[0])){
                            file = download(tDxInvoiceFileEntity.getXmlPath(), localPath);
                            fileType = "1";
                        }
                        if("2".equals(typeSplit[0])){
                            file = download(tDxInvoiceFileEntity.getPdfPath(), localPath);
                            fileType = "2";
                        }
                        if("3".equals(typeSplit[0])){
                            file = download(tDxInvoiceFileEntity.getOfdPath(), localPath);
                            fileType = "3";
                        }
                    }

                }

            }

            json.put("imgList", imgList);
            json.put("file", file);
            json.put("fileType", fileType);
        } catch (Exception e) {
            // 统一设置操作异常标识
            json = super.errorResult(e);
            return ResponseEntity.ok(json);
        }
        return ResponseEntity.ok(R.ok().put("data", super.responseResult(json)));
    }

    public String download(String localPath, String downloadPath) {
        try {
            // 获取图片/文件在ftp上的全路径
            File file = new File(localPath);
            String fileName = file.getName();
            log.debug("--- localPath=" + localPath);
            log.debug("---- fileName=" + fileName);
            FileModel fileModel = fileService.downFile(localPath, downloadPath + fileName);
            if (!OssReturnConfig.SUCCESS.equals(fileModel.getCode())) {
                log.debug("------ 文件下载失败！----");
                return "";
            }
            return FileUtil.fileToBase64(new File(downloadPath + fileName));

        } catch (Exception e) {
            return "";
        } finally {
            // 删除临时文件
            FileUtils.deleteDir(new File(localPath));
        }

    }
    @Override
    public boolean deleteElecByID(String id, String dbName) {
        DynamicContextHolder.push(dbName + DbConstant.BUSINESS_WRITE);
        try {
            // 根据id查询发票scanID
            TDxInvoice tDxInvoice = baseMapper.selectInvoice(id);
            baseMapper.deleteInvoiceByid(id);
            if(tDxInvoice!=null){
                if(StringUtils.isNotBlank(tDxInvoice.getScanId())){
                    baseMapper.deleteBatchImg(tDxInvoice.getScanId());
                }
            }
            return true;
        } catch (Exception e) {
           log.info("业务处理异常：{}", e);
            return false;
        }
    }
}
