package com.dxhy.erp.utils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.math.BigDecimal;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.ThreadLocalRandom;

import org.apache.commons.lang3.StringUtils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.dxhy.common.constant.DbConstant;
import com.dxhy.common.datasource.config.DynamicContextHolder;
import com.dxhy.common.enums.FplxEnum;
import com.dxhy.common.enums.FpqsjgEnum;
import com.dxhy.common.enums.FpztEnum;
import com.dxhy.common.util.ScanIdUtils;
import com.dxhy.common.utils.DateUtils;
import com.dxhy.erp.dao.*;
import com.dxhy.erp.entity.*;
import com.dxhy.erp.model.ApplicationContextRegister;
import com.dxhy.erp.service.CheckService;
import com.dxhy.model.OfdInvoice;
import com.dxhy.ofd.service.OfdService;
import com.dxhy.oss.model.FileModel;
import com.dxhy.oss.service.FileService;
import com.dxhy.pdf.entity.PdfInvoiceModel;
import com.dxhy.pdf.utils.PdfUtil;
import com.ele.parse.entity.FPEntity;

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

/**
 * @author dxhy
 */
@SuppressWarnings({"AlibabaUndefineMagicConstant", "AlibabaMethodTooLong"})
@Slf4j
public class MyThread extends Thread {

    private static final String[] FPDM_LIST = {"144031539110", "131001570151", "133011501118", "111001571071"};
    private final Map<String, String> map;
    private final String tempPath;
    private final RecordInvoiceDao recordInvoiceDao;

    private final SysDeptDao sysDeptDao;

    private final InvoiceElectronDao invoiceElectronDao;

    private final InvoiceDetailDao invoiceDetailDao;

    private final InvoiceImgDao invoiceImgDao;

    private final ScanIdUtils scanIdUtils;

    private final InvoiceQueryUtil invoiceQueryUtil;

    private final CheckService checkSerivice;

    private final OfdService ofdService;

    private String dbName;

    private final FileService fileService;
    private String ylgfTaxNo;

    public MyThread(Map<String, String> map, String tempPath, FileService fileService, String ylgfTaxNo) {
        this.tempPath = tempPath;
        this.map = map;
        this.fileService = fileService;
        this.ylgfTaxNo = ylgfTaxNo;

        this.recordInvoiceDao =
            (RecordInvoiceDao)ApplicationContextRegister.getApplicationContext().getBean("recordInvoiceDao");
        this.invoiceElectronDao =
            (InvoiceElectronDao)ApplicationContextRegister.getApplicationContext().getBean("invoiceElectronDao");
        this.checkSerivice = (CheckService)ApplicationContextRegister.getApplicationContext().getBean("checkService");
        this.ofdService = (OfdService)ApplicationContextRegister.getApplicationContext().getBean("ofdService");
        this.sysDeptDao = (SysDeptDao)ApplicationContextRegister.getApplicationContext().getBean("sysDeptDao");
        this.invoiceDetailDao =
            (InvoiceDetailDao)ApplicationContextRegister.getApplicationContext().getBean("invoiceDetailDao");
        this.invoiceImgDao = (InvoiceImgDao)ApplicationContextRegister.getApplicationContext().getBean("invoiceImgDao");
        this.scanIdUtils = (ScanIdUtils)ApplicationContextRegister.getApplicationContext().getBean("scanIdUtils");
        this.invoiceQueryUtil =
            (InvoiceQueryUtil)ApplicationContextRegister.getApplicationContext().getBean("invoiceQueryUtil");
        DynamicContextHolder.push(DbConstant.BASICS_READ);
        SysDeptEntity deptEntity = sysDeptDao.getOrg(ylgfTaxNo);

        if (deptEntity != null && deptEntity.getDbName() != null) {
            dbName = deptEntity.getDbName();
        }

    }

    @Override
    public void run() {
        try {
            getInstance(map, tempPath);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void getInstance(Map<String, String> map, String tempPath) throws Exception {
        // 转存临时路径
        String a = map.get("pdf");
        String text = map.get("text");
        byte[] pdfbyte = Base64.decode(a.getBytes(StandardCharsets.UTF_8));
        List<File> files = new ArrayList<>();
        if ("pdf".equals(text)) {

            writeBytesToFileClassic(pdfbyte, tempPath + map.get("request_id") + ".pdf");
            // 解析、上传、入库
            File pdffile = new File(tempPath + map.get("request_id") + ".pdf");
            // pdf文件
            files.add(pdffile);
        } else if ("ofd".equals(text)) {
            writeBytesToFileClassic(pdfbyte, tempPath + map.get("request_id") + ".ofd");
            // 解析、上传、入库
            File ofdfile = new File(tempPath + map.get("request_id") + ".ofd");
            // pdf文件
            files.add(ofdfile);
        }
        uploadImg(files, new Date(), text);

    }

    private void writeBytesToFileClassic(byte[] bFile, String fileDest) {

        FileOutputStream fileOuputStream = null;

        try {
            fileOuputStream = new FileOutputStream(fileDest);
            fileOuputStream.write(bFile);

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fileOuputStream != null) {
                try {
                    fileOuputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 上传图片
     *
     * @param files
     * @throws Exception
     */
    public List<InvoiceElectron> uploadImg(List<File> files, Date da, String text) throws Exception {

        FileModel fileModel;
        List<InvoiceElectron> newlist = new ArrayList<>();
        // 扫描pdf文件,将pdf文件转图片并进行处理

        for (File file : files) {

            String date = new SimpleDateFormat("yyyyMMdd").format(new Date());
            InvoiceImgSavePo imgSavePo = new InvoiceImgSavePo();
            InvoiceElectron electron = new InvoiceElectron();
            String pngPath = "";
            String invoiceDate = "";
            if ("pdf".equals(text)) {

                // pdf发票解析
                PdfInvoiceModel pdfInvoiceModel = PdfUtil.pdfAnalysis(file);
                pngPath = pdfInvoiceModel.getPngPath();
                invoiceDate = pdfInvoiceModel.getInvoiceDate();
                electron.setInvoiceCode(pdfInvoiceModel.getInvoiceCode());
                electron.setInvoiceNo(pdfInvoiceModel.getInvoiceNo());
                electron.setCheckCode(pdfInvoiceModel.getCheckCode());
                try {
                    electron.setInvoiceAmount(new BigDecimal(pdfInvoiceModel.getAmount()));
                } catch (Exception e) {
                    electron.setInvoiceAmount(new BigDecimal("0"));
                }
                electron.setInvoiceType(getFplx(pdfInvoiceModel.getInvoiceCode()));
                electron.setUuid(pdfInvoiceModel.getInvoiceCode() + pdfInvoiceModel.getInvoiceNo());
            } else if ("ofd".equals(text)) {

                // ofd解析发票
                OfdInvoice ofdInvoice = ofdService.ofdAnalysis(file, false, false, false);
                pngPath = ofdInvoice.getPngPath();
                invoiceDate = ofdInvoice.getIssueDate();
                electron.setInvoiceCode(ofdInvoice.getInvoiceCode());
                electron.setInvoiceNo(ofdInvoice.getInvoiceNo());
                electron.setInvoiceType(ofdInvoice.getInvoiceType());
                electron.setCheckCode(ofdInvoice.getInvoiceCheckCode());
                try {
                    electron.setInvoiceAmount(new BigDecimal(ofdInvoice.getTaxExclusiveTotalAmount()));
                } catch (Exception e) {
                    electron.setInvoiceAmount(new BigDecimal("0"));
                }
                electron.setUuid(ofdInvoice.getInvoiceCode() + ofdInvoice.getInvoiceNo());
            }
            String imgName = new File(pngPath).getName();
            fileModel = fileService.uploadFile(fileService.getPathPrefix() + "ylimage" + date + imgName, pngPath);
            String uuid = UUID.randomUUID().toString().replace("-", "");

            electron.setCheckInvoiceDate(invoiceDate);
            if (invoiceDate.length() == 8) {
                invoiceDate =
                    invoiceDate.substring(0, 4) + "-" + invoiceDate.substring(4, 6) + "-" + invoiceDate.substring(6);
            }
            DynamicContextHolder.push(dbName + DbConstant.BUSINESS_READ);
            InvoiceElectron selectElectron =
                invoiceElectronDao.selectElectron(electron.getInvoiceCode(), electron.getInvoiceNo());
            if (selectElectron == null) {
                try {
                    electron.setCreateDate(new Date());
                    electron.setScanId(uuid);
                    electron.setInvoiceDate(DateUtils.strToDate(invoiceDate));
                    electron.setUserAccount(this.map.get("userAccount"));
                    electron.setUserName(this.map.get("userName"));
                    electron.setCompany(this.map.get("company"));
                    electron.setRequestId(this.map.get("request_id"));
                    electron.setVendorId(this.map.get("vendor_id"));
                    electron.setInvoiceSerialNo(Long.valueOf(scanIdUtils.createSerialNum()));
                    electron.setQsType("5");
                    electron.setValid("1");
                    int saveInvoice = saveInvoice(electron);
                    if (saveInvoice == 1) {
                        imgSavePo.setImagePath(fileModel.getFilePath());
                        imgSavePo.setScanId(uuid);
                        imgSavePo.setUuid(map.get("invoiceCode") + map.get("invoiceNo"));
                        imgSavePo.setCreateDate(da);
                        insertImg(imgSavePo);
                    }
                    newlist.add(electron);
                } catch (Exception e) {
                    e.printStackTrace();
                    electron.setUuid(electron.getInvoiceCode() + electron.getInvoiceNo());
                    electron.setNotes("入库失败");
                    electron.setCreateDate(da);
                    electron.setScanId(uuid);
                    updateByTimes(electron.getInvoiceCode() + electron.getInvoiceNo(), "入库失败", da, uuid);
                    imgSavePo.setImagePath(fileModel.getFilePath());
                    imgSavePo.setScanId(uuid);
                    imgSavePo.setCreateDate(da);
                    imgSavePo.setUuid(map.get("invoiceCode") + map.get("invoiceNo"));
                    insertImg(imgSavePo);
                    newlist.add(electron);
                }
            } else {
                newlist.add(selectElectron);
            }

        }

        Map<String, List<InvoiceElectron>> hashMap = new HashMap<>(16);
        hashMap.put("list", newlist);
        get(hashMap);
        return newlist;

    }

    private String getFplx(String fpdm) {
        log.info("从发票代码中获取发票类型,参数为：{}", fpdm);

        String fplx = "";
        if (fpdm.trim().length() == 12) {
            String fplxflag = fpdm.substring(7, 8);
            for (String s : FPDM_LIST) {
                if (fpdm.equals(s)) {
                    fplx = "10";
                    break;
                }
            }
            if ("0".equals(fpdm.substring(0, 1)) && "11".equals(fpdm.substring(10, 12))) {
                fplx = "10";
            }
            if ("0".equals(fpdm.substring(0, 1)) && "12".equals(fpdm.substring(10, 12))) {
                fplx = "14";
            }
            boolean r = "06".equals(fpdm.substring(10, 12)) || "07".equals(fpdm.substring(10, 12));
            if ("0".equals(fpdm.substring(0, 1)) && r) {
                // 判断是否为卷式发票 第1位为0且第11-12位为06或07
                fplx = "11";
            }
            if ("2".equals(fplxflag) && !"0".equals(fpdm.substring(0, 1))) {
                fplx = "03";
            }
            boolean r1 = "04".equals(fpdm.substring(10, 12)) || "05".equals(fpdm.substring(10, 12));
            if ("0".equals(fpdm.substring(0, 1)) && r1) {
                fplx = "04";
            }
        } else if (fpdm.trim().length() == 10) {
            String fplxflag = fpdm.substring(7, 8);
            switch (fplxflag) {
                case "1":
                case "5":
                    fplx = "01";
                    break;
                case "6":
                case "3":
                    fplx = "04";
                    break;
                case "7":
                case "2":
                    fplx = "02";
                    break;
                default:
                    break;
            }
        }
        log.info("发票类型为：{}", fplx);
        return fplx;
    }

    public void get(Map<String, List<InvoiceElectron>> hashMap) throws Exception {

        for (InvoiceElectron electron : hashMap.get("list")) {
            electron.setRequestId(this.map.get("request_id"));
            electron.setVendorId(this.map.get("vendor_id"));

            if ("10".equals(electron.getInvoiceType())) {

                String invoiceDate = new SimpleDateFormat("yyyy-MM-dd").format(electron.getInvoiceDate());
                // 判断是否重复查验
                if ("1".equals(electron.getQsStatus())) {
                    // 不再查验，只更新请求id
                    updateByRequestId(electron.getInvoiceCode() + electron.getInvoiceNo(), this.map.get("request_id"),
                        this.map.get("vendor_id"), electron.getRequestId());
                    updateByRecordInvoiceRequestId(electron.getInvoiceCode() + electron.getInvoiceNo(),
                        this.map.get("request_id"), this.map.get("vendor_id"));
                } else {
                    // 进行查验处理
                    JSONObject checkResult = invoiceQueryUtil.queryInvoice(electron.getInvoiceCode(),
                        electron.getInvoiceNo(), invoiceDate, "", electron.getCheckCode(),null,null);
                    log.info("查验返回结果：{}", checkResult);
                    checkResult.put("company", electron.getCompany());
                    checkResult.put("scanId", electron.getScanId());
                    electron.setCheckReturnCode(checkResult.getString("resultCode"));
                    if ("0001".equals(checkResult.getString("resultCode"))) {

                        RecordInvoice record = getRecordInvoice(checkResult, electron.getUserName(), "5");
                        List<RecordInvoiceDetail> detailList = getRecordInvoiceDetail(checkResult);
                        int insertRecordInvoice = 0;
                        try {
                            if (record != null) {

                                DynamicContextHolder.push(DbConstant.BASICS_READ);
                                SysDeptEntity deptEntity = sysDeptDao.getOrg(record.getGfTaxNo());
                                if (deptEntity != null) {

                                    if (!deptEntity.getTaxname().equals(record.getGfName())) {
                                        electron.setCheckReturnCode("1026");
                                        electron.setNotes("签收失败,购方名称错误");
                                        electron.setQsStatus("0");
                                        updateByInvoice(electron);
                                        continue;
                                    }
                                } else {
                                    electron.setCheckReturnCode("1007");
                                    electron.setNotes("签收失败,购方税号不在配置名单内");
                                    electron.setQsStatus("0");
                                    updateByInvoice(electron);
                                    continue;
                                }
                                if (!"0".equals(record.getInvoiceStatus())) {
                                    electron.setCheckReturnCode("1025");
                                    electron.setNotes("签收失败,此发票状态异常,请核实是否已红冲或者作废");
                                    electron.setQsStatus("0");
                                    updateByInvoice(electron);
                                    continue;

                                } else {
                                    electron.setNotes("签收成功");
                                    electron.setQsStatus("1");
                                    updateByInvoice(electron);
                                    updateByInfo(record.getGfTaxNo(), record.getXfTaxNo(), record.getTotalAmount(),
                                        record.getTaxAmount(), record.getInvoiceAmount(), record.getInvoiceDate(),
                                        record.getInvoiceCode(), record.getInvoiceNo(), record.getGfName(),
                                        record.getXfName());
                                }
                                try {
                                    record.setQsDate(DateUtils.getSqlDateLong());
                                    record.setCreateDate(DateUtils.getSqlDateLong());
                                    record.setQsName(this.map.get("userName"));
                                    record.setQsStatus("1");
                                    record.setQsType("5");
                                    record.setSourceSystem("1");
                                    record.setRequestId(this.map.get("request_id"));
                                    record.setVendorId(this.map.get("vendor_id"));
                                    record.setCompany(this.map.get("company"));
                                    insertRecordInvoice = insertRecordInvoice(record);
                                    log.debug("+++++++++" + record + "--------------");
                                    if (insertRecordInvoice == 1) {
                                        insertInvoiceDetail(record.getInvoiceCode(), record.getInvoiceNo(), detailList);
                                    }
                                } catch (Exception e) {
                                    e.printStackTrace();
                                    log.error("入库底账表失败" + e);
                                }
                            }

                        } catch (Exception e) {
                            e.printStackTrace();
                            log.debug("========================" + insertRecordInvoice);
                        }
                    } else {
                        electron.setCheckReturnCode(checkResult.getString("returnCode"));
                        electron.setNotes(checkResult.getString("returnMessage"));
                        electron.setQsStatus("0");
                        updateByInvoice(electron);
                    }
                }
            } else if ("08".equals(electron.getInvoiceType())) {

                // 电子专票对比抵账库
                if ("1".equals(electron.getQsStatus())) {
                    // 不再对比，只更新请求id
                    updateByRequestId(electron.getInvoiceCode() + electron.getInvoiceNo(), this.map.get("request_id"),
                        this.map.get("vendor_id"), electron.getRequestId());
                    updateByRecordInvoiceRequestId(electron.getInvoiceCode() + electron.getInvoiceNo(),
                        this.map.get("request_id"), this.map.get("vendor_id"));
                } else {

                    DynamicContextHolder.push(dbName + DbConstant.BUSINESS_READ);
                    RecordInvoice recordInvoice =
                        recordInvoiceDao.selectOne(new QueryWrapper<RecordInvoice>().eq("uuid", electron.getUuid()));

                    if (recordInvoice != null) {

                        DynamicContextHolder.push(DbConstant.BASICS_READ);
                        SysDeptEntity deptEntity = sysDeptDao.getOrg(recordInvoice.getGfTaxNo());
                        if (deptEntity != null) {

                            if (!deptEntity.getTaxname().equals(recordInvoice.getGfName())) {
                                electron.setCheckReturnCode("1026");
                                electron.setNotes("签收失败,购方名称错误");
                                electron.setQsStatus("0");
                                updateByInvoice(electron);
                                continue;
                            }
                        } else {
                            electron.setCheckReturnCode("1007");
                            electron.setNotes("签收失败,购方税号不在配置名单内");
                            electron.setQsStatus("0");
                            updateByInvoice(electron);
                            continue;
                        }
                        if (!"0".equals(recordInvoice.getInvoiceStatus())) {
                            electron.setCheckReturnCode("1025");
                            electron.setNotes("签收失败,此发票状态异常,请核实是否已红冲或者作废");
                            electron.setQsStatus("0");
                            updateByInvoice(electron);

                        } else {
                            electron.setCheckReturnCode("0001");
                            electron.setNotes("签收成功");
                            electron.setQsStatus("1");
                            updateByInvoice(electron);
                            updateByInfo(recordInvoice.getGfTaxNo(), recordInvoice.getXfTaxNo(),
                                recordInvoice.getTotalAmount(), recordInvoice.getTaxAmount(),
                                recordInvoice.getInvoiceAmount(), recordInvoice.getInvoiceDate(),
                                recordInvoice.getInvoiceCode(), recordInvoice.getInvoiceNo(), recordInvoice.getGfName(),
                                recordInvoice.getXfName());

                            recordInvoice.setQsDate(DateUtils.getSqlDateLong());
                            recordInvoice.setQsName(this.map.get("userName"));
                            recordInvoice.setQsStatus("1");
                            recordInvoice.setQsType("5");
                            recordInvoice.setRequestId(this.map.get("request_id"));
                            recordInvoice.setVendorId(this.map.get("vendor_id"));
                            recordInvoiceDao.update(recordInvoice,
                                new QueryWrapper<RecordInvoice>().eq("uuid", recordInvoice.getUuid()));
                        }
                    } else {

                        electron.setCheckReturnCode("0009");
                        electron.setNotes("无底账信息，签收失败");
                        electron.setQsStatus("0");
                        updateByInvoice(electron);
                    }
                }
            } else {
                // 发票类型不正确，不查验，直接存库
                electron.setCheckReturnCode("1022");
                electron.setNotes("解析失败，请联系结算员处理，谢谢！");
                electron.setQsStatus("0");
                updateByInvoice(electron);
            }

        }
    }

    public int updateByQsDate(String uuid) {
        DynamicContextHolder.push(dbName + DbConstant.BUSINESS_WRITE);
        return invoiceElectronDao.updateByQsDate(uuid);

    }

    public int updateByInfo(String gfTaxNo, String xfTaxNo, BigDecimal totalAmount, BigDecimal taxAmount,
        BigDecimal invoiceAmount, Date invoiceDate, String invoiceCode, String invoiceNo, String gfName,
        String xfName) {
        DynamicContextHolder.push(dbName + DbConstant.BUSINESS_WRITE);
        return invoiceElectronDao.updateByInfo(gfTaxNo, xfTaxNo, totalAmount, taxAmount, invoiceAmount, invoiceDate,
            invoiceCode, invoiceNo, gfName, xfName);
    }

    public int updateByInvoice(InvoiceElectron invoice) throws Exception {
        DynamicContextHolder.push(dbName + DbConstant.BUSINESS_WRITE);
        return invoiceElectronDao.updateByInvoice(invoice);
    }

    public int updateByRecordInvoice(int invoiceStatus, String uuid) throws Exception {
        DynamicContextHolder.push(dbName + DbConstant.BUSINESS_WRITE);
        return invoiceElectronDao.updateByRecordInvoice(invoiceStatus, uuid);
    }

    public int updateByRecordInvoiceRequestId(String uuid, String requestId, String vendorId) throws Exception {
        DynamicContextHolder.push(dbName + DbConstant.BUSINESS_WRITE);
        return invoiceElectronDao.updateByRecordInvoiceRequestId(uuid, requestId, vendorId);
    }

    public int insertImgLog(ElectronLog log) throws Exception {
        DynamicContextHolder.push(dbName + DbConstant.BUSINESS_WRITE);
        return invoiceElectronDao.insertImgLog(log);
    }

    public int insertRecordInvoice(RecordInvoice recordInvoice) throws Exception {
        DynamicContextHolder.push(dbName + DbConstant.BUSINESS_WRITE);
        RecordInvoice uuid =
            recordInvoiceDao.selectOne(new QueryWrapper<RecordInvoice>().eq("uuid", recordInvoice.getUuid()));
        if (uuid != null) {
            return recordInvoiceDao.update(recordInvoice,
                new QueryWrapper<RecordInvoice>().eq("uuid", recordInvoice.getUuid()));
        } else {

            return recordInvoiceDao.insert(recordInvoice);
        }
    }

    public void insertInvoiceDetail(String invoiceCode, String invoiceNo, List<RecordInvoiceDetail> detailList)
        throws Exception {
        DynamicContextHolder.push(dbName + DbConstant.DETAIL_WRITE);
        invoiceDetailDao.delete(new QueryWrapper<RecordInvoiceDetail>().eq("uuid", invoiceCode + invoiceNo));
        for (RecordInvoiceDetail recordInvoiceDetail : detailList) {
            recordInvoiceDetail.setUuid(invoiceCode + invoiceNo);
            recordInvoiceDetail.setInvoiceCode(invoiceCode);
            recordInvoiceDetail.setInvoiceNo(invoiceNo);
            invoiceDetailDao.insert(recordInvoiceDetail);
        }

    }

    /**
     * 查验结果
     *
     * @param checkParams
     * @return
     * @throws Exception
     */
    public List<RecordInvoice> getCheck(List<CheckInvoiceParam> checkParams) throws Exception {
        List<FP> check = checkSerivice.getCheck(checkParams);
        return checkSerivice.toToRecordInvoices(check);
    }

    /**
     * 解析数据转换类
     *
     * @param entity
     * @param uuid
     * @param date
     * @return
     * @throws Exception
     */
    public InvoiceElectron getInvoiceSavePo(FPEntity entity, String uuid, Date date) throws Exception {

        InvoiceElectron invoicePo = new InvoiceElectron();
        // 购方信息
        if (StringUtils.isNotBlank(entity.getBuyer_name())) {
            invoicePo.setGfName(entity.getBuyer_name());
        } else {
            invoicePo.setGfName("");
        }
        if (StringUtils.isNotBlank(entity.getBuyer_nsrsbh())) {
            invoicePo.setGfTaxNo(entity.getBuyer_nsrsbh());
        } else {
            invoicePo.setGfTaxNo("");
        }

        if (StringUtils.isNotBlank(entity.getSeller_nsrsbh())) {
            invoicePo.setXfTaxNo(entity.getSeller_nsrsbh());
        } else {
            invoicePo.setXfTaxNo("");
        }

        invoicePo.setInvoiceType("10");
        Date kprq = null;
        try {
            kprq = new SimpleDateFormat("yyyy年MM月dd日").parse(entity.getKprq());
        } catch (Exception e) {
            if (StringUtils.isNotBlank(entity.getKprq())) {
                kprq = new SimpleDateFormat("yyyyMMdd").parse(entity.getKprq());
            } else {
                String dateKprq = new SimpleDateFormat("yyyyMMdd").format(new Date());
                kprq = new SimpleDateFormat("yyyyMMdd").parse(dateKprq);
            }
        }
        invoicePo.setInvoiceDate(kprq);
        boolean flag = false;
        try {
            invoicePo.setInvoiceAmount(new BigDecimal(entity.getHjje()));
        } catch (Exception e) {
            invoicePo.setInvoiceAmount(new BigDecimal("0"));
            // flag = true;
        }

        try {
            invoicePo.setTaxAmount(new BigDecimal(entity.getHjse()));
        } catch (Exception e) {
            invoicePo.setTaxAmount(new BigDecimal("0"));
            // flag = true;
        }
        try {
            invoicePo.setTotalAmount(new BigDecimal(entity.getJshj()));
        } catch (Exception e) {
            invoicePo.setTotalAmount(new BigDecimal("0"));
            // flag = true;
        }
        if (StringUtils.isBlank(entity.getFpdm())) {
            flag = true;
        }
        if (StringUtils.isBlank(entity.getFphm())) {
            flag = true;
        }

        if (flag) {
            invoicePo.setNotes("发票扫描异常");
        } else {
            invoicePo.setNotes("未签收");
        }
        // 生成随机发票代码
        if (StringUtils.isNotBlank(entity.getFpdm())) {
            invoicePo.setInvoiceCode(entity.getFpdm());
        } else {
            invoicePo.setInvoiceCode(sjnum12());
        }
        // 生成随机发票号吗
        if (StringUtils.isNotBlank(entity.getFphm())) {
            invoicePo.setInvoiceNo(entity.getFphm());
        } else {
            invoicePo.setInvoiceNo(sjnum8());
        }

        if (StringUtils.isNotBlank(entity.getJym())) {
            invoicePo.setCheckCode(entity.getJym().substring(entity.getJym().length() - 6));
        } else {
            invoicePo.setCheckCode(sjnum8());
        }

        if (StringUtils.isNotBlank(entity.getFpdm()) && StringUtils.isNotBlank(entity.getFphm())) {
            invoicePo.setUuid(entity.getFpdm() + entity.getFphm());
        } else {
            invoicePo.setUuid(invoicePo.getInvoiceCode() + invoicePo.getInvoiceNo());
        }
        invoicePo.setQsStatus("0");
        // 获取扫描时间
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String scanDateStr = sdf.format(new Date());
        invoicePo.setScanId(uuid);
        invoicePo.setCreateDate(date);

        return invoicePo;
    }

    /**
     * 10位随机数
     *
     * @return
     */
    public String sjnum12() {
        int[] a = new int[10];
        StringBuilder sjnum = new StringBuilder();
        ThreadLocalRandom tlr = ThreadLocalRandom.current();
        for (int i = 0; i < a.length; i++) {
            a[i] = (int)(10 * (tlr.nextDouble(1)));
            sjnum.append(a[i]);
        }
        return sjnum.toString();
    }

    public String sjnum8() {
        int[] a = new int[8];
        StringBuilder sjnum = new StringBuilder();
        ThreadLocalRandom tlr = ThreadLocalRandom.current();
        for (int i = 0; i < a.length; i++) {
            a[i] = (int)(8 * (tlr.nextDouble(1)));
            sjnum.append(a[i]);
        }
        return sjnum.toString();
    }

    public void insertImg(InvoiceImgSavePo invoiceImg) throws Exception {
        DynamicContextHolder.push(dbName + DbConstant.BUSINESS_WRITE);
        invoiceImgDao.insert(invoiceImg);
    }

    public int saveInvoice(InvoiceElectron electron) throws Exception {
        DynamicContextHolder.push(dbName + DbConstant.BUSINESS_WRITE);
        return invoiceElectronDao.insert(electron);
    }

    public int updateByNote(String note, String uuid) throws Exception {
        DynamicContextHolder.push(dbName + DbConstant.BUSINESS_WRITE);
        return invoiceElectronDao.updateByNote(uuid, note);
    }

    public int updateByCheckReturnCode(String note, String uuid, String returnCode, String requestId, String vendorId)
        throws Exception {
        DynamicContextHolder.push(dbName + DbConstant.BUSINESS_WRITE);
        return invoiceElectronDao.updateByCheckReturnCode(uuid, note, returnCode, requestId, vendorId);
    }

    public int updateByRequestId(String uuid, String requestId, String vendorId, String oldRequestId) throws Exception {
        DynamicContextHolder.push(dbName + DbConstant.BUSINESS_WRITE);
        return invoiceElectronDao.updateByRequestId(uuid, requestId, vendorId, oldRequestId);
    }

    public int updateByTimes(String uuid, String note, Date createDate, String scanId) throws Exception {
        DynamicContextHolder.push(dbName + DbConstant.BUSINESS_WRITE);
        return invoiceElectronDao.updateByTimes(createDate, note, uuid, scanId);
    }

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

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

        invoice.setInvoiceType(invoiceType);
        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.YQS.getQsjgDm());
        invoice.setQsType(qsType);
        invoice.setValid("1");
        invoice.setQsName(userName);
        invoice.setRzhYesorno("0");
        invoice.setAuthStatus("0");
        invoice.setScanId(queryInvoiceResult.getString("scanId"));
        return invoice;
    }

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

}
