package com.dxhy.erp.service.impl;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.date.DateUtil;
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.dxhy.api.model.db.TDxTaxCurrentEntity;
import com.dxhy.api.model.config.sys.SysEnterpriseConfigDto;
import com.dxhy.api.model.invoice.TDxRecordInvoice;
import com.dxhy.common.constant.DbConstant;
import com.dxhy.common.datasource.config.DynamicContextHolder;
import com.dxhy.common.enums.*;
import com.dxhy.common.service.InvoiceLogService;
import com.dxhy.common.service.impl.MpBaseServiceImpl;
import com.dxhy.common.util.*;
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.*;
import com.dxhy.erp.model.auth.InterfaceCode;
import com.dxhy.erp.service.SignDataService;
import com.dxhy.erp.utils.CheckUtils;
import com.dxhy.erp.utils.InvoiceQueryUtil;
import com.dxhy.jxpt.baseService.ncpInvoice.dao.TdxTaxCurrentDao;
import com.dxhy.oss.model.FileModel;
import com.dxhy.oss.service.FileService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.FileCopyUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.math.BigDecimal;
import java.nio.charset.StandardCharsets;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author jiaohongyang
 */
@SuppressWarnings({"AlibabaUndefineMagicConstant", "AlibabaMethodTooLong"})
@Service("signDataService")
@Slf4j
public class SignDataServiceImpl extends MpBaseServiceImpl<TdxInvoiceDao, InvoiceElectron> implements SignDataService {
    @Autowired
    private SysEnterpriseConfigErpDao enterpriseConfigErpDao;

    @Autowired
    private TdxRecordInvoiceErpDao tDxrecordInvoiceDao;

    @Autowired
    private TdxTaxCurrentDao taxCurrentDao;

    @Autowired
    private InvoiceLogService invoiceLogService;

    @Autowired
    private ScanIdUtils scanIdUtils;

    @Autowired
    private InvoiceDetailDao invoiceDetailDao;

    @Autowired
    private InvoiceImgDao invoiceImgDao;

    @Autowired
    private TdxCheckRecordInvoiceDao checkRecordInvoiceDao;

    @Autowired
    private InvoiceQueryUtil invoiceQueryUtil;

    @Autowired
    private FileService fileService;

    @Value("${erp.collectNum}")
    private String returnCount;

    @Override
    public String getInvoice(GlobalInfo globalInfo, Map<String, String> map, HttpServletRequest request,
        HttpServletResponse response, Authorize authorize) {
        ReturnStateInfo run = new ReturnStateInfo();
        List<InvoiceElectron> list;
        CollectData data = null;
        try {
            data = JSON.parseObject(map.get("data"), CollectData.class);
            run = getCheck(data);
            if (run.getReturnCode() != null || run.getReturnMessage() != null) {
                InterfaceCode interfaceCode = new InterfaceCode();
                interfaceCode.setGlobalInfo(globalInfo);
                interfaceCode.setReturnStateInfo(run);
                return JSON.toJSONString(interfaceCode);
            }

            DynamicContextHolder.push(DbConstant.BASICS_READ);
            SysEnterpriseConfigDto deptEntity = enterpriseConfigErpDao.getOrg(data.getBuyerTaxNo());
            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 interfaceCode = new InterfaceCode();
                interfaceCode.setGlobalInfo(globalInfo);
                interfaceCode.setReturnStateInfo(runInfo);
                return JSON.toJSONString(interfaceCode);
            }
            Integer total = 0;
            try {

                DynamicContextHolder.push(dbName + DbConstant.BUSINESS_READ);
                total = selectByAllCount(data);
            } catch (Exception e) {
                log.info("获取总条数错误：" + e);
               log.info("业务处理异常：{}", e);
            }
            // if ("1".equals(data.getStatus())){

            int startRow = data.getStartRow();
            if (startRow <= 0) {
                startRow = 1;
            }
            int endRow = 0;
            String requestRow = data.getRequestRow();
            if (StringUtils.isNotBlank(requestRow)) {
                if (Integer.parseInt(returnCount) > Integer.parseInt(requestRow)) {

                    endRow = Integer.parseInt(requestRow);
                }

            } else {
                endRow = Integer.parseInt(returnCount);
            }
            // 01回传信息
            List<InvoiceInfo> invoices = new ArrayList<>();
            DynamicContextHolder.push(dbName + DbConstant.BUSINESS_READ);
            list = selectByParam(data, startRow, endRow);
            log.info("-----------获取签收发票完成----------" + globalInfo.getDataExchangeId());
            startRow += list.size();
            for (InvoiceElectron info : list) {
                InvoiceInfo invoiceInfo = getInvoiceInfo(info);
                invoices.add(invoiceInfo);
            }

            log.info("===========签收发票实体转换完成============" + globalInfo.getDataExchangeId());
            GatherData gather = new GatherData();
            gather.setStartRow(data.getStartRow());
            gather.setTotalRows(total);
            gather.setContentRows(invoices.size());
            if (invoices.size() > 0) {
                gather.setInvoices(invoices);
            }

            if (startRow > total) {
                gather.setStatus("0");
            } else {
                gather.setStatus("1");
            }

            String result = JSON.toJSONString(gather);
            run.setReturnCode(ReturnCodeEnum.CLCG.getFhzDm());
            run.setReturnMessage(ReturnCodeEnum.CLCG.getFhzMc(ReturnCodeEnum.CLCG.getIndex()));
            InterfaceCode interfaceCode = new InterfaceCode();
            interfaceCode.setGlobalInfo(globalInfo);
            interfaceCode.setReturnStateInfo(run);
            interfaceCode.setData(Base64.encode(result));
            return JSON.toJSONString(interfaceCode);

        } catch (Exception e) {
           log.info("业务处理异常：{}", e);
            run.setReturnCode("2011");
            run.setReturnMessage("其他异常");
            String globalJson = null;
            String runJson = null;
            try {
                runJson = JSON.toJSONString(run);
                globalJson = JSON.toJSONString(globalInfo);
            } catch (Exception ignored) {
            }
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json; charset=utf-8");
            return "{\"globalInfo\":" + globalJson + ",\"returnStateInfo\":" + runJson + "}";
        }
    }

    public InvoiceInfo getInvoiceInfo(InvoiceElectron invoice) {
        InvoiceInfo info = new InvoiceInfo();
        if(StringUtils.isNotBlank(invoice.getInvoiceCode())){
            info.setInvoiceCode(invoice.getInvoiceCode());
        }else {
            info.setInvoiceCode("");
        }
        info.setInvoiceNo(invoice.getInvoiceNo());
        info.setInvoiceDate(new SimpleDateFormat("yyyyMMdd").format(invoice.getInvoiceDate()));
        DecimalFormat df = new DecimalFormat("0.00");
        try {

            info.setInvoiceAmount(df.format(invoice.getInvoiceAmount()));
        } catch (Exception e) {
            info.setInvoiceAmount("0.00");
        }
        try {

            info.setTaxAmount(df.format(invoice.getTaxAmount()));
        } catch (Exception e) {
            info.setTaxAmount("0.00");
        }
        try {
            info.setTotalAmount(df.format(invoice.getTotalAmount()));

        } catch (Exception e) {
            info.setTotalAmount("0.00");
        }
        info.setQsStatus(invoice.getQsStatus());
        info.setQsDate(new SimpleDateFormat("yyyyMMddHHmmss").format(invoice.getQsDate()));
        info.setNotes(invoice.getNotes());
        info.setQsUser(invoice.getUserName());
        return info;
    }

    public Integer selectByAllCount(CollectData data) throws Exception {
        Map<String, Object> map = new HashMap<>(7);
        map.put("buyerTaxNo", data.getBuyerTaxNo());
        map.put("startRow", data.getStartRow());
        map.put("requestRow", data.getRequestRow());
        map.put("qsStatus", data.getQsStatus());
        map.put("qsDateBegin", data.getQsDateBegin());
        map.put("qsDateEnd", data.getQsDateEnd());
        map.put("qsUser", data.getQsUser());
        return super.baseMapper.selectAllCount(map);
    }

    public List<InvoiceElectron> selectByParam(CollectData data, Integer start, Integer num) throws Exception {
        Map<String, Object> map = new HashMap<>(9);
        map.put("buyerTaxNo", data.getBuyerTaxNo());
        map.put("startRow", data.getStartRow());
        map.put("requestRow", data.getRequestRow());
        map.put("qsStatus", data.getQsStatus());
        map.put("qsDateBegin", data.getQsDateBegin());
        map.put("qsDateEnd", data.getQsDateEnd());
        map.put("qsUser", data.getQsUser());
        map.put("start", start - 1);
        map.put("num", num);
        return super.baseMapper.selectByParam(map);
    }

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

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

        if (CheckUtils.isNullOrEmpty(data.getQsDateBegin()) || (!CheckUtils.stringLength(data.getQsDateBegin(), 14))) {
            run.setReturnCode(ReturnCodeEnum.QSRQBNWK.getFhzDm());
            run.setReturnMessage(ReturnCodeEnum.QSRQBNWK.getFhzMc(ReturnCodeEnum.QSRQBNWK.getIndex()));
        }
        if (CheckUtils.isNullOrEmpty(data.getQsDateEnd()) || (!CheckUtils.stringLength(data.getQsDateEnd(), 14))) {
            run.setReturnCode(ReturnCodeEnum.JSRQBNWK.getFhzDm());
            run.setReturnMessage(ReturnCodeEnum.JSRQBNWK.getFhzMc(ReturnCodeEnum.JSRQBNWK.getIndex()));
        }
        if (CheckUtils.isNullOrEmpty(data.getStatus()) || (!CheckUtils.stringLength(data.getStatus(), 1))) {
            run.setReturnCode(ReturnCodeEnum.ZTBZBNWK.getFhzDm());
            run.setReturnMessage(ReturnCodeEnum.ZTBZBNWK.getFhzMc(ReturnCodeEnum.ZTBZBNWK.getIndex()));
        }
        if (!CheckUtils.checkNum(data.getStartRow())) {
            run.setReturnCode(ReturnCodeEnum.KSHSCW.getFhzDm());
            run.setReturnMessage(ReturnCodeEnum.KSHSCW.getFhzMc(ReturnCodeEnum.KSHSCW.getIndex()));
        }
        return run;
    }

    public ReturnStateInfo signCheck(CollectData data) {
        ReturnStateInfo run = new ReturnStateInfo();
        if (CheckUtils.isNullOrEmpty(data.getBatchNo()) || (!CheckUtils.stringLength(data.getBatchNo(), 32))
            || data.getContentRows() == null) {
            run.setReturnCode(ReturnCodeEnum.PCHBNWK.getFhzDm());
            run.setReturnMessage(ReturnCodeEnum.PCHBNWK.getFhzMc(ReturnCodeEnum.PCHBNWK.getIndex()));
            return run;
        }
        if (CheckUtils.isNullOrEmpty(data.getBuyerTaxNo())) {
            run.setReturnCode(ReturnCodeEnum.SHBNWK.getFhzDm());
            run.setReturnMessage(ReturnCodeEnum.SHBNWK.getFhzMc(ReturnCodeEnum.SHBNWK.getIndex()));
            return run;
        }

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

//        QueryWrapper<SysUserEntity> query = new QueryWrapper<>();
////        query.eq("username", data.getQsUser());
//        query.eq("loginname", data.getQsUser());
//        SysUserEntity userEntity = userDao.selectOne(query);
//
//        if (userEntity == null) {
//            run.setReturnCode(ReturnCodeEnum.QSRBNWK.getFhzDm());
//            run.setReturnMessage(ReturnCodeEnum.QSRBNWK.getFhzMc(ReturnCodeEnum.QSRBNWK.getIndex()));
//        }
        return run;
    }

    public ReturnStateInfo getInfoCheck(CollectData data) {
        ReturnStateInfo run = new ReturnStateInfo();
        if (CheckUtils.isNullOrEmpty(data.getBatchNo()) || (!CheckUtils.stringLength(data.getBatchNo(), 32))) {
            run.setReturnCode(ReturnCodeEnum.PCHBNWK.getFhzDm());
            run.setReturnMessage(ReturnCodeEnum.PCHBNWK.getFhzMc(ReturnCodeEnum.PCHBNWK.getIndex()));
            return run;
        }
        if (CheckUtils.isNullOrEmpty(data.getBuyerTaxNo())) {
            run.setReturnCode(ReturnCodeEnum.SHBNWK.getFhzDm());
            run.setReturnMessage(ReturnCodeEnum.SHBNWK.getFhzMc(ReturnCodeEnum.SHBNWK.getIndex()));
            return run;
        }
        return run;
    }

    public ReturnStateInfo getImgCheck(CollectData data) {
        ReturnStateInfo run = new ReturnStateInfo();

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

//        if (CheckUtils.isNullOrEmpty(data.getInvoiceCode())) {
//            run.setReturnCode(ReturnCodeEnum.FPDMBNWK.getFhzDm());
//            run.setReturnMessage(ReturnCodeEnum.FPDMBNWK.getFhzMc(ReturnCodeEnum.FPDMBNWK.getIndex()));
//            return run;
//        }

        if (CheckUtils.isNullOrEmpty(data.getInvoiceNo())) {
            run.setReturnCode(ReturnCodeEnum.FPHMBNWK.getFhzDm());
            run.setReturnMessage(ReturnCodeEnum.FPHMBNWK.getFhzMc(ReturnCodeEnum.FPHMBNWK.getIndex()));
            return run;
        } else {
            if (!CheckUtils.stringLength(data.getInvoiceNo(), 20)) {
                if (CheckUtils.isNullOrEmpty(data.getInvoiceCode())) {
                    run.setReturnCode(ReturnCodeEnum.FPDMBNWK.getFhzDm());
                    run.setReturnMessage(ReturnCodeEnum.FPDMBNWK.getFhzMc(ReturnCodeEnum.FPDMBNWK.getIndex()));
                    return run;
                }
            }
        }

        if (CheckUtils.isNullOrEmpty(data.getImgType())) {
            run.setReturnCode(ReturnCodeEnum.TPBZBNWK.getFhzDm());
            run.setReturnMessage(ReturnCodeEnum.TPBZBNWK.getFhzMc(ReturnCodeEnum.TPBZBNWK.getIndex()));
            return run;
        }
        return run;
    }

    @Override
    public String signInvoice(GlobalInfo globalInfo, Map<String, String> map, HttpServletRequest request,
        HttpServletResponse response, Authorize authorize) {
        ReturnStateInfo run = new ReturnStateInfo();
        CollectData data = null;
        try {
            data = JSON.parseObject(map.get("data"), CollectData.class);
            run = signCheck(data);
            if (run.getReturnCode() != null || run.getReturnMessage() != null) {
                InterfaceCode interfaceCode = new InterfaceCode();
                interfaceCode.setGlobalInfo(globalInfo);
                interfaceCode.setReturnStateInfo(run);
                return JSON.toJSONString(interfaceCode);
            }

            DynamicContextHolder.push(DbConstant.BASICS_READ);
            SysEnterpriseConfigDto deptEntity = enterpriseConfigErpDao.getOrg(data.getBuyerTaxNo());

            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 interfaceCode = new InterfaceCode();
                interfaceCode.setGlobalInfo(globalInfo);
                interfaceCode.setReturnStateInfo(runInfo);
                return JSON.toJSONString(interfaceCode);
            }

            List<InvoiceSavePo> list = data.getInvoices();

            if (list != null && list.size() > 0) {
                for (InvoiceSavePo paramInvoice : list) {
                    String invoiceType = paramInvoice.getInvoiceType();;
                    String invoiceCode = paramInvoice.getInvoiceCode();
                    String invoiceNo = paramInvoice.getInvoiceNo();
                    String uuid =invoiceCode + invoiceNo;
//                    if((StringUtils.isNotBlank(paramInvoice.getInvoiceType()))&&("31".equals(paramInvoice.getInvoiceType()) || "32".equals(paramInvoice.getInvoiceType()))){
//                        invoiceType = paramInvoice.getInvoiceType();
//                        uuid = invoiceNo;
//                    }else if(StringUtils.isNotBlank(paramInvoice.getInvoiceCode())) {
//                        invoiceCode = paramInvoice.getInvoiceCode();
//                        InvoiceUtil iu = new InvoiceUtil(invoiceCode);
//                        invoiceType = iu.getFplxdm();
//                        uuid = invoiceCode + invoiceNo;
//                    }else {
//                        invoiceType = "01";
//                    }

                    String invoiceDate = paramInvoice.getInvoiceDate();
                    if (invoiceDate.length() > 6) {
                        invoiceDate = invoiceDate.substring(0, 4) + "-" + invoiceDate.substring(4, 6) + "-"
                            + invoiceDate.substring(6);

                    }
                    BigDecimal invoiceAmount = paramInvoice.getInvoiceAmount();
                    String checkCode = paramInvoice.getCheckCode();
                    String img = paramInvoice.getImg();

                    InvoiceElectron invoice = new InvoiceElectron();
                    invoice.setUuid(uuid);
                    invoice.setBatchNo(data.getBatchNo());
                    invoice.setCheckCode(checkCode);
                    invoice.setInvoiceCode(invoiceCode);
                    invoice.setInvoiceNo(invoiceNo);
                    invoice.setInvoiceType(invoiceType);
                    try {
                        invoice.setInvoiceDate(new SimpleDateFormat("yyyy-MM-dd").parse(invoiceDate));

                    } catch (Exception e) {
                       log.info("业务处理异常：{}", e);
                        invoice.setInvoiceDate(new Date());
                    }
                    invoice.setQsDate(DateUtils.getSqlDateLong());
                    invoice.setInvoiceAmount(invoiceAmount);
                    // 手工签收
                    invoice.setQsType("6");
                    invoice.setValid("1");
                    invoice.setScanId(UUID.randomUUID().toString());
//                    invoice.setUserAccount(userEntity.getUserId().toString());
                    invoice.setUserName(data.getQsUser());

                    InvoiceElectron scaninfo = this.getScaninfo(uuid, dbName);

                    if (scaninfo == null || !"1".equals(scaninfo.getQsStatus())) {
                        TDxRecordInvoice record = getRecord(uuid, dbName);
                        // 专、机、通对比底账
                        if (FplxEnum.ZP.getFplxDm().equals(invoiceType) || FplxEnum.TXF.getFplxDm().equals(invoiceType)
                            || FplxEnum.JDC.getFplxDm().equals(invoiceType)|| FplxEnum.ZZDZ.getFplxDm().equals(invoiceType)
                            || FplxEnum.TLKP.getFplxDm().equals(invoiceType)|| FplxEnum.HKDZFP.getFplxDm().equals(invoiceType)
                            || FplxEnum.DZZP.getFplxDm().equals(invoiceType) || FplxEnum.QDZZP.getFplxDm().equals(invoiceType)) {

                            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
                            Date start = null;

                            if (record != null) {
                                log.info("票种:{}。走底账签收",invoiceType);

                                invoice.setCompany(deptEntity.getCompany());

                                DynamicContextHolder.push(dbName + DbConstant.BUSINESS_READ);
                                QueryWrapper<TDxTaxCurrentEntity> queryWrapper = new QueryWrapper<>();
                                queryWrapper.eq("taxno", record.getGfTaxNo());
                                final String scanInvoiceDate = new DateTime(invoiceDate).toString("yyyyMMdd");
                                final String recordInvoiceDate =
                                    new DateTime(record.getInvoiceDate()).toString("yyyyMMdd");
                                try {
                                    TDxTaxCurrentEntity taxCurrent = taxCurrentDao.selectOne(queryWrapper);
                                    if (taxCurrent != null) {
                                        // 当前税款所属期勾选起始日期
                                        String startDate = taxCurrent.getSelectStartDate();
                                        startDate = startDate.substring(0, 4) + "-" + startDate.substring(4, 6) + "-"
                                            + startDate.substring(6);
                                        start = df.parse(startDate);
                                    }

                                    if (!scanInvoiceDate.equals(recordInvoiceDate)) {

                                        // 传入的开票日期和底账表不一致
                                        invoice.setNotes("传入的开票日期与底账信息不一致");
                                        invoice.setQsStatus(FpqsjgEnum.WQS.getQsjgDm());
                                    } else if (invoiceAmount != null) {
                                        /**
                                         * 发票类型 01 03 为不含税金额
                                         * 发票类型31 32 161 283为含税金额必填
                                         **/
                                        if(FplxEnum.ZP.getFplxDm().equals(invoiceType)||FplxEnum.JDC.getFplxDm().equals(invoiceType)){
                                            if(!(MathUtil.round(invoiceAmount.toPlainString())
                                                    .equals(MathUtil.round(record.getInvoiceAmount().toPlainString())))){
                                                // 传入的金额和底账表不一致
                                                invoice.setNotes("传入的金额与底账信息不一致");
                                                invoice.setQsStatus(FpqsjgEnum.WQS.getQsjgDm());
                                            }
                                        }else if(FplxEnum.QDZZP.getFplxDm().equals(invoiceType)||FplxEnum.QDPP.getFplxDm().equals(invoiceType)
                                            ||FplxEnum.HKDZFP.getFplxDm().equals(invoiceType)||FplxEnum.TLKP.getFplxDm().equals(invoiceType)
                                        ){
                                            if(!(MathUtil.round(invoiceAmount.toPlainString())
                                                    .equals(MathUtil.round(record.getTotalAmount().toPlainString())))){
                                                // 传入的金额和底账表的价税合计不一致
                                                invoice.setNotes("传入的金额与底账信息不一致");
                                                invoice.setQsStatus(FpqsjgEnum.WQS.getQsjgDm());
                                            }
                                        }

                                    }

                                    if (!"0".equals(record.getInvoiceStatus())) {
                                        // 发票状态异常
                                        String zt = "";
                                        for (FpztEnum e : FpztEnum.values()) {
                                            if (e.getFpztDm().equals(record.getInvoiceStatus())) {
                                                zt = e.getFpztMc(e.getIndex());
                                            }
                                        }
                                        invoice.setNotes("非正常发票不能签收，当前的发票状态:" + zt);
                                        invoice.setQsStatus(FpqsjgEnum.WQS.getQsjgDm());
                                    } else if (start != null && record.getInvoiceDate().before(start)) {
                                        invoice.setNotes("发票已逾期，签收失败");
                                        invoice.setQsStatus(FpqsjgEnum.WQS.getQsjgDm());

                                    } else {
                                        DynamicContextHolder.push(dbName + DbConstant.BUSINESS_WRITE);
                                        TDxRecordInvoice invoiceUpdate = new TDxRecordInvoice();
                                        invoiceUpdate.setId(record.getId());
                                        invoiceUpdate.setQsStatus(FpqsjgEnum.YQS.getQsjgDm());
                                        invoiceUpdate.setQsType("6");
                                        invoiceUpdate.setQsDate(DateUtils.getSqlDateLong());
                                        invoiceUpdate.setLastUpdateDate(new Date());
                                        invoiceUpdate.setQsName(data.getQsUser());

                                        tDxrecordInvoiceDao.updateById(invoiceUpdate);

                                        invoice.setInvoiceAmount(record.getInvoiceAmount());
                                        invoice.setTaxAmount(record.getTaxAmount());
                                        invoice.setGfName(record.getGfName());
                                        invoice.setGfTaxNo(record.getGfTaxNo());
                                        invoice.setXfName(record.getXfName());
                                        invoice.setXfTaxNo(record.getXfTaxNo());
                                        invoice.setQsStatus(FpqsjgEnum.YQS.getQsjgDm());
                                        invoice.setInvoiceDate(record.getInvoiceDate());
                                        invoice.setInvoiceStatus(record.getInvoiceStatus());
                                        invoice.setTotalAmount(record.getTotalAmount());
                                        invoice.setCheckCode(record.getCheckCode());
                                        invoice.setNotes("签收成功");

                                        // 增加发票签收日志
                                        InvoiceLog log = new InvoiceLog();
                                        log.setInputName(data.getQsUser());
                                        log.setInputStatus("1");
                                        log.setInvoiceCode(invoiceCode);
                                        log.setInvoiceNo(invoiceNo);
                                        log.setQsType("6");
                                        log.setType("3");
                                        log.setCreateDate(new Date());
                                        List<InvoiceLog> logs = new ArrayList<>();
                                        logs.add(log);
                                        invoiceLogService.toInvoiceLog(logs);
                                    }

                                } catch (ParseException e1) {

                                    e1.printStackTrace();
                                }
                            } else {
                                invoice.setNotes("无底账信息，签收失败");
                                invoice.setQsStatus(FpqsjgEnum.WQS.getQsjgDm());

                            }

                        } else {// 普、电、卷查验

                            // 调用查验接口查询发票信息
                            JSONObject checkResult = invoiceQueryUtil.queryInvoice(invoiceCode, invoiceNo,
                                paramInvoice.getInvoiceDate(), String.valueOf(paramInvoice.getInvoiceAmount()), checkCode,data.getBuyerTaxNo(),invoiceType);

                            if ("0001".equals(checkResult.getString("resultCode"))) {

                                invoice.setNotes(checkResult.getString("resultTip"));
                                // 查验成功且信息一致，直接保存到底账表并签收
                                // 查验返回的购方税号
                                String checkGfsh = checkResult.getString("buyerTaxNo");
                                // 查验返回的购方名称
                                String checkGfmc = checkResult.getString("buyerName");
                                // 查验返回的作废标志
                                String zfbz = checkResult.getString("isCancelled");
                                // 查验返回的税额
                                String taxAmount = checkResult.getString("taxAmount");
                                if (StringUtils.isNotBlank(taxAmount)) {
                                    invoice.setTaxAmount(new BigDecimal(taxAmount));
                                }

                                invoice.setCompany(deptEntity.getCompany());

                                if (!("N".equals(zfbz) || "0".equals(zfbz))) {
                                    // 作废发票无法签收，发票查验接口只返回了作废状态，未返回其它异常状态
                                    invoice.setQsStatus(FpqsjgEnum.WQS.getQsjgDm());
                                    invoice.setNotes("签收失败！发票状态异常");
                                } else {

                                    invoice.setQsStatus(FpqsjgEnum.YQS.getQsjgDm());
                                    checkResult.put("company", deptEntity.getCompany());
                                    checkResult.put("scanId", invoice.getScanId());
                                    if (record == null) {
                                        DynamicContextHolder.push(dbName + DbConstant.BUSINESS_READ);
                                        TDxRecordInvoice insertRecord = getRecordInvoice(checkResult, data.getQsUser(), "6");
                                        DynamicContextHolder.push(dbName + DbConstant.BUSINESS_WRITE);
                                        int insert = tDxrecordInvoiceDao.insert(insertRecord);
                                        if (insert > 0) {
                                            List<RecordInvoiceDetail> detailList = getRecordInvoiceDetail(checkResult);
                                            DynamicContextHolder.push(dbName + DbConstant.DETAIL_WRITE);
                                            invoiceDetailDao
                                                .delete(new QueryWrapper<RecordInvoiceDetail>().eq("uuid", uuid));
                                            for (RecordInvoiceDetail detailInfo : detailList) {
                                                detailInfo.setInvoiceCode(insertRecord.getInvoiceCode());
                                                detailInfo.setInvoiceNo(insertRecord.getInvoiceNo());
                                                detailInfo.setUuid(uuid);
                                                invoiceDetailDao.insert(detailInfo);
                                            }
                                        }
                                    } else {
                                        if ("Y".equals(checkResult.getString("isCancelled"))) {
                                            invoice.setInvoiceStatus(FpztEnum.ZF.getFpztDm(FpztEnum.ZF.getIndex()));
                                        } else if ("N".equals(checkResult.getString("isCancelled"))) {
                                            invoice.setInvoiceStatus(FpztEnum.ZC.getFpztDm(FpztEnum.ZC.getIndex()));
                                        } else {
                                            invoice.setInvoiceStatus(checkResult.getString("isCancelled"));
                                        }
                                        record.setLastUpdateDate(new Date());
                                        record.setQsDate(DateUtils.getSqlDateLong());
                                        record.setQsStatus(FpqsjgEnum.YQS.getQsjgDm());
                                        record.setQsType("6");
                                        record.setQsName(data.getQsUser());
                                        record.setScanId(invoice.getScanId());
                                        DynamicContextHolder.push(dbName + DbConstant.BUSINESS_WRITE);
                                        tDxrecordInvoiceDao.updateById(record);
                                    }

                                    // 增加发票签收日志
                                    InvoiceLog log = new InvoiceLog();
                                    log.setInputName(data.getQsUser());
                                    log.setInputStatus("1");
                                    log.setInvoiceCode(invoiceCode);
                                    log.setInvoiceNo(invoiceNo);
                                    log.setQsType("6");
                                    log.setType("3");
                                    log.setCreateDate(new Date());
                                    List<InvoiceLog> logs = new ArrayList<>();
                                    logs.add(log);
                                    invoiceLogService.toInvoiceLog(logs);
                                }
                                invoice.setGfName(checkGfmc);
                                invoice.setGfTaxNo(checkGfsh);
                                invoice.setXfName(checkResult.getString("salerName"));
                                invoice.setXfTaxNo(checkResult.getString("salerTaxNo"));
                                invoice.setTotalAmount(checkResult.getBigDecimal("totalAmount"));
                                invoice.setInvoiceAmount(checkResult.getBigDecimal("invoiceAmount"));
                                invoice.setInvoiceRemark(checkResult.getString("remark"));

                                //重置代码号码，数电号码字段
                                String checkinvoiceType = checkResult.getString("invoiceType");
                                if("32".equals(checkinvoiceType)){
                                    String checkinvoiceCode = checkResult.getString("invoiceCode");
                                    String checkinvoiceNo = checkResult.getString("invoiceNo");
                                    String checkuuid = (StringUtils.isEmpty(checkinvoiceCode)?"":checkinvoiceCode) + checkinvoiceNo;
                                    //32 数电普
                                    invoice.setEleInvoiceNo(checkuuid);
                                    invoice.setInvoiceCode(uuid.substring(0,12));
                                    invoice.setInvoiceNo(uuid.substring(12,20));
                                }

                            } else {
                                // 调用查验接口失败，进入查验失败处理流程
                                invoice.setNotes(checkResult.getString("returnMessage"));
                                invoice.setQsStatus(FpqsjgEnum.WQS.getQsjgDm());

                            }
                        }

                        DynamicContextHolder.push(dbName + DbConstant.BUSINESS_WRITE);
                        if (scaninfo != null) {
                            invoice.setId(scaninfo.getId());
                            invoice.setUpdateDate(DateUtils.getSqlDateLong());
                            super.updateById(invoice);
                        } else {
                            invoice.setCreateDate(DateUtils.getSqlDateLong());
                            invoice.setInvoiceSerialNo(Long.valueOf(scanIdUtils.createSerialNum()));

                            super.save(invoice);
                        }
                    } else {
                        log.info("发票已签收成功:代码{}号码{}",scaninfo.getInvoiceCode(),scaninfo.getInvoiceNo());
                        continue;
                    }
                    // 图片上传入库
                    if (img != null && !"".equals(img)) {
                        byte[] imgbyte = Base64.decode(img.getBytes(StandardCharsets.UTF_8));
                        writeBytesToFileClassic(imgbyte,
                            fileService.getLocalPathDefault() + invoice.getScanId() + ".jpg");

                        File imgfile = new File(fileService.getLocalPathDefault() + invoice.getScanId() + ".jpg");

                        String imgPath;
                        String date = new SimpleDateFormat("yyyyMMdd").format(new Date());
                        InvoiceImgSavePo imgSavePo = new InvoiceImgSavePo();
                        String uploadName = fileService.getPathPrefix() + data.getQsUser() + date + imgfile.getName();
                        FileModel fileModel = fileService.uploadFile(uploadName, imgfile.getPath());

                        imgSavePo.setCreateDate(DateUtils.getSqlDateLong());
                        imgSavePo.setImagePath(fileModel.getFilePath());
                        imgSavePo.setScanId(invoice.getScanId());
//                        imgSavePo.setUuid(invoiceCode + invoiceNo);
                        imgSavePo.setUuid(uuid);
                        imgSavePo.setValid(1);

                        DynamicContextHolder.push(dbName + DbConstant.BUSINESS_WRITE);
                        invoiceImgDao.insert(imgSavePo);

                    }

                }
            }

            run.setReturnCode("0000");
            run.setReturnMessage("处理成功");
            String globalJson = null;
            String runJson = null;
            try {
                runJson = JSON.toJSONString(run);
                globalJson = JSON.toJSONString(globalInfo);
            } catch (Exception e1) {
            }
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json; charset=utf-8");
            return "{\"globalInfo\":" + globalJson + ",\"returnStateInfo\":" + runJson + "}";
        } catch (Exception e) {
           log.info("业务处理异常：{}", e);
            run.setReturnCode("2011");
            run.setReturnMessage("其他异常");
            String globalJson = null;
            String runJson = null;
            try {
                runJson = JSON.toJSONString(run);
                globalJson = JSON.toJSONString(globalInfo);
            } catch (Exception e1) {
            }
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json; charset=utf-8");
            return "{\"globalInfo\":" + globalJson + ",\"returnStateInfo\":" + runJson + "}";
        }
    }

    public static void main(String[] args) {
        if(true){
            System.out.println("1");
        }else if(true){
            System.out.println("2");

        }else if (false){
            System.out.println("3");

        }else if(true){
            System.out.println("3");

        }
    }

    @Override
    public String revokeSign(GlobalInfo globalInfo, Map<String, String> map, HttpServletRequest request,
        HttpServletResponse response, Authorize authorize) {
        ReturnStateInfo run = new ReturnStateInfo();
        InterfaceCode interfaceCode = new InterfaceCode();
        RevokeSignReq revokeSignReq = null;
        try {
            revokeSignReq = JSONObject.parseObject(map.get("data"), RevokeSignReq.class);
        } 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 (StringUtils.isBlank(revokeSignReq.getBuyerTaxNo())) {
                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);
            SysEnterpriseConfigDto deptEntity = enterpriseConfigErpDao.getOrg(revokeSignReq.getBuyerTaxNo());
            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);
            }
            if (StringUtils.isBlank(revokeSignReq.getBatchNo()) || revokeSignReq.getContentRows() == null) {
                run.setReturnCode(ReturnCodeEnum.PCHBNWK.getFhzDm());
                run.setReturnMessage(ReturnCodeEnum.PCHBNWK.getFhzMc(ReturnCodeEnum.PCHBNWK.getIndex()));
                interfaceCode.setGlobalInfo(globalInfo);
                interfaceCode.setReturnStateInfo(run);
                interfaceCode.setData("");
                return JSONObject.toJSONString(interfaceCode, SerializerFeature.WriteMapNullValue);
            }
            DynamicContextHolder.push(dbName + DbConstant.BUSINESS_READ);

            List<RevokeSignData> inAccountList = revokeSignReq.getInvoices();
            if (inAccountList.size() != revokeSignReq.getContentRows()) {
                run.setReturnCode(ReturnCodeEnum.NRYCY.getFhzDm());
                run.setReturnMessage(ReturnCodeEnum.NRYCY.getFhzMc(ReturnCodeEnum.NRYCY.getIndex()));
                interfaceCode.setReturnStateInfo(run);
                interfaceCode.setGlobalInfo(globalInfo);
                interfaceCode.setData("");
                return JSONObject.toJSONString(interfaceCode, SerializerFeature.WriteMapNullValue);
            }
            List<RevokeSignData> accountReturnList = new ArrayList<>();
            List<InvoiceLog> logs = new ArrayList<>();
            for (RevokeSignData revokeSignData : inAccountList) {
                if (StringUtils.isBlank(revokeSignData.getInvoiceCode())
                    || StringUtils.isBlank(revokeSignData.getInvoiceNo())) {
                    revokeSignData.setStatus("1");
                    revokeSignData.setFailureReason("9");
                    accountReturnList.add(revokeSignData);
                    continue;
                }
                // 判断抵帐表是否有票
                QueryWrapper<TDxRecordInvoice> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("uuid", revokeSignData.getInvoiceCode() + revokeSignData.getInvoiceNo());
                TDxRecordInvoice recordInvoice = tDxrecordInvoiceDao.selectOne(queryWrapper);
                if (recordInvoice == null) {
                    log.info("线程{},抵账无此票{}", Thread.currentThread().getId(),
                        revokeSignData.getInvoiceCode() + revokeSignData.getInvoiceNo());
                    revokeSignData.setStatus("1");
                    revokeSignData.setFailureReason("2");
                } else {
                    if (!"1".equals(recordInvoice.getQsStatus())) {
                        revokeSignData.setStatus("1");
                        revokeSignData.setFailureReason("3");
                        accountReturnList.add(revokeSignData);
                        continue;
                    } else {
                        // 更新底账表签收状态为未签收
                        recordInvoice.setQsStatus("0");
                        recordInvoice.setQsDate(null);
                        recordInvoice.setQsType(null);
                        recordInvoice.setQsName(null);
                        recordInvoice.setLastUpdateDate(new Date());
                        tDxrecordInvoiceDao.updateById(recordInvoice);
                        InvoiceElectron invoice = new InvoiceElectron();
                        invoice.setQsStatus("0");
                        invoice.setNotes("取消签收");
                        invoice.setUserName(null);
                        QueryWrapper<InvoiceElectron> invoiceElectronQueryWrapper = new QueryWrapper<>();
                        invoiceElectronQueryWrapper.eq("uuid", recordInvoice.getUuid());
                        super.update(invoice, invoiceElectronQueryWrapper);
                        revokeSignData.setStatus("0");
                        revokeSignData.setFailureReason("");
                        // 增加发票日志
                        InvoiceLog log = new InvoiceLog();
                        log.setInputName("system");
                        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);
                    }
                }
                accountReturnList.add(revokeSignData);
            }
            invoiceLogService.toInvoiceLog(logs);
            // 返回报文拼接
            RevokeSignReq revokeSignRes = new RevokeSignReq();
            revokeSignRes.setBatchNo(revokeSignReq.getBatchNo());
            revokeSignRes.setBuyerTaxNo(revokeSignReq.getBuyerTaxNo());
            revokeSignRes.setInvoices(accountReturnList);
            String data = JSON.toJSONString(revokeSignRes);
            run.setReturnCode(ReturnCodeEnum.CLCG.getFhzDm());
            run.setReturnMessage(ReturnCodeEnum.CLCG.getFhzMc(ReturnCodeEnum.CLCG.getIndex()));
            interfaceCode.setReturnStateInfo(run);
            interfaceCode.setGlobalInfo(globalInfo);
            interfaceCode.setData(Base64.encode(data));
            return JSONObject.toJSONString(interfaceCode, SerializerFeature.WriteMapNullValue);
        } catch (Exception e) {
           log.info("业务处理异常：{}", e);
            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);
        }
    }

    @Override
    public String getInvoiceByBatchNo(GlobalInfo globalInfo, Map<String, String> map, HttpServletRequest request,
        HttpServletResponse response, Authorize authorize) {
        ReturnStateInfo run = new ReturnStateInfo();
        CollectData data = null;
        try {
            data = JSON.parseObject(map.get("data"), CollectData.class);
            run = getInfoCheck(data);
            if (run.getReturnCode() != null || run.getReturnMessage() != null) {
                InterfaceCode interfaceCode = new InterfaceCode();
                interfaceCode.setGlobalInfo(globalInfo);
                interfaceCode.setReturnStateInfo(run);
                return JSON.toJSONString(interfaceCode);
            }

            DynamicContextHolder.push(DbConstant.BASICS_READ);
            SysEnterpriseConfigDto deptEntity = enterpriseConfigErpDao.getOrg(data.getBuyerTaxNo());
            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 interfaceCode = new InterfaceCode();
                interfaceCode.setGlobalInfo(globalInfo);
                interfaceCode.setReturnStateInfo(runInfo);
                return JSON.toJSONString(interfaceCode);
            }

            DynamicContextHolder.push(dbName + DbConstant.BUSINESS_READ);
            QueryWrapper<InvoiceElectron> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("batch_no", data.getBatchNo());

            List<InvoiceElectron> list = super.list(queryWrapper);
            List<ReturnInvoice> returnInvoices = new ArrayList<>();

            if (list.size() > 0) {

                for (InvoiceElectron electron : list) {
                    ReturnInvoice invoice = toInvoice(electron);
                    returnInvoices.add(invoice);
                }
            }

            String result = JSON.toJSONString(returnInvoices);
            run.setReturnCode(ReturnCodeEnum.CLCG.getFhzDm());
            run.setReturnMessage(ReturnCodeEnum.CLCG.getFhzMc(ReturnCodeEnum.CLCG.getIndex()));
            InterfaceCode interfaceCode = new InterfaceCode();
            interfaceCode.setGlobalInfo(globalInfo);
            interfaceCode.setReturnStateInfo(run);
            interfaceCode.setData(Base64.encode(result.getBytes(StandardCharsets.UTF_8)));
            return JSON.toJSONString(interfaceCode);

        } catch (Exception e) {
           log.info("业务处理异常：{}", e);
            run.setReturnCode("2011");
            run.setReturnMessage("其他异常");
            String globalJson = null;
            String runJson = null;

            runJson = JSON.toJSONString(run);
            globalJson = JSON.toJSONString(globalInfo);

            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json; charset=utf-8");
            return "{\"globalInfo\":" + globalJson + ",\"returnStateInfo\":" + runJson + "}";
        }

    }

    @Override
    public String getImg(GlobalInfo globalInfo, Map<String, String> map, HttpServletRequest request,
        HttpServletResponse response, Authorize authorize) {
        ReturnStateInfo run = new ReturnStateInfo();
        CollectData data = null;
        String timeString = DateUtil.formatDate(DateUtil.date());
        try {
            data = JSON.parseObject(map.get("data"), CollectData.class);
            run = getImgCheck(data);
            if (run.getReturnCode() != null || run.getReturnMessage() != null) {
                InterfaceCode interfaceCode = new InterfaceCode();
                interfaceCode.setGlobalInfo(globalInfo);
                interfaceCode.setReturnStateInfo(run);
                return JSON.toJSONString(interfaceCode);
            }

            DynamicContextHolder.push(DbConstant.BASICS_READ);
            SysEnterpriseConfigDto deptEntity = enterpriseConfigErpDao.getOrg(data.getBuyerTaxNo());
            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 interfaceCode = new InterfaceCode();
                interfaceCode.setGlobalInfo(globalInfo);
                interfaceCode.setReturnStateInfo(runInfo);
                return JSON.toJSONString(interfaceCode);
            }

            String imgType = data.getImgType();
            String uuid = (StringUtils.isBlank(data.getInvoiceCode())?"":data.getInvoiceCode()) + data.getInvoiceNo();

            FileModel fileModel = null;
            if (imgType != null && !"".equals(imgType)) {

                // 签收扫描图片
                if ("0".equals(imgType)) {
                    DynamicContextHolder.push(dbName + DbConstant.BUSINESS_READ);
                    QueryWrapper<InvoiceElectron> queryWrapper = new QueryWrapper<>();
                    queryWrapper.eq("uuid", uuid);
                    InvoiceElectron one = super.getOne(queryWrapper);

                    if (one != null) {

                        InvoiceImgQueryVo img = invoiceImgDao.getImg(one.getScanId());

                        if (img != null) {
                            // zip下载解压后删除
                            if (img.getImagePath().contains(".zip")) {
                                String fileName = img.getImagePath().substring(img.getImagePath().lastIndexOf("/"));
                                String localPath = fileService.getLocalPathDefault() + timeString + File.separator
                                    + fileName;
                                fileModel = fileService.downFile(img.getImagePath(), localPath);

                                File localZipFile = new File(localPath);
                                List<String> zip = FileUtils.unZip(localZipFile, localPath);
                                reName(zip.get(0), uuid + ".jpg");
                                localZipFile.delete();
                            } else {
                                // jpg直接下载
                                String fileName = img.getImagePath().substring(img.getImagePath().lastIndexOf("/"));
                                fileModel = fileService.downFile(img.getImagePath(),
                                    fileService.getLocalPathDefault() + timeString + "/" + fileName);

                            }
                        }
                    } else {
                        ReturnStateInfo runInfo = new ReturnStateInfo();
                        runInfo.setReturnCode(ReturnCodeEnum.FPBCZ.getFhzDm());
                        runInfo.setReturnMessage(ReturnCodeEnum.FPBCZ.getFhzMc(ReturnCodeEnum.FPBCZ.getIndex()));
                        InterfaceCode interfaceCode = new InterfaceCode();
                        interfaceCode.setGlobalInfo(globalInfo);
                        interfaceCode.setReturnStateInfo(runInfo);
                        return JSON.toJSONString(interfaceCode);
                    }
                    // 查验扫描图片
                } else if ("1".equals(imgType)) {
                    DynamicContextHolder.push(dbName + DbConstant.BUSINESS_READ);
                    QueryWrapper<TdxCheckRecordInvoice> queryWrapper = new QueryWrapper<>();
                    queryWrapper.eq("uuid", uuid);

                    TdxCheckRecordInvoice checkRecord = checkRecordInvoiceDao.selectOne(queryWrapper);

                    if (checkRecord != null) {

                        InvoiceImgQueryVo img = invoiceImgDao.getImg(checkRecord.getScanId());

                        if (img != null) {
                            String fileName = img.getImagePath().substring(img.getImagePath().lastIndexOf("/"));
                            fileModel = fileService.downFile(img.getImagePath(),
                                    fileService.getLocalPathDefault() + timeString + "/" + fileName);
                        }
                    } else {
                        ReturnStateInfo runInfo = new ReturnStateInfo();
                        runInfo.setReturnCode(ReturnCodeEnum.FPBCZ.getFhzDm());
                        runInfo.setReturnMessage(ReturnCodeEnum.FPBCZ.getFhzMc(ReturnCodeEnum.FPBCZ.getIndex()));
                        InterfaceCode interfaceCode = new InterfaceCode();
                        interfaceCode.setGlobalInfo(globalInfo);
                        interfaceCode.setReturnStateInfo(runInfo);
                        return JSON.toJSONString(interfaceCode);
                    }
                }

            }

            InputStream fis = null;
            // String result =null;
            byte[] bytes = null;
            try {
                fis = new FileInputStream(fileModel.getFilePath());
                bytes = FileCopyUtils.copyToByteArray(fis);

            } catch (Exception e) {
                if(fileModel==null){
                    log.info("未找到文件或下载失败");
                }
               log.info("业务处理异常：{}", e);
            } finally {
                fis.close();
            }
            InvoiceSavePo returnImg = new InvoiceSavePo();
            returnImg.setInvoiceCode(data.getInvoiceCode());
            returnImg.setInvoiceNo(data.getInvoiceNo());
            returnImg.setImg(Base64.encode(bytes));
            run.setReturnCode(ReturnCodeEnum.CLCG.getFhzDm());
            run.setReturnMessage(ReturnCodeEnum.CLCG.getFhzMc(ReturnCodeEnum.CLCG.getIndex()));
            InterfaceCode interfaceCode = new InterfaceCode();
            interfaceCode.setGlobalInfo(globalInfo);
            interfaceCode.setReturnStateInfo(run);
            interfaceCode.setData(Base64.encode(JSON.toJSONString(returnImg)));
            return JSON.toJSONString(interfaceCode);
        } catch (Exception e) {
           log.info("业务处理异常：{}", e);
            run.setReturnCode("2011");
            run.setReturnMessage("其他异常");
            String globalJson = null;
            String runJson = null;

            runJson = JSON.toJSONString(run);
            globalJson = JSON.toJSONString(globalInfo);

            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json; charset=utf-8");
            return "{\"globalInfo\":" + globalJson + ",\"returnStateInfo\":" + runJson + "}";
        }

    }

    /**
     * 根据uuid查询扫描信息
     *
     * @param uuid
     * @return
     *
     */
    private InvoiceElectron getScaninfo(String uuid, String dbName) {
        DynamicContextHolder.push(dbName + DbConstant.BUSINESS_READ);
        // 直接查询扫描表是否存在信息
        QueryWrapper<InvoiceElectron> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("uuid", uuid);
        return this.getOne(queryWrapper);
    }

    private TDxRecordInvoice getRecord(String uuid, String dbName) {
        DynamicContextHolder.push(dbName + DbConstant.BUSINESS_READ);
        QueryWrapper<TDxRecordInvoice> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("uuid", uuid);

        return tDxrecordInvoiceDao.selectOne(queryWrapper);
    }

    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 = (StringUtils.isEmpty(invoiceCode)?"":invoiceCode) + invoiceNo;

        invoice.setInvoiceType(invoiceType);
        if(!"32".equals(invoiceType)){
            invoice.setInvoiceCode(invoiceCode);
            invoice.setInvoiceNo(invoiceNo);
        }else {
            //32 数电普
            invoice.setEleInvoiceNo(uuid);
            invoice.setInvoiceCode(uuid.substring(0,12));
            invoice.setInvoiceNo(uuid.substring(12,20));
        }
        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.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;
    }

    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);
                    if("32".equals(invoiceType)){
                        invoiceDetail.setInvoiceNo(uuid);
                    }else {
                        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;
        }
    }

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

        FileOutputStream fileOuputStream = null;

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

        } catch (IOException e) {
           log.info("业务处理异常：{}", e);
        } finally {
            if (fileOuputStream != null) {
                try {
                    fileOuputStream.close();
                } catch (IOException e) {
                   log.info("业务处理异常：{}", e);
                }
            }
        }
    }

    private ReturnInvoice toInvoice(InvoiceElectron electron) {
        ReturnInvoice invoice = new ReturnInvoice();
        invoice.setBatchNo(electron.getBatchNo());
        if(StringUtils.isNotBlank(electron.getInvoiceCode())){
            invoice.setInvoiceCode(electron.getInvoiceCode());
        }else {
            invoice.setInvoiceCode("");
        }
        invoice.setInvoiceNo(electron.getInvoiceNo());
        invoice.setNotes(electron.getNotes());
        invoice.setQsDate(new SimpleDateFormat("yyyyMMddHHmmss").format(electron.getQsDate()));
        invoice.setQsStatus(electron.getQsStatus());

        return invoice;
    }

    /**
     * 文件重命名
     *
     * @param path
     * @param newname
     * @return
     */
    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;
        }

    }

}
