package com.dxhy.erp.service.impl;

import java.io.File;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.dxhy.erp.service.CustomsSignService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dxhy.common.constant.DbConstant;
import com.dxhy.common.datasource.config.DynamicContextHolder;
import com.dxhy.common.enums.*;
import com.dxhy.common.service.DictdetaServcice;
import com.dxhy.common.service.InvoiceLogService;
import com.dxhy.common.util.ScanIdUtils;
import com.dxhy.common.util.pojo.Authorize;
import com.dxhy.common.util.pojo.GlobalInfo;
import com.dxhy.common.utils.DateUtils;
import com.dxhy.common.vo.InvoiceLog;
import com.dxhy.erp.dao.*;
import com.dxhy.erp.entity.*;
import com.dxhy.erp.model.ReimburseReq;
import com.dxhy.erp.model.ReturnStateInfo;
import com.dxhy.erp.model.auth.InterfaceCode;
import com.dxhy.erp.service.TDxInvoiceReimburseService;
import com.dxhy.erp.utils.CheckUtils;
import com.dxhy.erp.utils.InvoiceQueryUtilTaxNo;
import com.dxhy.oss.service.FtpService;

import cn.hutool.core.codec.Base64;
import lombok.extern.slf4j.Slf4j;

/**
 * @author Gy Chen
 * @date 2021/3/5
 */
@Service
@Slf4j
public class TDxInvoiceReimburseServiceImpl extends ServiceImpl<TDxInvoiceReimburseDao, TDxInvoiceReimburse>
    implements TDxInvoiceReimburseService {
    @Resource
    DictdetaServcice dictdetaServcice;
    @Resource
    FtpService ftpService;
    @Resource
    TDxInvoiceImgDao tDxInvoiceImgDao;
    @Resource
    TdxRecordInvoiceDao tdxRecordInvoiceDao;
    @Resource
    TdxInvoiceDao tdxInvoiceDao;
    @Resource
    ScanIdUtils scanIdUtils;
    @Resource
    private InvoiceQueryUtilTaxNo invoiceQueryUtilTaxNo;
    @Resource
    RecordInvoiceDetailDao recordInvoiceDetailDao;
    @Resource
    RecordInvoiceStatisticDao recordInvoiceStatisticDao;
    @Resource
    private TdxRecordInvoiceDao tDxrecordInvoiceDao;
    @Resource
    private InvoiceLogService invoiceLogService;
    @Resource
    private SysDeptDao sysDeptDao;
    @Value("${ftp.connection.tempPath}")
    private String tempPath;
    @Value("${ftp.connection.pathPrefix}")
    private String pathPrefix;
    @Value("${reimburse.checkStatus}")
    private boolean checkStatus;

    @Resource
    private CustomsSignService customsSignInvoice ;

    @Override
    public TDxInvoiceReimburse invoiceHandle(ReimburseReq reimburseReq, SysDeptEntity deptEntity) {
        List<String> fplxList = new ArrayList<>();
        fplxList.add("01");
        fplxList.add("03");
        fplxList.add("04");
        fplxList.add("08");
        fplxList.add("10");
        fplxList.add("11");
        fplxList.add("14");
        fplxList.add("31");
        fplxList.add("32");
        String invoiceType = reimburseReq.getInvoiceType();
        String dbName = deptEntity.getDbName();
        String scanId = scanIdUtils.createSerialNum();
        if (StringUtils.isNotBlank(reimburseReq.getBase64ImgFile())) {
            reimburseReq.setScanId(scanId);
            try {
                String fileName = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS"))
                    + reimburseReq.getInvoiceCode() + reimburseReq.getInvoiceNo();
                String filePath = tempPath + fileName + ".jpg";
                File file = new File(filePath);
                Base64.decodeToFile(reimburseReq.getBase64ImgFile(), file);
                ftpService.uploadFile(pathPrefix, fileName + ".jpg", filePath);
                // FileUtils.deleteDir(file);
                saveInvoiceImg(reimburseReq.getInvoiceCode() + reimburseReq.getInvoiceNo(),
                    pathPrefix + fileName + ".jpg", scanId, dbName);
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else if (StringUtils.isNotBlank(reimburseReq.getImagePath())) {
            reimburseReq.setScanId(scanId);
            saveInvoiceImg(reimburseReq.getInvoiceCode() + reimburseReq.getInvoiceNo(), reimburseReq.getImagePath(),
                scanId, dbName);
        }
        if (StringUtils.isNotBlank(reimburseReq.getBase64FileStream())) {
            reimburseReq.setScanId(scanId);
            String fileName = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS"))
                + reimburseReq.getInvoiceCode() + reimburseReq.getInvoiceNo();
            String fileType = null;
            if (StringUtils.isNotBlank(reimburseReq.getFileType())) {
                if ("0".equals(reimburseReq.getFileType())) {
                    fileType = "pdf";
                } else if ("1".equals(reimburseReq.getFileType())) {
                    fileType = "ofd";
                }
                if (StringUtils.isNotBlank(fileType)) {
                    String filePath = savePdf(reimburseReq.getBase64FileStream(), fileName, fileType);
                    try {
                        ftpService.uploadFile(pathPrefix, fileName + "." + fileType, filePath);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    this.saveInvoiceFile(reimburseReq.getInvoiceCode() + reimburseReq.getInvoiceNo(),
                        pathPrefix + fileName + "." + fileType, scanId, dbName);
                }
            }
        } else if (StringUtils.isNotBlank(reimburseReq.getFilePath())) {
            reimburseReq.setScanId(scanId);
            this.saveInvoiceFile(reimburseReq.getInvoiceCode() + reimburseReq.getInvoiceNo(),
                reimburseReq.getFilePath(), scanId, dbName);
        }
        if (fplxList.contains(invoiceType)) {
            reimburseReq = signInvoice(reimburseReq, deptEntity);
            reimburseReq.setUuid(reimburseReq.getInvoiceCode() + reimburseReq.getInvoiceNo());
        } else if("17".equals(invoiceType)){
            //添加缴款书签收
            reimburseReq = customsSignInvoice.customsSignInvoice(reimburseReq, deptEntity);
            reimburseReq.setCompany(deptEntity.getCompany());
            TDxInvoiceReimburse reimburse = buildReimburse(null, reimburseReq, fplxList);
            return reimburse;
        } else {
            StringBuffer sb = new StringBuffer();
            sb.append(reimburseReq.getInvoiceType());
            if (StringUtils.isNotBlank(reimburseReq.getTicketNumber())) {
                sb.append(reimburseReq.getTicketNumber());
            }
            if (StringUtils.isNotBlank(reimburseReq.getInvoiceCode())) {
                sb.append(reimburseReq.getInvoiceCode());
            }
            if (StringUtils.isNotBlank(reimburseReq.getInvoiceNo())) {
                sb.append(reimburseReq.getInvoiceNo());
            }
            reimburseReq.setUuid(sb.toString());
        }
        TDxInvoiceReimburse reimburse = insertReimbursement(reimburseReq, deptEntity, fplxList);
        return reimburse;
    }

    @Override
    public String signCanceled(GlobalInfo globalInfo, Map<String, String> map, HttpServletRequest request,
        HttpServletResponse response, Authorize authorize) {

        ReturnStateInfo run = new ReturnStateInfo();
        InterfaceCode interfaceCode = new InterfaceCode();
        ReimburseReq reimburseReq = null;
        try {
            reimburseReq = JSONObject.parseObject(map.get("data"), ReimburseReq.class);
            run = getCheck(reimburseReq);
            if (run.getReturnCode() != null || run.getReturnMessage() != null) {
                interfaceCode.setGlobalInfo(globalInfo);
                interfaceCode.setReturnStateInfo(run);
                return JSON.toJSONString(interfaceCode);
            }
        } catch (Exception e) {
            run.setReturnCode(ReturnCodeEnum.QQBWGSCW.getFhzDm());
            run.setReturnMessage(ReturnCodeEnum.QQBWGSCW.getFhzMc(ReturnCodeEnum.QQBWGSCW.getIndex()));
            interfaceCode.setGlobalInfo(globalInfo);
            interfaceCode.setReturnStateInfo(run);
            interfaceCode.setData("");
            return JSONObject.toJSONString(interfaceCode, SerializerFeature.WriteMapNullValue);
        }
        try {
            if (org.apache.commons.lang3.StringUtils.isBlank(reimburseReq.getGfTaxNo())) {
                run.setReturnCode(ReturnCodeEnum.SHBNWK.getFhzDm());
                run.setReturnMessage(ReturnCodeEnum.SHBNWK.getFhzMc(ReturnCodeEnum.SHBNWK.getIndex()));
                interfaceCode.setGlobalInfo(globalInfo);
                interfaceCode.setReturnStateInfo(run);
                interfaceCode.setData("");
                return JSONObject.toJSONString(interfaceCode, SerializerFeature.WriteMapNullValue);
            }
            DynamicContextHolder.push(DbConstant.BASICS_READ);
            SysDeptEntity deptEntity = sysDeptDao.getOrg(reimburseReq.getGfTaxNo());
            String dbName = null;
            if (deptEntity != null && deptEntity.getDbName() != null) {
                dbName = deptEntity.getDbName();
            } else {
                ReturnStateInfo runInfo = new ReturnStateInfo();
                runInfo.setReturnCode(ReturnCodeEnum.JTSHBF.getFhzDm());
                runInfo.setReturnMessage(ReturnCodeEnum.JTSHBF.getFhzMc(ReturnCodeEnum.JTSHBF.getIndex()));
                interfaceCode.setGlobalInfo(globalInfo);
                interfaceCode.setReturnStateInfo(runInfo);
                interfaceCode.setData("");
                return JSON.toJSONString(interfaceCode);
            }
            List<InvoiceLog> logs = new ArrayList<>();
            if (FplxEnum.ZP.getFplxDm().equals(reimburseReq.getInvoiceType())
                || FplxEnum.TXF.getFplxDm().equals(reimburseReq.getInvoiceType())
                || FplxEnum.JDC.getFplxDm().equals(reimburseReq.getInvoiceType())
                || FplxEnum.PP.getFplxDm().equals(reimburseReq.getInvoiceType())
                || FplxEnum.DZZP.getFplxDm().equals(reimburseReq.getInvoiceType())
                || FplxEnum.DZP.getFplxDm().equals(reimburseReq.getInvoiceType())
                || FplxEnum.JSP.getFplxDm().equals(reimburseReq.getInvoiceType())
                || FplxEnum.QDZZP.getFplxDm().equals(reimburseReq.getInvoiceType())
                || FplxEnum.QDPP.getFplxDm().equals(reimburseReq.getInvoiceType())) {
                // 判断抵帐表是否有票
                QueryWrapper<TdxRecordInvoice> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("uuid", reimburseReq.getInvoiceCode() + reimburseReq.getInvoiceNo());
                DynamicContextHolder.push(dbName + DbConstant.BUSINESS_READ);
                TdxRecordInvoice recordInvoice = tDxrecordInvoiceDao.selectOne(queryWrapper);
                if (recordInvoice == null) {
                    log.info("线程{},抵账无此票{}", Thread.currentThread().getId(),
                        reimburseReq.getInvoiceCode() + reimburseReq.getInvoiceNo());
                    run.setReturnCode(ReturnCodeEnum.FPBCZ.getFhzDm());
                    run.setReturnMessage(ReturnCodeEnum.FPBCZ.getFhzMc(ReturnCodeEnum.FPBCZ.getIndex()));
                    interfaceCode.setGlobalInfo(globalInfo);
                    interfaceCode.setReturnStateInfo(run);
                    interfaceCode.setData("");
                    return JSONObject.toJSONString(interfaceCode, SerializerFeature.WriteMapNullValue);
                } else {
                    if (!"1".equals(recordInvoice.getQsStatus())) {
                        run.setReturnCode("2866");
                        run.setReturnMessage("发票未签收");
                        interfaceCode.setGlobalInfo(globalInfo);
                        interfaceCode.setReturnStateInfo(run);
                        interfaceCode.setData("");
                        return JSONObject.toJSONString(interfaceCode, SerializerFeature.WriteMapNullValue);
                    } else {
                        // 更新底账表签收状态为未签收
                        recordInvoice.setQsStatus("0");
                        recordInvoice.setQsDate(null);
                        recordInvoice.setQsType(null);
                        recordInvoice.setQsName(null);
                        recordInvoice.setLastUpdateDate(new Date());
                        DynamicContextHolder.push(dbName + DbConstant.BUSINESS_WRITE);
                        tDxrecordInvoiceDao.updateById(recordInvoice);
                        InvoiceElectron invoice = new InvoiceElectron();
                        invoice.setQsStatus("0");
                        invoice.setNotes("取消签收");
                        invoice.setUpdateDate(new Date());
                        QueryWrapper<InvoiceElectron> invoiceElectronQueryWrapper = new QueryWrapper<>();
                        invoiceElectronQueryWrapper.eq("uuid", recordInvoice.getUuid());
                        tdxInvoiceDao.update(invoice, invoiceElectronQueryWrapper);
                        // 增加发票日志
                        InvoiceLog log = new InvoiceLog();
                        log.setInputName(reimburseReq.getQsName());
                        log.setInputStatus("5");
                        log.setInvoiceCode(recordInvoice.getInvoiceCode());
                        log.setInvoiceNo(recordInvoice.getInvoiceNo());
                        log.setCreateDate(new Date());
                        for (QsfsEnum e : QsfsEnum.values()) {
                            if (e.getQsfsMc(e.getIndex()).equals(recordInvoice.getQsType())) {
                                log.setQsType(e.getQsfsDm(e.getIndex()));
                            }
                        }
                        log.setType("4");
                        logs.add(log);
                    }
                }

            } else {
                DynamicContextHolder.push(dbName + DbConstant.BUSINESS_READ);
                List<TDxInvoiceReimburse> list = this.baseMapper
                    .selectList(Wrappers.<TDxInvoiceReimburse>query().eq("select_id", reimburseReq.getSelectId()));
                if (list != null && list.size() > 0) {
                    TDxInvoiceReimburse reimburse = list.get(0);
                    DynamicContextHolder.push(dbName + DbConstant.BUSINESS_WRITE);
                    this.baseMapper
                        .delete(Wrappers.<TDxInvoiceReimburse>query().eq("select_id", reimburseReq.getSelectId()));
                } else {
                    run.setReturnCode(ReturnCodeEnum.FPBCZ.getFhzDm());
                    run.setReturnMessage(ReturnCodeEnum.FPBCZ.getFhzMc(ReturnCodeEnum.FPBCZ.getIndex()));
                    interfaceCode.setGlobalInfo(globalInfo);
                    interfaceCode.setReturnStateInfo(run);
                    interfaceCode.setData("");
                    return JSONObject.toJSONString(interfaceCode, SerializerFeature.WriteMapNullValue);
                }
            }
            if (logs != null && logs.size() > 0) {
                invoiceLogService.toInvoiceLog(logs);
            }
            run.setReturnCode(ReturnCodeEnum.CLCG.getFhzDm());
            run.setReturnMessage(ReturnCodeEnum.CLCG.getFhzMc(ReturnCodeEnum.CLCG.getIndex()));
            interfaceCode.setReturnStateInfo(run);
            interfaceCode.setGlobalInfo(globalInfo);
            interfaceCode.setData("");
            return JSONObject.toJSONString(interfaceCode, SerializerFeature.WriteMapNullValue);
        } catch (Exception e) {
            e.printStackTrace();
            run.setReturnCode(ReturnCodeEnum.CLSB.getFhzDm());
            run.setReturnMessage(ReturnCodeEnum.CLSB.getFhzMc(ReturnCodeEnum.CLSB.getIndex()));
            interfaceCode.setReturnStateInfo(run);
            interfaceCode.setGlobalInfo(globalInfo);
            interfaceCode.setData("");
            return JSONObject.toJSONString(interfaceCode, SerializerFeature.WriteMapNullValue);
        }
    }

    public ReturnStateInfo getCheck(ReimburseReq data) {
        ReturnStateInfo run = new ReturnStateInfo();

        if (CheckUtils.isNullOrEmpty(data.getGfTaxNo())) {
            run.setReturnCode(ReturnCodeEnum.SHBNWK.getFhzDm());
            run.setReturnMessage(ReturnCodeEnum.SHBNWK.getFhzMc(ReturnCodeEnum.SHBNWK.getIndex()));
        }

        if (CheckUtils.isNullOrEmpty(data.getQsName())) {
            run.setReturnCode(ReturnCodeEnum.QSRBNWK.getFhzDm());
            run.setReturnMessage(ReturnCodeEnum.QSRBNWK.getFhzMc(ReturnCodeEnum.QSRBNWK.getIndex()));
        }

        if (CheckUtils.isNullOrEmpty(data.getInvoiceType())) {
            run.setReturnCode(ReturnCodeEnum.FPLXWK.getFhzDm());
            run.setReturnMessage(ReturnCodeEnum.FPLXWK.getFhzMc(ReturnCodeEnum.FPLXWK.getIndex()));
        }
        if (FplxEnum.ZP.getFplxDm().equals(data.getInvoiceType())
            || FplxEnum.TXF.getFplxDm().equals(data.getInvoiceType())
            || FplxEnum.JDC.getFplxDm().equals(data.getInvoiceType())
            || FplxEnum.PP.getFplxDm().equals(data.getInvoiceType())
            || FplxEnum.DZZP.getFplxDm().equals(data.getInvoiceType())
            || FplxEnum.DZP.getFplxDm().equals(data.getInvoiceType())
            || FplxEnum.JSP.getFplxDm().equals(data.getInvoiceType())) {
            boolean r1 =
                CheckUtils.isNullOrEmpty(data.getInvoiceCode()) || !(CheckUtils.stringLength(data.getInvoiceCode(), 10)
                    || CheckUtils.stringLength(data.getInvoiceCode(), 12));
            if (r1) {
                run.setReturnCode(ReturnCodeEnum.DMHMBF.getFhzDm());
                run.setReturnMessage(ReturnCodeEnum.DMHMBF.getFhzMc(ReturnCodeEnum.DMHMBF.getIndex()));
            }
            boolean r2 =
                CheckUtils.isNullOrEmpty(data.getInvoiceNo()) || !(CheckUtils.stringLength(data.getInvoiceNo(), 8)
                    || CheckUtils.stringLength(data.getInvoiceNo(), 10));
            if (r2) {
                run.setReturnCode(ReturnCodeEnum.DMHMBF.getFhzDm());
                run.setReturnMessage(ReturnCodeEnum.DMHMBF.getFhzMc(ReturnCodeEnum.DMHMBF.getIndex()));
            }
        } else {
            if (CheckUtils.isNullOrEmpty(data.getSelectId())) {
                run.setReturnCode(ReturnCodeEnum.NRYCY.getFhzDm());
                run.setReturnMessage(ReturnCodeEnum.NRYCY.getFhzMc(ReturnCodeEnum.NRYCY.getIndex()));
            }
        }
        return run;
    }

    public String savePdf(String pdf, String fileName, String fileType) {
        /*        BufferedInputStream bis = null;
        FileOutputStream fos = null;
        BufferedOutputStream bos = null;*/
        String tempPathPdf = tempPath + "file/" + new SimpleDateFormat("yyyyMMdd").format(new Date()) + "/";
        String filePath = tempPathPdf + fileName + "." + fileType;
        try {
            File file = new File(filePath);
            File path = file.getParentFile();
            if (!path.exists()) {
                path.mkdirs();
            }
            Base64.decodeToFile(pdf, file);
            /*byte[] bytes = Base64.decodeStr(pdf).getBytes();//base64编码内容转换为字节数组
            ByteArrayInputStream byteInputStream = new ByteArrayInputStream(bytes);
            bis = new BufferedInputStream(byteInputStream);
            createFileDir(tempPathPdf);
            File file = new File(filePath);
            File path = file.getParentFile();
            if(!path.exists()){
                path.mkdirs();
            }
            fos = new FileOutputStream(file);
            bos = new BufferedOutputStream(fos);

            byte[] buffer = new byte[1024];
            int length = bis.read(buffer);
            while(length != -1){
                bos.write(buffer, 0, length);
                length = bis.read(buffer);
            }
            bos.flush();
            */
        } catch (Exception e) {
            e.printStackTrace();
        }
        return filePath;
    }

    public void createFileDir(String tempPath) {
        // 创建临时存储文件夹
        File tempFileDir = new File(tempPath);
        if (!tempFileDir.exists()) {
            tempFileDir.mkdirs();
        }
    }
    public ReimburseReq signInvoice(ReimburseReq reimburseReq, SysDeptEntity deptEntity) {
        String invoiceType = reimburseReq.getInvoiceType();
        DynamicContextHolder.push(deptEntity.getDbName() + DbConstant.BUSINESS_READ);
        TdxRecordInvoice recordInvoice = tdxRecordInvoiceDao.selectOne(
            Wrappers.<TdxRecordInvoice>query().eq("uuid", reimburseReq.getInvoiceCode() + reimburseReq.getInvoiceNo()));
        if (recordInvoice != null && "1".equals(recordInvoice.getQsStatus())) {
            reimburseReq.setNotes("发票已签收，重复推送");
            return reimburseReq;
        }
        InvoiceElectron invoice = tdxInvoiceDao.selectOne(
            Wrappers.<InvoiceElectron>query().eq("uuid", reimburseReq.getInvoiceCode() + reimburseReq.getInvoiceNo()));
        if (FplxEnum.ZP.getFplxDm().equals(invoiceType) || FplxEnum.DZZP.getFplxDm().equals(invoiceType)
            || FplxEnum.TXF.getFplxDm().equals(invoiceType) || FplxEnum.JDC.getFplxDm().equals(invoiceType)
            || FplxEnum.QDZZP.getFplxDm().equals(invoiceType)) {
            if (recordInvoice == null) {
                reimburseReq.setQsStatus("0");
                reimburseReq.setNotes("签收失败，发票不存在");
                buildInvoiceElectron(recordInvoice, reimburseReq, invoice, deptEntity);
                return reimburseReq;
            }
            if (!new SimpleDateFormat("yyyy-MM-dd").format(recordInvoice.getInvoiceDate())
                .equals(reimburseReq.getInvoiceDate())) {
                reimburseReq.setQsStatus("0");
                reimburseReq.setNotes("签收失败，开票日期与底账不一致");
                buildInvoiceElectron(recordInvoice, reimburseReq, invoice, deptEntity);
                return reimburseReq;
            }
            if (!recordInvoice.getInvoiceAmount().setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString()
                .equals(new BigDecimal(reimburseReq.getInvoiceAmount()).setScale(2, BigDecimal.ROUND_HALF_UP)
                    .toPlainString())) {
                reimburseReq.setQsStatus("0");
                reimburseReq.setNotes("签收失败，金额与底账不一致");
                buildInvoiceElectron(recordInvoice, reimburseReq, invoice, deptEntity);
                return reimburseReq;
            }
            if (!recordInvoice.getGfName().equals(reimburseReq.getGfName())) {
                reimburseReq.setQsStatus("0");
                reimburseReq.setNotes("签收失败，购方名称与底账不一致");
                buildInvoiceElectron(recordInvoice, reimburseReq, invoice, deptEntity);
                return reimburseReq;
            }
            if (!"0".equals(recordInvoice.getInvoiceStatus())) {
                reimburseReq.setQsStatus("0");
                reimburseReq.setNotes("签收失败，发票状态异常");
                buildInvoiceElectron(recordInvoice, reimburseReq, invoice, deptEntity);
                return reimburseReq;
            }
            reimburseReq.setQsStatus("1");
            reimburseReq.setNotes("签收成功");
            InvoiceElectron invoiceElectron = buildInvoiceElectron(recordInvoice, reimburseReq, invoice, deptEntity);
            return reimburseReq;
        } else {
            if (checkStatus) {
                JSONObject jsonObject = invoiceQueryUtilTaxNo.queryInvoice(reimburseReq.getInvoiceCode(),
                    reimburseReq.getInvoiceNo(), reimburseReq.getInvoiceDate(), reimburseReq.getInvoiceAmount(),
                    reimburseReq.getCheckCode(), reimburseReq.getGfTaxNo(),reimburseReq.getInvoiceType());
                if (jsonObject.containsKey("returnCode")) {
                    reimburseReq.setQsStatus("0");
                    reimburseReq.setNotes(jsonObject.getString("returnMessage"));
                    buildInvoiceElectron(recordInvoice, reimburseReq, invoice, deptEntity);
                    return reimburseReq;
                } else {
                    if (recordInvoice == null) {
                        recordInvoice =
                            getRecordInvoice(jsonObject, reimburseReq.getQsName(), QsfsEnum.JKTS.getQsfsDm());
                    }
                    if (!new SimpleDateFormat("yyyy-MM-dd").format(recordInvoice.getInvoiceDate())
                        .equals(reimburseReq.getInvoiceDate())) {
                        reimburseReq.setQsStatus("0");
                        reimburseReq.setNotes("签收失败，开票日期与查验结果不一致");
                        buildInvoiceElectron(recordInvoice, reimburseReq, invoice, deptEntity);
                        return reimburseReq;
                    }
                    if (!recordInvoice.getInvoiceAmount().setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString()
                        .equals(new BigDecimal(reimburseReq.getInvoiceAmount()).setScale(2, BigDecimal.ROUND_HALF_UP)
                            .toPlainString())) {
                        reimburseReq.setQsStatus("0");
                        reimburseReq.setNotes("签收失败，金额与查验结果不一致");
                        buildInvoiceElectron(recordInvoice, reimburseReq, invoice, deptEntity);
                        return reimburseReq;
                    }
                    if (!recordInvoice.getGfName().equals(reimburseReq.getGfName())) {
                        reimburseReq.setQsStatus("0");
                        reimburseReq.setNotes("签收失败，购方名称与查验结果不一致");
                        buildInvoiceElectron(recordInvoice, reimburseReq, invoice, deptEntity);
                        return reimburseReq;
                    }
                    if (!"0".equals(recordInvoice.getInvoiceStatus())) {
                        reimburseReq.setQsStatus("0");
                        reimburseReq.setNotes("签收失败，发票状态异常");
                        buildInvoiceElectron(recordInvoice, reimburseReq, invoice, deptEntity);
                        return reimburseReq;
                    }
                    reimburseReq.setQsStatus("1");
                    reimburseReq.setNotes("签收成功");
                    InvoiceElectron invoiceElectron =
                        buildInvoiceElectron(recordInvoice, reimburseReq, invoice, deptEntity);
                    return reimburseReq;
                }
            } else {
                reimburseReq.setQsStatus("1");
                reimburseReq.setNotes("签收成功");
                InvoiceElectron invoiceElectron =
                    buildInvoiceElectron(recordInvoice, reimburseReq, invoice, deptEntity);
                return reimburseReq;
            }
        }
    }

    private List<TdxRecordInvoiceStatistics> getInvoiceStatistics(List<RecordInvoiceDetail> tDxRecordInvoiceDetails) {
        List<TdxRecordInvoiceStatistics> invoiceStatisticsList = new ArrayList<TdxRecordInvoiceStatistics>();

        if (tDxRecordInvoiceDetails != null && tDxRecordInvoiceDetails.size() > 0) {
            RecordInvoiceDetail detail = tDxRecordInvoiceDetails.get(0);
            // 最终要的结果
            final Map<String, List<RecordInvoiceDetail>> resultMap = new HashMap();
            // 按税率分组
            tDxRecordInvoiceDetails.forEach(dataItem -> {
                if (!dataItem.getGoodsName().trim().equals("原价合计") && !dataItem.getGoodsName().trim().equals("折扣额合计")
                    && !dataItem.getGoodsName().trim().equals("(详见销货清单)")&& !dataItem.getGoodsName().trim().equals("（详见销货清单）") && StringUtils.isNotEmpty(dataItem.getTaxRate())) {
                    if (resultMap.containsKey(dataItem.getTaxRate())) {
                        resultMap.get(dataItem.getTaxRate()).add(dataItem);
                    } else {
                        final List<RecordInvoiceDetail> list = new ArrayList();
                        list.add(dataItem);
                        resultMap.put(dataItem.getTaxRate(), list);
                    }
                }
            });

            // 循环遍历map获取每组明细，并循环遍历每组里的明细组装抵账统计数据
            for (Map.Entry<String, List<RecordInvoiceDetail>> entry : resultMap.entrySet()) {
                // 获取每组明细
                final List<RecordInvoiceDetail> detailList = entry.getValue();
                // 定义抵账统计实体
                final TdxRecordInvoiceStatistics recordInvoiceStatistics = new TdxRecordInvoiceStatistics();
                // 税额
                BigDecimal taxAmount = new BigDecimal(0.0);
                // 金额
                BigDecimal detailAmount = new BigDecimal(0.0);
                // 循环赋值
                for (RecordInvoiceDetail invoiceDetail : detailList) {
                    String taxAmountString = invoiceDetail.getTaxAmount();
                    BigDecimal se;
                    try {
                        se = new BigDecimal(invoiceDetail.getTaxAmount());
                    } catch (Exception e) {
                        se = new BigDecimal("0");
                    }
                    taxAmount = taxAmount.add(se);
                    detailAmount = detailAmount.add(new BigDecimal(invoiceDetail.getDetailAmount()));

                }
                // 价税合计
                final BigDecimal totalAmount = taxAmount.add(detailAmount);
                // 税率
                recordInvoiceStatistics.setTaxRate(entry.getKey());
                // 发票号码
                recordInvoiceStatistics.setInvoiceNo(detail.getInvoiceNo());
                // 发票代码
                recordInvoiceStatistics.setInvoiceCode(detail.getInvoiceCode());
                // 税额
                recordInvoiceStatistics.setTaxAmount(taxAmount.toPlainString());
                // 金额
                recordInvoiceStatistics.setDetailAmount(detailAmount);
                // 价税合计
                recordInvoiceStatistics.setTotalAmount(totalAmount);
                recordInvoiceStatistics.setCreateDate(new Date());
                // 放入集合
                invoiceStatisticsList.add(recordInvoiceStatistics);
            }

        }

        return invoiceStatisticsList;
    }

    public List<RecordInvoiceDetail> getRecordInvoiceDetail(ReimburseReq vo) {
        List<RecordInvoiceDetail> tDxRecordInvoiceDetailList = vo.getInvoiceDetailInfos();
        for (RecordInvoiceDetail detail : tDxRecordInvoiceDetailList) {
            detail.setInvoiceCode(vo.getInvoiceCode());
            detail.setInvoiceNo(vo.getInvoiceNo());
            detail.setUuid(vo.getInvoiceCode() + vo.getInvoiceNo());
        }
        return tDxRecordInvoiceDetailList;
    }

    public TdxRecordInvoice buildRecord(ReimburseReq vo) {
        TdxRecordInvoice record = new TdxRecordInvoice();
        record.setInvoiceType(vo.getInvoiceType());
        record.setInvoiceCode(vo.getInvoiceCode());
        record.setInvoiceNo(vo.getInvoiceNo());
        record.setUuid(vo.getInvoiceCode() + vo.getInvoiceNo());
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        try {
            record.setInvoiceDate(sdf.parse(vo.getInvoiceDate()));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        record.setGfTaxNo(vo.getGfTaxNo());
        record.setGfName(vo.getGfName());
        record.setGfAddressAndPhone(vo.getGfAddressAndPhone());
        record.setGfBankAndNo(vo.getGfBankAndNo());
        record.setXfTaxNo(vo.getXfTaxNo());
        record.setXfName(vo.getXfName());
        record.setXfAddressAndPhone(vo.getXfAddressAndPhone());
        record.setXfBankAndNo(vo.getXfBankAndNo());
        record.setInvoiceAmount(new BigDecimal(vo.getInvoiceAmount()));
        record.setTaxAmount(new BigDecimal(vo.getTaxAmount()));
        record.setTotalAmount(new BigDecimal(vo.getTotalAmount()));
        record.setRemark(vo.getRemark());
        record.setInvoiceStatus(vo.getInvoiceStatus());
        if (!"0".equals(vo.getInvoiceStatus())) {
            record.setStatusUpdateDate(new Date());
        }
        record.setQsDate(new Date());
        record.setSourceSystem("1");
        record.setValid("1");
        record.setCreateDate(new Date());
        record.setDetailYesorno("1");
        record.setQsType(QsfsEnum.JKTS.getQsfsDm());
        record.setQsStatus("1");
        record.setCheckCode(vo.getCheckCode());
        record.setQsName(vo.getQsName());
        record.setDkTaxAmount(new BigDecimal(vo.getTaxAmount()));
        record.setScanId(vo.getScanId());
        if (StringUtils.isNotBlank(vo.getVoucherNumber())) {
            record.setVoucherNumber(vo.getVoucherNumber());
        }
        if (StringUtils.isNotBlank(vo.getRelatedBusinessDocuments())) {
            record.setRelatedBusinessDocuments(vo.getRelatedBusinessDocuments());
        }
        if (StringUtils.isNotBlank(vo.getBusinessDocumentNumber())) {
            record.setDocumentNumber(vo.getBusinessDocumentNumber());
        }
        record.setLastUpdateDate(new Date());
        return record;
    }

    public TdxRecordInvoice getRecordInvoice(JSONObject queryInvoiceResult, String userName, String qsType) {
        TdxRecordInvoice invoice = new TdxRecordInvoice();

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

        invoice.setInvoiceType(invoiceType);
        if("31".equals(invoiceType) ||"32".equals(invoiceType)){
            invoice.setInvoiceNo(uuid);
        }else {
            invoice.setInvoiceCode(invoiceCode);
            invoice.setInvoiceNo(invoiceNo);
        }
        invoice.setUuid(uuid);
        if ("Y".equals(queryInvoiceResult.getString("isCancelled"))) {
            invoice.setInvoiceStatus(FpztEnum.ZF.getFpztDm(FpztEnum.ZF.getIndex()));
        } else if ("N".equals(queryInvoiceResult.getString("isCancelled"))) {
            invoice.setInvoiceStatus(FpztEnum.ZC.getFpztDm(FpztEnum.ZC.getIndex()));
        } else {
            invoice.setInvoiceStatus(queryInvoiceResult.getString("isCancelled"));
        }
        invoice.setInvoiceAmount(queryInvoiceResult.getBigDecimal("invoiceAmount"));
        invoice.setTaxAmount(queryInvoiceResult.getBigDecimal("taxAmount"));
        invoice.setTotalAmount(queryInvoiceResult.getBigDecimal("totalAmount"));
        invoice.setInvoiceDate(queryInvoiceResult.getDate("invoiceDate"));
        invoice.setGfAddressAndPhone(queryInvoiceResult.getString("buyerAddressPhone"));
        invoice.setGfBankAndNo(queryInvoiceResult.getString("buyerAccount"));
        invoice.setGfName(queryInvoiceResult.getString("buyerName"));
        invoice.setGfTaxNo(queryInvoiceResult.getString("buyerTaxNo"));
        invoice.setXfAddressAndPhone(queryInvoiceResult.getString("salerAddressPhone"));
        invoice.setXfBankAndNo(queryInvoiceResult.getString("buyerAccount"));
        invoice.setXfName(queryInvoiceResult.getString("salerName"));
        invoice.setXfTaxNo(queryInvoiceResult.getString("salerTaxNo"));
        invoice.setMachinecode(queryInvoiceResult.getString("machineNo"));
        invoice.setRemark(queryInvoiceResult.getString("remark"));
        invoice.setCheckCode(queryInvoiceResult.getString("checkCode"));
        invoice.setTxfbz(queryInvoiceResult.getString("txfbz"));
        invoice.setSourceSystem("1");
        invoice.setCompany(queryInvoiceResult.getString("company"));
        if (FplxEnum.JDC.getFplxDm().equals(invoiceType)) {
            invoice.setDetailYesorno("0");
        } else {
            if (queryInvoiceResult.containsKey("detailList")) {
                JSONArray dataArray = queryInvoiceResult.getJSONArray("detailList");
                if (dataArray != null && dataArray.size() > 0) {
                    invoice.setDetailYesorno("1");
                } else {
                    invoice.setDetailYesorno("0");
                }
            } else {
                invoice.setDetailYesorno("0");
            }
        }
        invoice.setCreateDate(new Date());
        invoice.setLastUpdateDate(new Date());
        invoice.setQsDate(DateUtils.getSqlDateLong());
        invoice.setQsStatus(FpqsjgEnum.WQS.getQsjgDm());
        invoice.setQsType(qsType);
        invoice.setValid("1");
        invoice.setDeptName(queryInvoiceResult.getString("deptName"));
        invoice.setDeptId(queryInvoiceResult.getString("deptId"));
        invoice.setQsName(userName);
        invoice.setRzhYesorno("0");
        invoice.setAuthStatus("0");
        invoice.setScanId(queryInvoiceResult.getString("scanId"));
        return invoice;
    }

    private InvoiceElectron buildInvoiceElectron(TdxRecordInvoice recordInvoice, ReimburseReq reimburseReq,
        InvoiceElectron invoiceElectron, SysDeptEntity deptEntity) {
        InvoiceElectron invoice = new InvoiceElectron();
        invoice.setInvoiceType(reimburseReq.getInvoiceType());
        invoice.setInvoiceCode(reimburseReq.getInvoiceCode());
        invoice.setInvoiceNo(reimburseReq.getInvoiceNo());
        try {
            invoice.setInvoiceDate(StringUtils.isNotBlank(reimburseReq.getInvoiceDate())
                ? new SimpleDateFormat("yyyy-MM-dd").parse(reimburseReq.getInvoiceDate()) : null);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        invoice.setInvoiceSerialNo(Long.valueOf(scanIdUtils.createSerialNum()));
        invoice.setGfTaxNo(reimburseReq.getGfTaxNo());
        invoice.setGfName(reimburseReq.getGfName());
        invoice.setXfTaxNo(reimburseReq.getXfTaxNo());
        invoice.setXfName(reimburseReq.getXfName());
        invoice.setInvoiceAmount(new BigDecimal(reimburseReq.getInvoiceAmount()));
        invoice.setTaxAmount(new BigDecimal(reimburseReq.getTaxAmount()));
        invoice.setTotalAmount(new BigDecimal(reimburseReq.getTotalAmount()));
        invoice.setUserAccount(reimburseReq.getQsName());
        invoice.setUserName(reimburseReq.getQsName());
        invoice.setQsType(QsfsEnum.JKTS.getQsfsDm());
        invoice.setValid("1");
        invoice.setUuid(reimburseReq.getInvoiceCode() + reimburseReq.getInvoiceNo());
        invoice.setCreateDate(new Date());
        invoice.setQsStatus(reimburseReq.getQsStatus());
        invoice.setQsDate(new Date());
        invoice.setNotes(reimburseReq.getNotes());
        if (StringUtils.isNotBlank(reimburseReq.getScanId())) {
            invoice.setScanId(reimburseReq.getScanId());
        }
        invoice.setCheckCode(reimburseReq.getCheckCode());
        invoice.setInvoiceStatus(reimburseReq.getInvoiceStatus());
        invoice.setQsName(reimburseReq.getQsName());
        invoice.setCompany(deptEntity.getCompany());
        DynamicContextHolder.push(deptEntity.getDbName() + DbConstant.BUSINESS_WRITE);
        if (invoiceElectron != null) {
            invoice.setId(invoiceElectron.getId());
            tdxInvoiceDao.updateById(invoice);
        } else {
            tdxInvoiceDao.insert(invoice);
        }
        if ("1".equals(invoice.getQsStatus())) {
            if (recordInvoice != null && recordInvoice.getId() != null) {
                recordInvoice.setQsStatus("1");
                recordInvoice.setQsDate(new Date());
                recordInvoice.setQsName(reimburseReq.getQsName());
                recordInvoice.setQsType(QsfsEnum.JKTS.getQsfsDm());
                recordInvoice.setLastUpdateDate(new Date());
                if (StringUtils.isNotBlank(reimburseReq.getScanId())) {
                    recordInvoice.setScanId(reimburseReq.getScanId());
                }
                if (StringUtils.isNotBlank(reimburseReq.getVoucherNumber())) {
                    recordInvoice.setVoucherNumber(reimburseReq.getVoucherNumber());
                }
                if (StringUtils.isNotBlank(reimburseReq.getRelatedBusinessDocuments())) {
                    recordInvoice.setRelatedBusinessDocuments(reimburseReq.getRelatedBusinessDocuments());
                }
                if (StringUtils.isNotBlank(reimburseReq.getBusinessDocumentNumber())) {
                    recordInvoice.setDocumentNumber(reimburseReq.getBusinessDocumentNumber());
                }
                tdxRecordInvoiceDao.updateById(recordInvoice);
            } else {
                TdxRecordInvoice record = buildRecord(reimburseReq);
                List<RecordInvoiceDetail> recordInvoiceDetails = getRecordInvoiceDetail(reimburseReq);
                List<TdxRecordInvoiceStatistics> statistics = getInvoiceStatistics(recordInvoiceDetails);
                if (record != null) {
                    DynamicContextHolder.push(deptEntity.getDbName() + DbConstant.BUSINESS_WRITE);
                    record.setCompany(deptEntity.getCompany());
                    tdxRecordInvoiceDao.insert(record);
                }
                if (recordInvoiceDetails != null && recordInvoiceDetails.size() > 0) {
                    for (RecordInvoiceDetail detail : recordInvoiceDetails) {
                        DynamicContextHolder.push(deptEntity.getDbName() + DbConstant.DETAIL_WRITE);
                        if(StringUtils.isNotBlank(detail.getTaxRate())){
                            if(detail.getTaxRate().contains("%")){
                                detail.setTaxRate(detail.getTaxRate().replace("%",""));
                            }
                        }
                        recordInvoiceDetailDao.insert(detail);
                    }
                }
                if (statistics != null && statistics.size() > 0) {
                    for (TdxRecordInvoiceStatistics statistics1 : statistics) {
                        DynamicContextHolder.push(deptEntity.getDbName() + DbConstant.BUSINESS_WRITE);
                        if(StringUtils.isNotBlank( statistics1.getTaxRate())){
                            String taxRate = statistics1.getTaxRate();
                            if (taxRate.contains("%")) {
                                taxRate = taxRate.replace("%", "");
                                statistics1.setTaxRate(taxRate);
                            }
                        }
                        recordInvoiceStatisticDao.insert(statistics1);
                    }
                }
            }
            InvoiceLog log = new InvoiceLog();
            log.setInputName(reimburseReq.getQsName());
            log.setInputStatus("1");
            log.setInvoiceCode(reimburseReq.getInvoiceCode());
            log.setInvoiceNo(reimburseReq.getInvoiceNo());
            log.setQsType("6");
            log.setType("3");
            log.setCreateDate(new Date());
            List<InvoiceLog> logs = new ArrayList<>();
            logs.add(log);
            invoiceLogService.toInvoiceLog(logs);
        }
        return invoice;
    }

    public TDxInvoiceReimburse insertReimbursement(ReimburseReq reimburseReq, SysDeptEntity deptEntity,
        List<String> fplxList) {
        TDxInvoiceReimburse entity;
        if (fplxList.contains(reimburseReq.getInvoiceType())) {
            DynamicContextHolder.push(deptEntity.getDbName() + DbConstant.BUSINESS_READ);
            entity = this.baseMapper.selectOne(Wrappers.<TDxInvoiceReimburse>query().eq("uuid",
                reimburseReq.getInvoiceCode() + reimburseReq.getInvoiceNo()));
        } else {
            entity = null;
        }
        reimburseReq.setCompany(deptEntity.getCompany());
        TDxInvoiceReimburse reimburse = buildReimburse(entity, reimburseReq, fplxList);
        DynamicContextHolder.push(deptEntity.getDbName() + DbConstant.BUSINESS_WRITE);
        this.saveOrUpdate(reimburse);
        return reimburse;
    }

    private TDxInvoiceReimburse buildReimburse(TDxInvoiceReimburse entity, ReimburseReq reimburseReq,
        List<String> fplxList) {
        if (entity == null) {
            entity = new TDxInvoiceReimburse();
        } else {
            entity.setUpdateDate(new Date());
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        entity.setInvoiceType(reimburseReq.getInvoiceType());
        entity.setInvoiceCode(reimburseReq.getInvoiceCode());
        entity.setInvoiceNo(reimburseReq.getInvoiceNo());
        entity.setInvoiceDate(reimburseReq.getInvoiceDate());
        entity.setTicketNumber(reimburseReq.getTicketNumber());
        entity.setPassenger(reimburseReq.getPassenger());
        entity.setInvoiceAmount(StringUtils.isBlank(reimburseReq.getInvoiceAmount()) ? new BigDecimal("0")
            : new BigDecimal(reimburseReq.getInvoiceAmount()));
        entity.setTaxAmount(StringUtils.isBlank(reimburseReq.getTaxAmount()) ? new BigDecimal("0")
            : new BigDecimal(reimburseReq.getTaxAmount()));
        entity.setTotalAmount(StringUtils.isBlank(reimburseReq.getTotalAmount()) ? new BigDecimal("0")
            : new BigDecimal(reimburseReq.getTotalAmount()));
        entity.setInvoiceStatus(reimburseReq.getInvoiceStatus());
        entity.setDqskssq(reimburseReq.getDqskssq());
        entity.setSourceSystem(reimburseReq.getSourceSystem());
        entity.setDepartureCity(reimburseReq.getDepartureCity());
        entity.setReachingCity(reimburseReq.getReachingCity());
        entity.setRelatedBusinessDocuments(reimburseReq.getRelatedBusinessDocuments());
        entity.setBusinessDocumentMaker(reimburseReq.getBusinessDocumentMaker());
        entity.setBusinessDocumentNumber(reimburseReq.getBusinessDocumentNumber());
        entity.setReimbursementTime(
            StringUtils.isBlank(reimburseReq.getReimbursementTime()) ? null : reimburseReq.getReimbursementTime());
        entity.setReimbursementStatus(reimburseReq.getReimbursementStatus());
        entity.setTrainNumber(reimburseReq.getTrainNumber());
        try {
            entity.setTicketDepartureTime(sdf.parse(reimburseReq.getTicketDepartureTime()));
        } catch (Exception e) {

        }
        try {
            entity.setTicketArrivalTime(sdf.parse(reimburseReq.getTicketArrivalTime()));
        } catch (Exception e) {

        }
        entity.setPassengerSFZH(reimburseReq.getPassengerSFZH());
        entity.setXfName(reimburseReq.getXfName());
        entity.setXfAddressAndPhone(reimburseReq.getXfAddressAndPhone());
        entity.setXfBankAndNo(reimburseReq.getXfBankAndNo());
        entity.setGfTaxNo(reimburseReq.getGfTaxNo());
        entity.setGfName(reimburseReq.getGfName());
        entity.setGfAddressAndPhone(reimburseReq.getGfAddressAndPhone());
        entity.setGfBankAndNo(reimburseReq.getGfBankAndNo());
        entity.setXfTaxNo(reimburseReq.getXfTaxNo());
        entity.setTaxRate(reimburseReq.getTaxRate());
        entity.setTag(reimburseReq.getTag());
        entity.setIsDeduction(reimburseReq.getIsDeduction());
        entity.setUuid(reimburseReq.getUuid());
        entity.setIsDomestic(reimburseReq.getIsDomestic());
        entity.setCreateDate(DateUtils.getStringDate());
        entity.setRzhYesorno("0");
        entity.setSelectId(reimburseReq.getSelectId());
        entity.setQsName(reimburseReq.getQsName());
        entity.setQsType(QsfsEnum.JKTS.getQsfsDm());
        entity.setQsDate(DateUtils.getStringDate());
        entity.setScanId(reimburseReq.getScanId());
        entity.setCheckCode(reimburseReq.getCheckCode());
        if (fplxList.contains(reimburseReq.getInvoiceType()) || "17".equals(reimburseReq.getInvoiceType())) {
            entity.setQsStatus(reimburseReq.getQsStatus());
            entity.setQzStatus(reimburseReq.getQsStatus());
            entity.setNotes(reimburseReq.getNotes());
        } else {
            entity.setQsStatus("1");
            entity.setQzStatus("1");
            entity.setNotes("签收成功");
        }
        entity.setFuelSurcharge(reimburseReq.getFuelSurcharge());
        entity.setCaacDevelopmentFund(reimburseReq.getCaacDevelopmentFund());
        entity.setFare(StringUtils.isBlank(reimburseReq.getFare()) ? null : reimburseReq.getFare());
        entity.setRemark(reimburseReq.getRemark());
        entity.setCompany(reimburseReq.getCompany());
        entity.setVoucherNumber(reimburseReq.getVoucherNumber());
        entity.setCurrency(reimburseReq.getCurrency());
        return entity;
    }

    public void saveInvoiceImg(String uuid, String filePath, String scanId, String dbName) {
        TDxInvoiceImg img = new TDxInvoiceImg();
        img.setUuid(uuid);
        img.setCreateDate(new Date());
        img.setImagePath(filePath);
        img.setScanId(scanId);
        img.setValid("1");
        DynamicContextHolder.push(dbName + DbConstant.BUSINESS_WRITE);
        tDxInvoiceImgDao.insert(img);
    }

    public void saveInvoiceFile(String uuid, String filePath, String scanId, String dbName) {
        DynamicContextHolder.push(dbName + DbConstant.BUSINESS_WRITE);
        TDxInvoiceImg img = tDxInvoiceImgDao.selectOne(Wrappers.<TDxInvoiceImg>query().eq("scan_id", scanId));
        if (img != null) {
            img.setImage(filePath);
            DynamicContextHolder.push(dbName + DbConstant.BUSINESS_WRITE);
            tDxInvoiceImgDao.updateById(img);
        } else {
            img = new TDxInvoiceImg();
            img.setUuid(uuid);
            img.setCreateDate(new Date());
            img.setImage(filePath);
            img.setScanId(scanId);
            img.setValid("1");
            DynamicContextHolder.push(dbName + DbConstant.BUSINESS_WRITE);
            tDxInvoiceImgDao.insert(img);
        }

    }
}
