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

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.dxhy.api.model.config.Business;
import com.dxhy.api.model.config.Tax;
import com.dxhy.api.model.config.UserInfo;
import com.dxhy.api.model.invoice.TDxRecordInvoice;
import com.dxhy.api.model.sign.*;
import com.dxhy.common.constant.DbConstant;
import com.dxhy.common.constant.DictConstant;
import com.dxhy.common.datasource.config.DynamicContextHolder;
import com.dxhy.common.enums.FplxEnum;
import com.dxhy.common.enums.FpqsjgEnum;
import com.dxhy.common.enums.FpztEnum;
import com.dxhy.common.enums.QsfsEnum;
import com.dxhy.common.service.DictdetaServcice;
import com.dxhy.common.service.InvoiceLogService;
import com.dxhy.common.service.TabulateRedisService;
import com.dxhy.common.service.impl.MpBaseServiceImpl;
import com.dxhy.common.util.*;
import com.dxhy.common.utils.BaseContextHandler;
import com.dxhy.common.utils.CommonUtil;
import com.dxhy.common.utils.DateUtils;
import com.dxhy.common.utils.LocalTrmSeqNum;
import com.dxhy.common.vo.InvoiceLog;
import com.dxhy.jxpt.baseService.sign.dao.SignInvoiceDao;
import com.dxhy.jxpt.baseService.sign.dao.SignInvoiceDelDao;
import com.dxhy.jxpt.baseService.sign.dao.SignInvoiceImgDao;
import com.dxhy.jxpt.baseService.sign.dao.SignRecordInvoiceDao;
import com.dxhy.jxpt.baseService.sign.service.elec.SignElecInvoiceService;
import com.dxhy.jxpt.baseService.sign.service.fpqs.FpqsService;
import com.dxhy.jxpt.baseService.sign.service.fpqs.SignFpqsService;
import com.dxhy.jxpt.baseService.sign.service.singletable.SignInvoiceService;
import com.dxhy.jxpt.baseService.sign.service.singletable.SignInvoiceStatisticsService;
import com.dxhy.jxpt.baseService.sign.service.singletable.SignSaveInvoiceInfoService;
import com.dxhy.jxpt.baseService.sign.service.singletable.SignScanInvoiceLogService;
import com.dxhy.jxpt.baseService.util.CompareNameUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 发票签收业务逻辑处理实现类
 *
 * @author jiaohongyang
 */
@Service("signFpqsService")
@Slf4j
@SuppressWarnings({"AlibabaUndefineMagicConstant", "AlibabaMethodTooLong", "AlibabaCollectionInitShouldAssignCapacity",
        "AlibabaStringConcat", "AlibabaCollectionInitShouldAssignCapacity"})
public class SignFpqsServiceImpl extends MpBaseServiceImpl<SignRecordInvoiceDao, TDxRecordInvoice>
        implements SignFpqsService {

    @Resource
    private SignInvoiceService signInvoiceSmService;

    @Resource
    private SignSaveInvoiceInfoService signSaveInvoiceInfoService;

    @Resource
    private SignScanInvoiceLogService signScanInvoiceLogService;

    @Resource
    private SignElecInvoiceService signElecInvoiceService;

    @Resource
    private InvoiceLogService invoiceLogService;

    @Resource
    private SignInvoiceDao signInvoiceDao;

    @Resource
    private SignInvoiceDelDao signInvoiceDelDao;

    @Resource
    private ScanIdUtils scanIdUtils;

    @Resource
    private TabulateRedisService tabulateRedisService;

    @Resource
    private SignInvoiceStatisticsService signInvoiceStatisticsService;
    @Resource
    private DictdetaServcice dictdetaServcice;
    @Resource
    private FpqsService fpqsService;

    @Autowired
    private SignInvoiceImgDao signInvoiceImgDao;

    @Override
    public String selectWqsfp(Map<String, Object> pramsMap, int curr, int size) {
        List<Object> returnList = new ArrayList<>();
        DynamicContextHolder.push(pramsMap.get("dbName") + DbConstant.BUSINESS_READ);
        String company = (String)pramsMap.get("company");
        String menuId = (String)pramsMap.get("menuId");
        JSONObject json = tabulateRedisService.getTabulateMenu(company, menuId);

        List<String> gfshList = (List<String>)pramsMap.get("gfsh");

        if (gfshList.size() == 0) {
            // 未从getUserInfo()获取到购方税号信息
            json.put("hjsl", "0");
            json.put("hjje", "0.00");
            json.put("hjse", "0.00");
            json.put("total", "0");
            json.put("datalist", new ArrayList<SgqsWqsfpVO>());
        } else {
            // 合计信息,仅第一页时需要统计，减少数据库压力
            if (curr == 1) {
                long hjsl;
                String hjje = "0.00";
                String hjse = "0.00";
                List<TDxRecordInvoice> hjList = super.baseMapper.selectWqsfpHj(pramsMap);
                TDxRecordInvoice hjxx = hjList.get(0);
                hjsl = hjxx.getId();
                if (hjsl != 0) {
                    hjje = AmountFormatUtil.fmtMicrometer(MathUtil.round(hjxx.getInvoiceAmount().toPlainString()));
                    hjse = AmountFormatUtil.fmtMicrometer(MathUtil.round(hjxx.getTaxAmount().toPlainString()));
                }
                json.put("hjsl", hjsl);
                json.put("hjje", hjje);
                json.put("hjse", hjse);
                if (0 == hjsl) {
                    json.put("total", 0);
                    json.put("datalist", returnList);
                    return super.responseResult(json);
                }
            }

            PageHelper.startPage(curr, size);
            List<TDxRecordInvoice> pageList = super.baseMapper.selectWqsfp(pramsMap);
            PageInfo<TDxRecordInvoice> pageInfo = new PageInfo<>(pageList);
            List<TDxRecordInvoice> resultList = pageInfo.getList();

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

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

                int start = new Long(pageInfo.getStartRow()).intValue();

                for (int i = 0; i < resultList.size(); i++) {
                    SgqsWqsfpVO mxlb = this.convertToMxlbView(resultList.get(i), start + i);
                    returnList.add(mxlb);
                }
            }
            json.put("datalist", returnList);
        }

        return super.responseResult(json);
    }

    /**
     * 转换为页面需要的显示对象
     *
     * @param tDxRecordInvoice
     *            底账数据
     * @param i
     *            i
     * @return 返回
     */
    private SgqsWqsfpVO convertToMxlbView(TDxRecordInvoice tDxRecordInvoice, int i) {

        SgqsWqsfpVO wqsfp = new SgqsWqsfpVO();
        wqsfp.setId(String.valueOf(tDxRecordInvoice.getId()));
        wqsfp.setXh(String.valueOf(i));
        wqsfp.setInvoiceType(tDxRecordInvoice.getInvoiceType());
        wqsfp.setInvoiceCode(tDxRecordInvoice.getInvoiceCode());
        wqsfp.setInvoiceNo(tDxRecordInvoice.getInvoiceNo());
        wqsfp.setEleInvoiceNo(tDxRecordInvoice.getEleInvoiceNo());
        wqsfp.setInvoiceDate(DateUtils.dateToStr(tDxRecordInvoice.getInvoiceDate()));
        String qsztDm = tDxRecordInvoice.getQsStatus();
        if (FpqsjgEnum.YQS.getQsjgDm().equals(qsztDm)) {
            wqsfp.setQsStatus(FpqsjgEnum.YQS.getQsjgMc(FpqsjgEnum.YQS.getIndex()));
        } else {
            wqsfp.setQsStatus(FpqsjgEnum.WQS.getQsjgMc(FpqsjgEnum.WQS.getIndex()));
        }
        wqsfp.setXfName(tDxRecordInvoice.getXfName());
        wqsfp.setGfName(tDxRecordInvoice.getGfName());
        if(ObjectUtil.isNotEmpty(tDxRecordInvoice.getInvoiceAmount())){
            wqsfp.setInvoiceAmount(
                    AmountFormatUtil.fmtMicrometer(MathUtil.round(tDxRecordInvoice.getInvoiceAmount().toPlainString())));
        }
        if(ObjectUtil.isNotEmpty(tDxRecordInvoice.getTaxAmount())){
            wqsfp.setTaxAmount(
                    AmountFormatUtil.fmtMicrometer(MathUtil.round(tDxRecordInvoice.getTaxAmount().toPlainString())));
        }

        return wqsfp;
    }

    @Override
    public String qsWqsfp(JSONArray detailArray, Map<String, String> pramsMap, UserInfo userInfo) {

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

        List<Long> idList = new ArrayList<>(detailArray.size());
        for (Object o : detailArray) {
            JSONObject idJson = (JSONObject)o;
            idList.add(idJson.getLong("id"));
        }
        int failureCount = 0;
        int succeeCount = 0;
        // 查询底账信息
        Collection<TDxRecordInvoice> recordList = super.listByIds(idList);

        for (TDxRecordInvoice recode : recordList) {
            String invoiceType = recode.getInvoiceType();
            // 拼装需要的参数信息
            if(StringUtils.isNotBlank( recode.getInvoiceCode())){
                pramsMap.put("invoiceCode", recode.getInvoiceCode());
            }
            pramsMap.put("invoiceNo", recode.getInvoiceNo());
            //如果是全电
            if(FplxEnum.QDZZP.equals(invoiceType)||FplxEnum.QDPP.equals(invoiceType)
                    ||FplxEnum.TLKP.equals(invoiceType)||FplxEnum.HKDZFP.equals(invoiceType)||FplxEnum.JDCDZ.equals(invoiceType)){
                if(recode.getInvoiceNo().length()==20){
                    pramsMap.put("invoiceCode", recode.getInvoiceNo().substring(0,12));
                    pramsMap.put("invoiceNo", recode.getInvoiceNo().substring(12, 20));
                }
            }

            pramsMap.put("eleInvoiceNo", recode.getEleInvoiceNo());
            // 根据发票代码识别发票类型
//            InvoiceUtil iu = new InvoiceUtil(recode.getInvoiceCode());
//            String invoiceType = iu.getFplxdm();

            pramsMap.put("invoiceDate", DateUtils.dateToStr(recode.getInvoiceDate()));
            if (ObjectUtil.isNotEmpty(recode.getInvoiceAmount())) {
                pramsMap.put("invoiceAmount", recode.getInvoiceAmount().toPlainString());
            }
            if (ObjectUtil.isNotEmpty(recode.getTotalAmount())) {
                pramsMap.put("totalAmount", recode.getTotalAmount().toPlainString());
            }
            if (ObjectUtil.isNotEmpty(recode.getTaxAmount())) {
                pramsMap.put("taxAmount", recode.getTaxAmount().toPlainString());
            }
            if (StringUtils.isNotBlank(recode.getGfName())) {
                pramsMap.put("gfName", recode.getGfName());
            }
            if (StringUtils.isNotBlank(recode.getGfTaxNo())) {
                pramsMap.put("gfsh", recode.getGfTaxNo());
            }
            if (StringUtils.isNotBlank(recode.getXfName())) {
                pramsMap.put("xfName", recode.getXfName());
            }
            if (StringUtils.isNotBlank(recode.getXfTaxNo())) {
                pramsMap.put("xfsh", recode.getXfTaxNo());
            }
            pramsMap.put("xxly", recode.getXxly());

            Object[] objects = fpqsService.zpSaveInvoice(pramsMap, userInfo, QsfsEnum.SGQS.getQsfsDm(), invoiceType,null);
            boolean result = (Boolean)objects[0];
            // 签收成功
            if (result) {
                succeeCount++;
            } else {
                // 签收失败
                failureCount++;
            }
        }
        return "签收成功:" + succeeCount + "条; \n 签收失败:" + failureCount + "条";
    }

    @Override
    public String smqsQsfp(Map<String, String> pramsMap, UserInfo userInfo) {
        String invoiceCode = pramsMap.get("invoiceCode");
        String invoiceNo = pramsMap.get("invoiceNo");
        String uuid =(StringUtils.isBlank(invoiceCode)?"":invoiceCode) + invoiceNo;

        //从抵账库获取种类代码
        DynamicContextHolder.push(userInfo.getDbName() + DbConstant.BUSINESS_READ);
        QueryWrapper<TDxRecordInvoice> invoiceWrapper = new QueryWrapper<>();
        invoiceWrapper.lambda().eq(TDxRecordInvoice::getUuid, uuid);
        TDxRecordInvoice selrecordInvoice = super.getOne(invoiceWrapper);
        boolean dkdj = false;
        String invoiceType = "";
        boolean recordHaveDate = false;
        InvoiceUtil iu = new InvoiceUtil(invoiceCode);
        //发票类型，先查底账，没有再走工具类判断
        if(ObjectUtil.isNotNull(selrecordInvoice)){
            invoiceType = selrecordInvoice.getInvoiceType();
            recordHaveDate = true;
            if("4".equals(selrecordInvoice.getXxly())){
                //发票属于代扣代缴，直接走底账签收
                dkdj = true;
                pramsMap.put("xxly", selrecordInvoice.getXxly());
            }
        }else{
            invoiceType = iu.getFplxdm();
        }

        String company = pramsMap.get("company");
        String menuId = pramsMap.get("menuId");
        if(FplxEnum.QDZZP.getFplxDm().equals(pramsMap.get("invoiceType")) || FplxEnum.QDPP.getFplxDm().equals(pramsMap.get("invoiceType"))){
            invoiceType = pramsMap.get("invoiceType");
        }
        pramsMap.put("invoiceType", invoiceType);
        pramsMap.put("uuid", uuid);
        pramsMap.put("scanId", UUID.randomUUID().toString());
        JSONObject json = tabulateRedisService.getTabulateMenu(company, menuId);

        TDxInvoice tDxInvoice = this.initQsjl(pramsMap);

        List<SmqsWqsfpVO> returnList = new ArrayList<>();
        // 签收返回数据信息
        Object[] result = new Object[3];
        result[0] = false;
        if(ObjectUtil.isNotNull(selrecordInvoice)){
            result[0] = true;
        }
        JSONObject jsonObject = null;
        //if(FplxEnum.QDZZP.getFplxDm().equals(invoiceType) || FplxEnum.QDPP.getFplxDm().equals(invoiceType)){
        if(!recordHaveDate&&invoiceNo.length()==20){
            log.info("抵账库没有，且属于全电专普，走查验获取票种");
            result[0] = true;
            jsonObject = fpqsService.checkInvoice(pramsMap, userInfo, QsfsEnum.SMQS.getQsfsDm(), invoiceType);
            String resultCode = jsonObject.getString("resultCode");
            if (jsonObject.containsKey("returnCode")) {
                result[0] = false;
                result[1] = jsonObject.getString("returnMessage");
            }else if (!"0001".equals(resultCode)) {
                result[0] = false;
                result[1] = jsonObject.getString("resultTip");
            }
            if(StringUtils.isNotBlank(jsonObject.getString("invoiceType"))){
                invoiceType = jsonObject.getString("invoiceType");
            }
        }
        // 底账表签收校验
        if (FplxEnum.ZP.getFplxDm().equals(invoiceType) || FplxEnum.TXF.getFplxDm().equals(invoiceType)
                || FplxEnum.JDC.getFplxDm().equals(invoiceType) || FplxEnum.DZZP.getFplxDm().equals(invoiceType)
                || FplxEnum.ZZDZ.getFplxDm().equals(invoiceType)|| FplxEnum.TLKP.getFplxDm().equals(invoiceType)|| FplxEnum.HKDZFP.getFplxDm().equals(invoiceType)
                || (FplxEnum.QDZZP.getFplxDm().equals(invoiceType) && (Boolean) result[0])
                || FplxEnum.SDFP_JDCTYXSFP.getFplxDm().equals(invoiceType)|| FplxEnum.ZZJDC.getFplxDm().equals(invoiceType)|| FplxEnum.ESCDZ.getFplxDm().equals(invoiceType)|| FplxEnum.ZZESC.getFplxDm().equals(invoiceType)
                || dkdj
            ) {
            result = fpqsService.zpSaveInvoice(pramsMap, userInfo, QsfsEnum.SMQS.getQsfsDm(), invoiceType,jsonObject);
        } else if ((FplxEnum.QDPP.getFplxDm().equals(invoiceType)) && (Boolean) result[0]) {
            /**
            * @Description 全电普票 此处存在两种情况，
             * 1底账有。invoiceType是32，(Boolean) result[0]是true
             * 2底账无。能进来此处是查验成功,invoiceType是32，(Boolean) result[0]是true。
            * @param pramsMap
            * @param userInfo
            * @Return java.lang.String
            * @Author wangruwei
            * @Date 2023/4/20 16:09
            **/
            log.info("全电普票签收");
            if(ObjectUtil.isNotNull(selrecordInvoice)){
                log.info("底账存在，用抵账库信息去签收");
                result = fpqsService.zpSaveInvoice(pramsMap, userInfo, QsfsEnum.SMQS.getQsfsDm(), invoiceType,jsonObject);
            }else{
            //else if((Boolean) result[0]){
                log.info("底账没有，查验成功，用查验数据开始签收");
                result = fpqsService.qdSaveInvoice(pramsMap, userInfo, QsfsEnum.SMQS.getQsfsDm(), invoiceType,jsonObject);
            }

        } else {
            // 查验签收规则
            if(jsonObject==null){
                result = fpqsService.dzpSaveInvoice(pramsMap, userInfo, QsfsEnum.SMQS.getQsfsDm(), invoiceType);
            }
        }

        boolean results = (Boolean)result[0];
        String desc = (String)result[1];
        TDxRecordInvoice recordInvoice = (TDxRecordInvoice)result[2];
        // 扫码签收信息拼装返回
        if (results) {
            tDxInvoice.setInvoiceAmount(recordInvoice.getInvoiceAmount());
            //更新代码号码，支持全电
            tDxInvoice.setInvoiceCode(recordInvoice.getInvoiceCode());
            tDxInvoice.setInvoiceNo(recordInvoice.getInvoiceNo());
            tDxInvoice.setEleInvoiceNo(recordInvoice.getEleInvoiceNo());
            tDxInvoice.setInvoiceType(recordInvoice.getInvoiceType());

            tDxInvoice.setTaxAmount(recordInvoice.getTaxAmount());
            tDxInvoice.setGfName(recordInvoice.getGfName());
            tDxInvoice.setGfTaxNo(recordInvoice.getGfTaxNo());
            tDxInvoice.setXfName(recordInvoice.getXfName());
            tDxInvoice.setXfTaxNo(recordInvoice.getXfTaxNo());
            tDxInvoice.setInvoiceDate(recordInvoice.getInvoiceDate());
            tDxInvoice.setQsDate(DateUtils.getSqlDateLong());
            tDxInvoice.setQsStatus(FpqsjgEnum.YQS.getQsjgDm());
            tDxInvoice.setQsType(QsfsEnum.SMQS.getQsfsDm());
            tDxInvoice.setInvoiceStatus(recordInvoice.getInvoiceStatus());
            tDxInvoice.setTotalAmount(recordInvoice.getTotalAmount());
            tDxInvoice.setCreateDate(DateUtils.getSqlDateLong());
            tDxInvoice.setCheckCode(recordInvoice.getCheckCode());
            tDxInvoice.setInvoiceRemark(recordInvoice.getRemark());
            tDxInvoice.setNotes(desc);
        } else {
            if(ObjectUtil.isNotNull(recordInvoice)){
                tDxInvoice.setEleInvoiceNo(recordInvoice.getEleInvoiceNo());
            }
            tDxInvoice.setInvoiceType(invoiceType);
            tDxInvoice.setQsDate(DateUtils.getSqlDateLong());
            tDxInvoice.setQsStatus(FpqsjgEnum.WQS.getQsjgDm());
            tDxInvoice.setQsType(QsfsEnum.SMQS.getQsfsDm());
            tDxInvoice.setCreateDate(DateUtils.getSqlDateLong());
            tDxInvoice.setNotes(desc);
        }
        SmqsWqsfpVO qsjg = this.convertToSmqsView(tDxInvoice);
        returnList.add(qsjg);
        json.put("datalist", returnList);
        return super.responseResult(json);
    }


    /**
     * 根据uuid查询发票信息
     *
     * @param uuid
     *            uuid
     * @return 返回
     */
    private List<TDxRecordInvoice> getInvoiceList(String uuid) {
        // 直接查询底账表是否存在信息
        QueryWrapper<TDxRecordInvoice> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("uuid", uuid);
        return super.list(queryWrapper);
    }

    /**
     * 根据uuid查询发票信息
     *
     * @param uuid
     *            uuid
     * @return 返回
     */
    private TDxRecordInvoice getRecordInvoice(String uuid, String dbName) {
        DynamicContextHolder.push(dbName + DbConstant.BUSINESS_READ);
        // 直接查询底账表是否存在信息
        QueryWrapper<TDxRecordInvoice> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("uuid", uuid);
        return this.baseMapper.selectOne(queryWrapper);
    }

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

    /**
     * 初始化签收记录公共信息
     *
     * @param pramsMap
     *            入参
     * @return 返回
     */
    private TDxInvoice initQsjl(Map<String, String> pramsMap) {
        TDxInvoice tDxInvoice = new TDxInvoice();
        String invoiceCode = pramsMap.get("invoiceCode");
        String invoiceNo = pramsMap.get("invoiceNo");
        tDxInvoice.setInvoiceType(pramsMap.get("invoiceType"));
        tDxInvoice.setInvoiceCode(invoiceCode);
        tDxInvoice.setInvoiceNo(invoiceNo);
        if(StringUtils.isNotEmpty(invoiceNo)&&invoiceNo.length()==20){
            tDxInvoice.setInvoiceCode(invoiceNo.substring(0,12));
            tDxInvoice.setInvoiceNo(invoiceNo.substring(12,20));
            tDxInvoice.setEleInvoiceNo(invoiceNo);
        }
        tDxInvoice.setUuid(pramsMap.get("uuid"));
        tDxInvoice.setUserAccount(pramsMap.get("userId"));
        tDxInvoice.setUserName(pramsMap.get("userName"));

        tDxInvoice.setUuid(invoiceCode + invoiceNo);
        tDxInvoice.setValid("1");
        tDxInvoice.setDeptId(pramsMap.get("businessCode"));
        tDxInvoice.setDeptName(pramsMap.get("businessName"));
        tDxInvoice.setScanId(pramsMap.get("scanId"));
        tDxInvoice.setCompany(pramsMap.get("company"));
        try {
            tDxInvoice.setInvoiceDate(new SimpleDateFormat("yyyy-MM-dd").parse(pramsMap.get("invoiceDate")));
        } catch (Exception e) {
            tDxInvoice.setInvoiceDate(new Date());
        }
        return tDxInvoice;
    }

    /**
     * 转换成扫描签收结果列表
     *
     * @param tDxInvoice
     *            扫描信息
     * @return 返回
     */
    private SmqsWqsfpVO convertToSmqsView(TDxInvoice tDxInvoice) {
        SmqsWqsfpVO qsjg = new SmqsWqsfpVO();
        qsjg.setInvoiceType(tDxInvoice.getInvoiceType());
        qsjg.setId(tDxInvoice.getUuid());
        qsjg.setCheckCode(StringHelper.trim(tDxInvoice.getCheckCode(), ""));
        if (tDxInvoice.getInvoiceAmount() != null) {

            qsjg.setInvoiceAmount(
                    AmountFormatUtil.fmtMicrometer(MathUtil.round(tDxInvoice.getInvoiceAmount().toPlainString())));
        } else {
            qsjg.setInvoiceAmount("");
        }
        qsjg.setInvoiceCode(tDxInvoice.getInvoiceCode());
        qsjg.setInvoiceNo(tDxInvoice.getInvoiceNo());
        qsjg.setEleInvoiceNo(tDxInvoice.getEleInvoiceNo());
        qsjg.setNotes(tDxInvoice.getNotes());
        if (FpqsjgEnum.YQS.getQsjgDm().equals(tDxInvoice.getQsStatus())) {
            qsjg.setQsStatus(FpqsjgEnum.YQS.getQsjgMcSmb(FpqsjgEnum.YQS.getIndex()));
            qsjg.setDelState(false);
            qsjg.setEditState(false);
        } else {
            qsjg.setQsStatus(FpqsjgEnum.WQS.getQsjgMcSmb(FpqsjgEnum.WQS.getIndex()));
            qsjg.setDelState(true);
            qsjg.setEditState(true);
        }
        if (tDxInvoice.getTaxAmount() != null) {
            qsjg.setTaxAmount(
                    AmountFormatUtil.fmtMicrometer(MathUtil.round(tDxInvoice.getTaxAmount().toPlainString())));
        } else {
            qsjg.setTaxAmount("");
        }
        qsjg.setScanId(tDxInvoice.getScanId());
        qsjg.setUserName(tDxInvoice.getUserName());
        qsjg.setInvoiceDate(
                (tDxInvoice.getInvoiceDate() == null) ? "" : DateUtils.dateToStr(tDxInvoice.getInvoiceDate()));
        qsjg.setQsDate((tDxInvoice.getQsDate() == null) ? "" : DateUtils.dateToStr(tDxInvoice.getQsDate()));
        qsjg.setInvoiceType(tDxInvoice.getInvoiceType());
        qsjg.setGfName(tDxInvoice.getGfName());
        qsjg.setGfTaxNo(tDxInvoice.getGfTaxNo());
        qsjg.setXfName(tDxInvoice.getXfName());
        qsjg.setXfTaxNo(tDxInvoice.getXfTaxNo());
        qsjg.setBusinessName(tDxInvoice.getDeptName());
        if (tDxInvoice.getTotalAmount() != null) {

            qsjg.setTotalAmount(
                    AmountFormatUtil.fmtMicrometer(MathUtil.round(tDxInvoice.getTotalAmount().toPlainString())));
        } else {
            qsjg.setTotalAmount("");
        }
        return qsjg;
    }

    /**
     * 设置扫描签收失败结果
     *
     * @param tDxInvoice
     *            扫描信息
     * @param pramsMap
     *            入参
     * @return 返回信息
     */
    private TDxInvoice failSmqs(TDxInvoice tDxInvoice, Map<String, String> pramsMap, String qsType, String notes) {
        if (pramsMap.get("invoiceAmount") != null && !"".equals(pramsMap.get("invoiceAmount"))) {

            tDxInvoice.setInvoiceAmount(new BigDecimal(pramsMap.get("invoiceAmount")));
        }
        tDxInvoice.setQsDate(DateUtils.getSqlDateLong());
        tDxInvoice.setQsStatus(FpqsjgEnum.WQS.getQsjgDm());
        tDxInvoice.setQsType(qsType);
        tDxInvoice.setCreateDate(DateUtils.getSqlDateLong());
        tDxInvoice.setCheckCode(pramsMap.get("checkCode"));
        tDxInvoice.setNotes(notes);
        if (tDxInvoice.getInvoiceDate() == null && pramsMap.get("invoiceDate") != null) {

            tDxInvoice.setInvoiceDate(DateUtils.strToDate(pramsMap.get("invoiceDate")));
        }
        return tDxInvoice;
    }

    /**
     * 设置扫描签收成功结果
     *
     * @param tDxInvoice
     *            扫描信息
     * @param invoice
     *            抵账信息
     * @return 返回
     */
    private TDxInvoice succSmqs(TDxInvoice tDxInvoice, TDxRecordInvoice invoice, String qsType) {
        tDxInvoice.setInvoiceAmount(invoice.getInvoiceAmount());
        tDxInvoice.setTaxAmount(invoice.getTaxAmount());
        tDxInvoice.setGfName(invoice.getGfName());
        tDxInvoice.setGfTaxNo(invoice.getGfTaxNo());
        tDxInvoice.setXfName(invoice.getXfName());
        tDxInvoice.setXfTaxNo(invoice.getXfTaxNo());
        tDxInvoice.setInvoiceDate(invoice.getInvoiceDate());
        tDxInvoice.setQsDate(DateUtils.getSqlDateLong());
        tDxInvoice.setQsStatus(FpqsjgEnum.YQS.getQsjgDm());
        tDxInvoice.setQsType(qsType);
        tDxInvoice.setInvoiceStatus(invoice.getInvoiceStatus());
        tDxInvoice.setTotalAmount(invoice.getTotalAmount());
        tDxInvoice.setCreateDate(DateUtils.getSqlDateLong());
        tDxInvoice.setCheckCode(invoice.getCheckCode());
        tDxInvoice.setInvoiceRemark(invoice.getRemark());
        tDxInvoice.setNotes("签收成功");
        return tDxInvoice;
    }

    @Override
    public void delQsjl(Map<String, String> pramsMap) {
        DynamicContextHolder.push(pramsMap.get("dbName") + DbConstant.BUSINESS_WRITE);
        signInvoiceSmService.delByUuid(pramsMap.get("uuid"), pramsMap.get("userId"));
    }

    @Override
    public String smyqsQsfp(Map<String, String> pramsMapAll, UserInfo userInfo) {
        JSONObject json;
        String company = pramsMapAll.get("company");
        String menuId = pramsMapAll.get("menuId");
        json = tabulateRedisService.getTabulateMenu(company, menuId);

        TDxInvoice tDxInvoice;
        int success = 0;
        DynamicContextHolder.push(pramsMapAll.get("dbName") + DbConstant.BUSINESS_READ);
        // 从扫描记录表获取扫描信息
        String pch = pramsMapAll.get("pch");
        QueryWrapper<TDxScanInvoiceLog> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("pch", pch);
        TDxScanInvoiceLog scanInvoiceLog = signScanInvoiceLogService.getOne(queryWrapper);

        if (scanInvoiceLog == null) {
            json.put("total", 0);
            json.put("success", 0);
            json.put("fail", 0);
            json.put("datalist", "");
            return super.responseResult(json);

        }
        String invoiceText = scanInvoiceLog.getInvoiceText();

        // 校验扫描信息
        List<Map<String, String>> pramsMapList = this.validateScanInfo(invoiceText, pramsMapAll);
        List<SmyqsWqsfpVO> returnList = new ArrayList<>();

        if (pramsMapList.size() > 0) {
            // 扫描仪每次上传多张发票，因此需要根据上传pch循环处理本批上传的发票
            for (int i = 0; i < pramsMapList.size(); i++) {
                Map<String, String> pramsMap = pramsMapList.get(i);
                String invoiceType = pramsMap.get("invoiceType");
                String invoiceCode = pramsMap.get("invoiceCode");
                String invoiceNo = pramsMap.get("invoiceNo");
                String invoiceDate = DateUtils.dateToStr(DateUtils.getSqlDate());
                if (StringUtils.isNotBlank(pramsMap.get("invoiceDate"))) {

                    invoiceDate = pramsMap.get("invoiceDate");
                } else {
                    pramsMap.put("invoiceDate", invoiceDate);
                }
                tDxInvoice = this.initQsjl(pramsMap);

                tDxInvoice.setXfName(pramsMap.get("xfmc"));
                tDxInvoice.setGfName(pramsMap.get("gfmc"));
                tDxInvoice.setGfTaxNo(pramsMap.get("gfsh"));
                tDxInvoice.setXfTaxNo(pramsMap.get("xfsh"));
                tDxInvoice.setSettlementNo(pramsMap.get("settlementNo"));
                tDxInvoice.setSettleSource(pramsMap.get("settleSource"));
                if (pramsMap.get("taxAmount") != null && !"".equals(pramsMap.get("taxAmount"))) {

                    tDxInvoice.setTaxAmount(new BigDecimal(pramsMap.get("taxAmount")));
                } else {
                    tDxInvoice.setTaxAmount(new BigDecimal("0.00"));
                }
                if (pramsMap.get("invoiceAmount") != null && !"".equals(pramsMap.get("invoiceAmount"))) {

                    tDxInvoice.setInvoiceAmount(new BigDecimal(pramsMap.get("invoiceAmount")));
                } else {
                    tDxInvoice.setInvoiceAmount(new BigDecimal("0.00"));
                }
                tDxInvoice.setTotalAmount(tDxInvoice.getInvoiceAmount().add(tDxInvoice.getTaxAmount()));
                if (StringUtils.isNotBlank(pramsMap.get("checkCode"))) {
                    tDxInvoice.setCheckCode(pramsMap.get("checkCode"));
                }
                if (pramsMap.get("totalAmount") != null && !"".equals(pramsMap.get("totalAmount"))) {

                    tDxInvoice.setTotalAmount(new BigDecimal(pramsMap.get("totalAmount")));
                } else {
                    tDxInvoice.setTotalAmount(new BigDecimal("0.00"));
                }
                // 签收返回数据信息
                pramsMap.put("xfName", pramsMap.get("xfmc"));
                pramsMap.put("gfName", pramsMap.get("gfmc"));
                Object[] result = new Object[3];
                result[0] = false;
                if("1".equals(pramsMap.get("recordHaveData"))){
                    result[0] = true;
                }
                JSONObject jsonObject = null;
                //如果是代扣代缴，走底账签收
                boolean dkdj = false;
                if("3".equals(pramsMap.get("xxly"))){
                    dkdj = true;
                }

                if("0".equals(pramsMap.get("recordHaveData"))&&invoiceNo.length()==20){
                    log.info("抵账库不存在此发票且是全电专普，走查验验证票种");
                    //if(FplxEnum.QDZZP.getFplxDm().equals(invoiceType) || FplxEnum.QDPP.getFplxDm().equals(invoiceType)){
                    result[0] = true;
                    pramsMap.put("invoiceAmount",pramsMap.get("totalAmount"));
                    jsonObject = fpqsService.checkInvoice(pramsMap, userInfo,QsfsEnum.SMYQS.getQsfsDm(), invoiceType);
                    String resultCode = jsonObject.getString("resultCode");
                    if (jsonObject.containsKey("returnCode")) {
                        result[0] = false;
                        result[1] = jsonObject.getString("returnMessage");
                    }else if (!"0001".equals(resultCode)) {
                        result[0] = false;
                        result[1] = jsonObject.getString("resultTip");
                    }
                    if(StringUtils.isNotBlank(jsonObject.getString("invoiceType"))){
                        invoiceType = jsonObject.getString("invoiceType");
                        tDxInvoice.setInvoiceType(invoiceType);
                    }
                }


                // 底账表签收校验
                if (FplxEnum.ZP.getFplxDm().equals(invoiceType) || FplxEnum.TXF.getFplxDm().equals(invoiceType)
                        || FplxEnum.JDC.getFplxDm().equals(invoiceType) || FplxEnum.DZZP.getFplxDm().equals(invoiceType)
                        || (FplxEnum.QDZZP.getFplxDm().equals(invoiceType) && (Boolean) result[0])
                        || dkdj
                        //|| FplxEnum.TLKP.getFplxDm().equals(invoiceType)
                        //|| FplxEnum.HKDZFP.getFplxDm().equals(invoiceType)
                ) {
                    result = fpqsService.zpSaveInvoice(pramsMap, userInfo, QsfsEnum.SMYQS.getQsfsDm(), invoiceType,jsonObject);
                } else if ((FplxEnum.QDPP.getFplxDm().equals(invoiceType)) && (Boolean) result[0]) {
                    /**
                     * @Description 全电普票 此处存在两种情况，
                     * 1底账有。invoiceType是32，(Boolean) result[0]是true
                     * 2底账无。能进来此处是查验成功,invoiceType是32，(Boolean) result[0]是true。
                     * @param pramsMap
                     * @param userInfo
                     * @Return java.lang.String
                     * @Author wangruwei
                     * @Date 2023/4/20 16:09
                     **/
                    //全电普票
                    log.info("全电普票签收");
                    if("1".equals(pramsMap.get("recordHaveData"))){
                        log.info("底账存在，用抵账库信息去签收");
                        result = fpqsService.zpSaveInvoice(pramsMap, userInfo, QsfsEnum.SMYQS.getQsfsDm(), invoiceType,jsonObject);
                    }else{
                        log.info("底账没有，查验成功，开始签收");
                        result = fpqsService.qdSaveInvoice(pramsMap, userInfo, QsfsEnum.SMYQS.getQsfsDm(), invoiceType,jsonObject);
                    }
                } else {
                    // 查验签收规则
                    if(jsonObject==null){
                        result = fpqsService.dzpSaveInvoice(pramsMap, userInfo, QsfsEnum.SMYQS.getQsfsDm(), invoiceType);
                    }
                }

                boolean results = (Boolean)result[0];
                String desc = (String)result[1];
                TDxRecordInvoice recordInvoice = (TDxRecordInvoice)result[2];
                // 扫码签收信息拼装返回
                if (results) {
                    tDxInvoice.setEleInvoiceNo(recordInvoice.getEleInvoiceNo());
                    tDxInvoice.setInvoiceAmount(recordInvoice.getInvoiceAmount());
                    tDxInvoice.setTaxAmount(recordInvoice.getTaxAmount());
                    tDxInvoice.setGfName(recordInvoice.getGfName());
                    tDxInvoice.setGfTaxNo(recordInvoice.getGfTaxNo());
                    tDxInvoice.setXfName(recordInvoice.getXfName());
                    tDxInvoice.setXfTaxNo(recordInvoice.getXfTaxNo());
                    tDxInvoice.setInvoiceDate(recordInvoice.getInvoiceDate());
                    tDxInvoice.setQsDate(DateUtils.getSqlDateLong());
                    tDxInvoice.setQsStatus(FpqsjgEnum.YQS.getQsjgDm());
                    tDxInvoice.setQsType(QsfsEnum.SMQS.getQsfsDm());
                    tDxInvoice.setInvoiceStatus(recordInvoice.getInvoiceStatus());
                    tDxInvoice.setTotalAmount(recordInvoice.getTotalAmount());
                    tDxInvoice.setCreateDate(DateUtils.getSqlDateLong());
                    tDxInvoice.setCheckCode(recordInvoice.getCheckCode());
                    tDxInvoice.setInvoiceRemark(recordInvoice.getRemark());
                    tDxInvoice.setNotes(desc);
                } else {
                    try {
                        if (FplxEnum.ESC.getFplxDm().equals(invoiceType)) {
                            if(pramsMap.get("invoiceAmount") != null && !"".equals(pramsMap.get("invoiceAmount"))){
                                tDxInvoice.setInvoiceAmount(new BigDecimal(pramsMap.get("invoiceAmount")));
                            }else {
                                tDxInvoice.setInvoiceAmount(tDxInvoice.getInvoiceAmount().add(tDxInvoice.getTaxAmount()));
                            }
                        }
                    }catch (Exception e){
                        tDxInvoice.setInvoiceAmount(new BigDecimal("0.00"));
                    }
                    tDxInvoice.setQsDate(DateUtils.getSqlDateLong());
                    tDxInvoice.setQsStatus(FpqsjgEnum.WQS.getQsjgDm());
                    tDxInvoice.setQsType(QsfsEnum.SMQS.getQsfsDm());
                    tDxInvoice.setCreateDate(DateUtils.getSqlDateLong());
                    tDxInvoice.setNotes(desc);
                }

                SmyqsWqsfpVO qsjg = this.convertToSmyqsView(tDxInvoice, invoiceDate, i + 1);
                returnList.add(qsjg);

            }
        }

        int fail = 0;
        for (SmyqsWqsfpVO smyqsWqsfpVO : returnList) {
            if (smyqsWqsfpVO.getDelState()) {
                fail++;
            } else {
                success++;
            }
        }

        json.put("total", returnList.size());
        json.put("success", success);
        json.put("fail", fail);
        json.put("datalist", returnList);
        return super.responseResult(json);
    }

    /**
     * 扫描基本信息校验失败，直接转换为页面展示对象
     *
     * @param pramsMap
     *            入参
     * @param i
     *            序号
     * @return 返回
     */

    private SmyqsWqsfpVO convertMapToSmyqsView(Map<String, String> pramsMap, int i) {
        SmyqsWqsfpVO qsjg = new SmyqsWqsfpVO();
        qsjg.setXh(String.valueOf(i));
        qsjg.setId("");
        qsjg.setCheckCode(StringUtils.isBlank(pramsMap.get("checkCode")) ? "" : pramsMap.get("checkCode"));
        qsjg.setInvoiceCode(pramsMap.get("invoiceCode"));
        qsjg.setInvoiceNo(pramsMap.get("invoiceNo"));
        qsjg.setNotes(pramsMap.get("errmsg"));
        qsjg.setUserName(pramsMap.get("userName"));
        qsjg.setQsStatus(FpqsjgEnum.WQS.getQsjgMcSmb(FpqsjgEnum.WQS.getIndex()));
        qsjg.setInvoiceAmount(StringUtils.isBlank(pramsMap.get("invoiceAmount")) ? "" : pramsMap.get("invoiceAmount"));
        qsjg.setTaxAmount(StringUtils.isBlank(pramsMap.get("taxAmount")) ? "" : pramsMap.get("taxAmount"));
        qsjg.setInvoiceDate(StringUtils.isBlank(pramsMap.get("invoiceDate")) ? "" : pramsMap.get("invoiceDate"));
        qsjg.setGfName(StringUtils.isBlank(pramsMap.get("gfmc")) ? "" : pramsMap.get("gfmc"));
        qsjg.setGfTaxNo(StringUtils.isBlank(pramsMap.get("gfsh")) ? "" : pramsMap.get("gfsh"));
        qsjg.setXfName(StringUtils.isBlank(pramsMap.get("xfmc")) ? "" : pramsMap.get("xfmc"));
        qsjg.setQsDate(DateUtils.getStringDateShort());
        qsjg.setInvoiceType(StringUtils.isBlank(pramsMap.get("invoiceType")) ? "" : pramsMap.get("invoiceType"));
        qsjg.setScanId(StringUtils.isBlank(pramsMap.get("scanId")) ? "" : pramsMap.get("scanId"));
        qsjg.setBusinessName(StringUtils.isBlank(pramsMap.get("businessName")) ? "" : pramsMap.get("businessName"));
        qsjg.setBusinessCode(StringUtils.isBlank(pramsMap.get("businessCode")) ? "" : pramsMap.get("businessCode"));
        return qsjg;
    }

    /**
     * 校验扫描仪上传的数据是否合法
     *
     * @param invoiceText
     *            待校验数据
     * @param pramsMap
     *            公共参数
     * @return 返回
     */
    private List<Map<String, String>> validateScanInfo(String invoiceText, Map<String, String> pramsMap) {

        List<Map<String, String>> pramsMapList = new ArrayList<>();

        JSONObject ocrData = JSONObject.parseObject(invoiceText);
        if (ocrData != null) {

            JSONArray datas = ocrData.getJSONArray("invoiceList");
            for (int i = 0; i < datas.size(); i++) {
                Map<String, String> validateMap = new HashMap<>();
                validateMap.put("userId", pramsMap.get("userId"));
                validateMap.put("userName", pramsMap.get("userName"));
                validateMap.put("gfshAll", pramsMap.get("gfshAll"));
                validateMap.put("gfmcAll", pramsMap.get("gfmcAll"));
                validateMap.put("dbName", pramsMap.get("dbName"));
                validateMap.put("businessCode", pramsMap.get("businessCode"));
                validateMap.put("businessName", pramsMap.get("businessName"));
                validateMap.put("company", pramsMap.get("company"));

                JSONObject data = (JSONObject)ocrData.getJSONArray("invoiceList").get(i);
                String invoiceCode = data.getString("fpdm");
                String invoiceNo = data.getString("fphm");
                String invoiceDate = data.getString("kprq");
                String invoiceAmount = data.getString("je");
                String taxAmount = data.getString("se");
                String totalAmount = data.getString("jshj");
                String checkCode = data.getString("jym");
                String gfsh = data.getString("gfsh");
                String gfmc = data.getString("gfmc");
                String xfsh = data.getString("xfsh");
                String xfmc = data.getString("xfmc");
                String scanId = data.getString("scanid");
                String barCode = data.getString("barCode");
                String invoiceType = data.getString("fplx");
                //扫描仪扫回来的种类不对，查抵账库赋值
                QueryWrapper<TDxRecordInvoice> query = new QueryWrapper<>();
                query.eq("uuid", (StringUtils.isEmpty(invoiceCode)?"":invoiceCode)+invoiceNo);
                TDxRecordInvoice recordInvoice = super.getOne(query);
                if(ObjectUtil.isNotEmpty(recordInvoice)){
                    invoiceType = recordInvoice.getInvoiceType();
                    //抵账库存在此发票
                    validateMap.put("recordHaveData", "1");
                    validateMap.put("xxly", recordInvoice.getXxly());
                }else{
                    //抵账库不存在此发票
                    validateMap.put("recordHaveData", "0");
                }

                String settlementNo = "";
                String settleSource = "";
                if (barCode != null && !"".equals(barCode)) {
                    settlementNo = barCode.substring(barCode.indexOf("#") + 1);
                    settleSource = barCode.substring(0, barCode.indexOf("#"));
                }
                //if(!(FplxEnum.QDZZP.getFplxDm().equals(invoiceType) || FplxEnum.QDPP.getFplxDm().equals(invoiceType))){
                if (StringUtils.isBlank(invoiceNo)) {
                    invoiceNo = "F" + LocalTrmSeqNum.getSeqNum();
                }
                if(invoiceNo.length()!=20){
                    if (StringUtils.isBlank(invoiceCode)) {
                        invoiceCode = "F" + LocalTrmSeqNum.getSeqNum();
                    }
                }
                validateMap.put("invoiceCode", invoiceCode);
                validateMap.put("invoiceNo", invoiceNo);
                validateMap.put("invoiceDate", toDate(invoiceDate));
                validateMap.put("invoiceAmount", invoiceAmount);
                validateMap.put("taxAmount", taxAmount);
                validateMap.put("totalAmount", totalAmount);
                validateMap.put("checkCode", checkCode);
                validateMap.put("gfsh", gfsh);
                validateMap.put("gfmc", gfmc);
                validateMap.put("xfsh", xfsh);
                validateMap.put("xfmc", xfmc);
                validateMap.put("scanId", scanId);
                validateMap.put("uuid", invoiceCode + invoiceNo);
                validateMap.put("settlementNo", settlementNo);
                validateMap.put("settleSource", settleSource);
                if(FplxEnum.QDZZP.getFplxDm().equals(invoiceType) || FplxEnum.QDPP.getFplxDm().equals(invoiceType)
                        || FplxEnum.ZZDZ.getFplxDm().equals(invoiceType)|| FplxEnum.ZZPP.getFplxDm().equals(invoiceType)
                 ){
                    validateMap.put("invoiceType", invoiceType);
                }else {
                    InvoiceUtil iu = new InvoiceUtil(invoiceCode);
                    invoiceType = iu.getFplxdm();
                    if (StringUtils.isNotBlank(invoiceType)) {

                        validateMap.put("invoiceType", invoiceType);
                    } else {
                        validateMap.put("invoiceType", "01");
                    }
                }
                pramsMapList.add(validateMap);
            }
        }
        return pramsMapList;
    }

    public String toDate(String invoiceDate) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        try {
            if (invoiceDate.length() > 10) {
                invoiceDate = invoiceDate.substring(0, 10);
            }
            boolean flg =
                    StringUtils.isNotBlank(invoiceDate) && (invoiceDate.length() == 8 || invoiceDate.length() == 10);
            if (flg) {
                if (invoiceDate.startsWith("2")) {

                    Date parse = dateFormat.parse(invoiceDate.replaceAll("-", ""));
                    return format.format(parse);
                } else {
                    return format.format(new Date());
                }
            } else if (StringUtils.isNotBlank(invoiceDate) && invoiceDate.length() == 6) {
                Date parse = dateFormat.parse("20" + invoiceDate);
                return format.format(parse);
            } else {
                return format.format(new Date());
            }
        } catch (Exception e) {
            return format.format(new Date());
        }
    }

    /**
     * 对比扫描信息和底账表信息是否一致
     *
     * @param tDxRecordInvoice
     *            底账表信息
     * @param pramsMap
     *            扫描传入信息
     * @return 返回
     */
    private String compareInvoiceInfo(TDxRecordInvoice tDxRecordInvoice, Map<String, String> pramsMap) {
        String notes = null;
        if (!pramsMap.get("invoiceDate").equals(DateUtils.dateToStr(tDxRecordInvoice.getInvoiceDate()))) {
            notes = "扫描的开票日期与底账开票日期不一致";
        } else {
            if (!pramsMap.get("gfsh").equals(tDxRecordInvoice.getGfTaxNo())) {
                notes = "扫描的购方税号与底账购方税号不一致";
            } else {

                if (!MathUtil.round(pramsMap.get("invoiceAmount"))
                        .equals(MathUtil.round(tDxRecordInvoice.getInvoiceAmount().toPlainString()))) {
                    notes = "扫描的金额与底账金额不一致";
                }

            }
        }
        return notes;
    }

    /**
     * 转换扫描仪结果对象列表
     *
     * @param tDxInvoice
     *            扫描信息
     * @param invoiceDate
     *            开票日期，传入此参数是由于请求传入的扫描日期可能是错误的
     * @param i
     *            序号
     * @return 返回
     */
    private SmyqsWqsfpVO convertToSmyqsView(TDxInvoice tDxInvoice, String invoiceDate, int i) {
        SmyqsWqsfpVO qsjg = new SmyqsWqsfpVO();
        qsjg.setXh(String.valueOf(i));
        qsjg.setId(tDxInvoice.getUuid());
        qsjg.setCheckCode(StringUtils.isBlank(tDxInvoice.getCheckCode()) ? "" : tDxInvoice.getCheckCode());
        qsjg.setInvoiceCode(tDxInvoice.getInvoiceCode());
        qsjg.setInvoiceNo(tDxInvoice.getInvoiceNo());
        qsjg.setEleInvoiceNo(tDxInvoice.getEleInvoiceNo());
        qsjg.setNotes(tDxInvoice.getNotes());
        qsjg.setUserName(tDxInvoice.getUserName());
        qsjg.setXfTaxNo(StringUtils.isBlank(tDxInvoice.getXfTaxNo()) ? "" : tDxInvoice.getXfTaxNo());
        if (FpqsjgEnum.YQS.getQsjgDm().equals(tDxInvoice.getQsStatus())) {
            qsjg.setQsStatus(FpqsjgEnum.YQS.getQsjgMcSmb(FpqsjgEnum.YQS.getIndex()));
            qsjg.setEditState(false);
            qsjg.setDelState(false);
        } else {
            qsjg.setQsStatus(FpqsjgEnum.WQS.getQsjgMcSmb(FpqsjgEnum.WQS.getIndex()));
            qsjg.setEditState(true);
            qsjg.setDelState(true);
        }
        qsjg.setInvoiceAmount((tDxInvoice.getInvoiceAmount() == null) ? ""
                : AmountFormatUtil.fmtMicrometer(MathUtil.round(tDxInvoice.getInvoiceAmount().toPlainString())));
        qsjg.setTaxAmount((tDxInvoice.getTaxAmount() == null) ? ""
                : AmountFormatUtil.fmtMicrometer(MathUtil.round(tDxInvoice.getTaxAmount().toPlainString())));
        qsjg.setInvoiceDate(
                tDxInvoice.getInvoiceDate() != null ? DateUtils.dateToStr(tDxInvoice.getInvoiceDate()) : invoiceDate);
        qsjg.setGfName(StringUtils.isBlank(tDxInvoice.getGfName()) ? "" : tDxInvoice.getGfName());
        qsjg.setGfTaxNo(StringUtils.isBlank(tDxInvoice.getGfTaxNo()) ? "" : tDxInvoice.getGfTaxNo());
        qsjg.setXfName(StringUtils.isBlank(tDxInvoice.getXfName()) ? "" : tDxInvoice.getXfName());
        qsjg.setQsDate(tDxInvoice.getQsDate() == null ? "" : DateUtils.dateToStr(tDxInvoice.getQsDate()));
        tDxInvoice.setQsType(QsfsEnum.SMYQS.getQsfsMc(QsfsEnum.SMYQS.getIndex()));
        qsjg.setInvoiceType(tDxInvoice.getInvoiceType());
        qsjg.setScanId((tDxInvoice.getScanId() == null) ? "" : tDxInvoice.getScanId());
        qsjg.setBusinessName(tDxInvoice.getDeptName() == null ? "" : tDxInvoice.getDeptName());
        qsjg.setBusinessCode(tDxInvoice.getDeptId() == null ? "" : tDxInvoice.getDeptId());
        qsjg.setUuid(tDxInvoice.getUuid());
        qsjg.setSettlementNo(tDxInvoice.getSettlementNo());
        qsjg.setTotalAmount((tDxInvoice.getTotalAmount() == null) ? ""
                : AmountFormatUtil.fmtMicrometer(MathUtil.round(tDxInvoice.getTotalAmount().toPlainString())));

        return qsjg;
    }

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

    @Override
    public String updateQsjl(Map<String, String> pramsMap, UserInfo userInfo) {

        JSONObject json = new JSONObject();

        DynamicContextHolder.push(pramsMap.get("dbName") + DbConstant.BUSINESS_WRITE);
        UpdateWrapper<TDxInvoice> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("scan_id", pramsMap.get("scanId"));
        // 防止对已签收的记录进行修改
        updateWrapper.eq("qs_status", "0");
        // 防止修改其他人的记录
        updateWrapper.eq("user_account", pramsMap.get("userId"));

        TDxInvoice tDxInvoice = new TDxInvoice();
        tDxInvoice.setUserAccount(pramsMap.get("userId"));
        tDxInvoice.setUserName(pramsMap.get("userName"));
        tDxInvoice.setDeptId(pramsMap.get("businessCode"));
        tDxInvoice.setDeptName(pramsMap.get("businessName"));
        tDxInvoice.setScanId(pramsMap.get("scanId"));
        String invoiceCode = pramsMap.get("invoiceCode");
        String invoiceNo = pramsMap.get("invoiceNo");
        String invoiceType = pramsMap.get("invoiceType");
        String uuid = (StringUtils.isBlank(invoiceCode)?"":invoiceCode) + invoiceNo;

        tDxInvoice.setInvoiceCode(invoiceCode);
        tDxInvoice.setInvoiceNo(invoiceNo);
        tDxInvoice.setUuid(uuid);
        tDxInvoice.setInvoiceDate(DateUtils.strToDate(pramsMap.get("invoiceDate")));
        tDxInvoice.setGfTaxNo(pramsMap.get("gfsh"));
        tDxInvoice.setXfTaxNo(pramsMap.get("xfsh"));
        if (pramsMap.get("taxAmount") != null && !"".equals(pramsMap.get("taxAmount"))) {

            tDxInvoice.setTaxAmount(new BigDecimal(pramsMap.get("taxAmount")));
        } else {
            tDxInvoice.setTaxAmount(new BigDecimal("0.00"));
        }
        if (pramsMap.get("invoiceAmount") != null && !"".equals(pramsMap.get("invoiceAmount"))) {

            tDxInvoice.setInvoiceAmount(new BigDecimal(pramsMap.get("invoiceAmount")));
        } else {
            tDxInvoice.setInvoiceAmount(new BigDecimal("0.00"));
        }
        tDxInvoice.setUpdateDate(DateUtils.getSqlDateLong());
        if (pramsMap.containsKey("checkCode")) {
            tDxInvoice.setCheckCode(pramsMap.get("checkCode"));
        }
        if (!(FplxEnum.QDZZP.getFplxDm().equals(invoiceType) || FplxEnum.QDPP.getFplxDm().equals(invoiceType))) {
            /*
            * @Description TODO 都已经传来了发票种类代码了直接用
            * @Author wangruwei
            * @Date 2023/2/17 15:36
            *InvoiceUtil iu = new InvoiceUtil(invoiceCode);
            invoiceType = iu.getFplxdm();*/
            tDxInvoice.setTotalAmount(tDxInvoice.getInvoiceAmount().add(tDxInvoice.getTaxAmount()));
        }else {
            if (pramsMap.get("totalAmount") != null && !"".equals(pramsMap.get("totalAmount"))) {

                tDxInvoice.setTotalAmount(new BigDecimal(pramsMap.get("totalAmount")));
            } else {
                tDxInvoice.setTotalAmount(new BigDecimal("0.00"));
            }
        }

        String invoiceDate = pramsMap.get("invoiceDate");
        tDxInvoice.setInvoiceType(invoiceType);
        tDxInvoice.setInvoiceDate(DateUtils.strToDate(invoiceDate));
        pramsMap.put("xfName", pramsMap.get("xfmc"));
        pramsMap.put("gfName", pramsMap.get("gfmc"));
        boolean isExits = false;
        // 签收返回数据信息
        Object[] result = new Object[3];
        JSONObject jsonObject = null;
        if(FplxEnum.QDZZP.getFplxDm().equals(invoiceType) || FplxEnum.QDPP.getFplxDm().equals(invoiceType)
                //|| FplxEnum.TLKP.getFplxDm().equals(invoiceType)|| FplxEnum.HKDZFP.getFplxDm().equals(invoiceType)
        ){
            result[0] = true;
            pramsMap.put("invoiceAmount",pramsMap.get("totalAmount"));
            jsonObject = fpqsService.checkInvoice(pramsMap, userInfo,QsfsEnum.SMYQS.getQsfsDm(), invoiceType);
            String resultCode = jsonObject.getString("resultCode");
            if (jsonObject.containsKey("returnCode")) {
                result[0] = false;
                result[1] = jsonObject.getString("returnMessage");
            }else if (!"0001".equals(resultCode)) {
                result[0] = false;
                result[1] = jsonObject.getString("resultTip");
            }
            if(StringUtils.isNotBlank(jsonObject.getString("invoiceType"))){
                invoiceType = jsonObject.getString("invoiceType");
            }
        }
        // 底账表签收校验
        if (FplxEnum.ZP.getFplxDm().equals(invoiceType) || FplxEnum.TXF.getFplxDm().equals(invoiceType)
                || FplxEnum.JDC.getFplxDm().equals(invoiceType) || FplxEnum.DZZP.getFplxDm().equals(invoiceType)
                //|| FplxEnum.TLKP.getFplxDm().equals(invoiceType)
                //|| FplxEnum.HKDZFP.getFplxDm().equals(invoiceType)
                || (FplxEnum.QDZZP.getFplxDm().equals(invoiceType) && (Boolean) result[0])) {
            result = fpqsService.zpSaveInvoice(pramsMap, userInfo,QsfsEnum.SMYQS.getQsfsDm(), invoiceType,jsonObject);
        } else if ((FplxEnum.QDPP.getFplxDm().equals(invoiceType)) && (Boolean) result[0]) {
            //全电专票
            result = fpqsService.qdSaveInvoice(pramsMap, userInfo,QsfsEnum.SMYQS.getQsfsDm(), invoiceType,jsonObject);
        } else {
            // 查验签收规则
            if(jsonObject==null){
                result = fpqsService.dzpSaveInvoice(pramsMap, userInfo,QsfsEnum.SMYQS.getQsfsDm(), invoiceType);
            }
        }
//        // 底账表签收校验
//        if (FplxEnum.ZP.getFplxDm().equals(invoiceType) || FplxEnum.TXF.getFplxDm().equals(invoiceType)
//                || FplxEnum.JDC.getFplxDm().equals(invoiceType) || FplxEnum.DZZP.getFplxDm().equals(invoiceType)) {
//            result = fpqsService.zpSaveInvoice(pramsMap, userInfo, QsfsEnum.SMYQS.getQsfsDm(), invoiceType);
//        } else {
//            // 查验签收规则
//            result = fpqsService.dzpSaveInvoice(pramsMap, userInfo, QsfsEnum.SMYQS.getQsfsDm(), invoiceType);
//        }
        boolean results = (Boolean)result[0];
        String desc = (String)result[1];
        TDxRecordInvoice recordInvoice = (TDxRecordInvoice)result[2];
        // 签收信息拼装返回
        if (results) {
            tDxInvoice.setInvoiceAmount(recordInvoice.getInvoiceAmount());
            tDxInvoice.setTaxAmount(recordInvoice.getTaxAmount());
            tDxInvoice.setGfName(recordInvoice.getGfName());
            tDxInvoice.setGfTaxNo(recordInvoice.getGfTaxNo());
            tDxInvoice.setXfName(recordInvoice.getXfName());
            tDxInvoice.setXfTaxNo(recordInvoice.getXfTaxNo());
            tDxInvoice.setInvoiceDate(recordInvoice.getInvoiceDate());
            tDxInvoice.setQsDate(DateUtils.getSqlDateLong());
            tDxInvoice.setQsStatus(FpqsjgEnum.YQS.getQsjgDm());
//            tDxInvoice.setQsType(QsfsEnum.SMQS.getQsfsDm());
            tDxInvoice.setQsType(QsfsEnum.SMYQS.getQsfsDm());
            tDxInvoice.setInvoiceStatus(recordInvoice.getInvoiceStatus());
            tDxInvoice.setTotalAmount(recordInvoice.getTotalAmount());
            tDxInvoice.setCreateDate(DateUtils.getSqlDateLong());
            tDxInvoice.setCheckCode(recordInvoice.getCheckCode());
            tDxInvoice.setInvoiceRemark(recordInvoice.getRemark());
            tDxInvoice.setNotes(desc);
        } else {
            // 查看扫描表是否存在
            TDxInvoice invoiceScanInfo = this.getScaninfo(uuid, pramsMap.get("dbName"));
            if (invoiceScanInfo != null) {
                if (StringUtils.isNotBlank(invoiceScanInfo.getXfName())) {
                    tDxInvoice.setXfName(invoiceScanInfo.getXfName());
                }
                if (StringUtils.isNotBlank(invoiceScanInfo.getGfName())) {
                    tDxInvoice.setGfName(invoiceScanInfo.getGfName());
                }
                tDxInvoice.setCreateDate(invoiceScanInfo.getCreateDate());
            }
            tDxInvoice.setQsDate(DateUtils.getSqlDateLong());
            tDxInvoice.setQsStatus(FpqsjgEnum.WQS.getQsjgDm());
//            tDxInvoice.setQsType(QsfsEnum.SMQS.getQsfsDm());
            tDxInvoice.setQsType(QsfsEnum.SMYQS.getQsfsDm());

            tDxInvoice.setNotes(desc);
        }
        SmqsWqsfpVO qsjg = this.convertToSmqsView(tDxInvoice);
        json.put("dataList", qsjg);
        return super.responseResult(json);
    }

    @Override
    public String qsExcelfp(JSONArray detailArray, Map<String, String> pramsMap, UserInfo userInfo) {
        String company = pramsMap.get("company");
        String menuId = pramsMap.get("menuId");

        JSONObject json = tabulateRedisService.getTabulateMenu(company, menuId);
        List<SmqsWqsfpVO> returnList = new ArrayList<>();
        for (int i = 0; i < detailArray.size(); i++) {
            JSONObject excelFp = detailArray.getJSONObject(i);
            // 入参统一在入口处理

            String invoiceType = excelFp.getString("invoiceType");
            String invoiceCode = excelFp.getString("invoiceCode");
            String invoiceNo = excelFp.getString("invoiceNo");
            //从抵账库获取种类代码
            DynamicContextHolder.push(userInfo.getDbName() + DbConstant.BUSINESS_READ);
            QueryWrapper<TDxRecordInvoice> invoiceWrapper = new QueryWrapper<>();
            invoiceWrapper.lambda().eq(TDxRecordInvoice::getUuid, (StringUtils.isEmpty(invoiceCode)?"":invoiceCode)+invoiceNo);
            TDxRecordInvoice selrecordInvoice = super.getOne(invoiceWrapper);
            boolean dkdj = false;
            if(ObjectUtil.isNotNull(selrecordInvoice)){
                invoiceType = selrecordInvoice.getInvoiceType();
                //如果是代扣代缴，走底账签收
                if("4".equals(selrecordInvoice.getXxly())){
                    dkdj = true;
                    pramsMap.put("xxly", selrecordInvoice.getXxly());
                }
            }
            pramsMap.put("invoiceCode", invoiceCode);
            pramsMap.put("invoiceNo", invoiceNo);
            pramsMap.put("invoiceType", invoiceType);
            pramsMap.put("invoiceDate", excelFp.getString("invoiceDate"));
            pramsMap.put("invoiceAmount", excelFp.getString("invoiceAmount"));
            pramsMap.put("checkCode", excelFp.getString("checkCode"));

            InvoiceUtil iu = new InvoiceUtil(invoiceCode);
            // 通行费发票二维码中的发票类型代码为10“电子发票”，需要单独根据发票代码判断发票类型
            if (FplxEnum.TXF.getFplxDm().equals(iu.getFplxdm())) {
                invoiceType = FplxEnum.TXF.getFplxDm();
            }
            String uuid = (StringUtils.isBlank(invoiceCode)?"":invoiceCode) + invoiceNo;
            pramsMap.put("uuid", uuid);
            pramsMap.put("scanId", UUID.randomUUID().toString());
            TDxInvoice tDxInvoice = this.initQsjl(pramsMap);

            // 签收返回数据信息
            Object[] result = new Object[3];
            result[0] = false;
            if(ObjectUtil.isNotEmpty(selrecordInvoice)){
                result[0] = true;
            }
            JSONObject jsonObject = null;
            //此处查验逻辑是为了确定数电票票种，目前除了数电电票机动车、二手车不支持查验外，其余数电电票都支持查验
            //数电电票机动车、二手车仍然走该逻辑直至签收失败
            if(ObjectUtil.isEmpty(selrecordInvoice)&&invoiceNo.length()==20){
                log.info("抵账库不存在此发票且是全电专普，走查验验证票种");
                //if(FplxEnum.QDZZP.getFplxDm().equals(invoiceType) || FplxEnum.QDPP.getFplxDm().equals(invoiceType)){
                result[0] = true;
                jsonObject = fpqsService.checkInvoice(pramsMap, userInfo,QsfsEnum.DRQS.getQsfsDm(), invoiceType);
                String resultCode = jsonObject.getString("resultCode");
                if (jsonObject.containsKey("returnCode")) {
                    result[0] = false;
                    result[1] = jsonObject.getString("returnMessage");
                }else if (!"0001".equals(resultCode)) {
                    result[0] = false;
                    result[1] = jsonObject.getString("resultTip");
                }
                if(StringUtils.isNotBlank(jsonObject.getString("invoiceType"))){
                    invoiceType = jsonObject.getString("invoiceType");
                }
            }

            // 底账表签收校验
            if (FplxEnum.ZP.getFplxDm().equals(invoiceType)
                    || FplxEnum.TXF.getFplxDm().equals(invoiceType)
                    || FplxEnum.JDC.getFplxDm().equals(invoiceType)
                    || FplxEnum.DZZP.getFplxDm().equals(invoiceType)
                    || FplxEnum.QDZZP.getFplxDm().equals(invoiceType)
                    || FplxEnum.TLKP.getFplxDm().equals(invoiceType)
                    || FplxEnum.HKDZFP.getFplxDm().equals(invoiceType)
                    || FplxEnum.SDFP_JDCTYXSFP.getFplxDm().equals(invoiceType)
                    || FplxEnum.ZZJDC.getFplxDm().equals(invoiceType)
                    || FplxEnum.ESCDZ.getFplxDm().equals(invoiceType)
                    || FplxEnum.ZZESC.getFplxDm().equals(invoiceType)
                    || dkdj) {
                result = fpqsService.zpSaveInvoice(pramsMap, userInfo, QsfsEnum.DRQS.getQsfsDm(), invoiceType,jsonObject);
            }  else if ((FplxEnum.QDPP.getFplxDm().equals(invoiceType)) && (Boolean) result[0]) {
                /**
                 * @Description 全电普票 此处存在两种情况，
                 * 1底账有。invoiceType是32，(Boolean) result[0]是true
                 * 2底账无。能进来此处是查验成功,invoiceType是32，(Boolean) result[0]是true。
                 * @param pramsMap
                 * @param userInfo
                 * @Return java.lang.String
                 * @Author wangruwei
                 * @Date 2023/4/20 16:09
                 **/
                //全电普票
                log.info("全电普票签收");
                if(ObjectUtil.isNotNull(selrecordInvoice)){
                    log.info("底账存在，用抵账库信息去签收");
                    result = fpqsService.zpSaveInvoice(pramsMap, userInfo, QsfsEnum.DRQS.getQsfsDm(), invoiceType,jsonObject);
                }else{
                    log.info("底账没有，查验成功，开始签收");
                    result = fpqsService.qdSaveInvoice(pramsMap, userInfo, QsfsEnum.DRQS.getQsfsDm(), invoiceType,jsonObject);
                }
            }else {
                // 查验签收规则
                if(jsonObject==null){
                    result = fpqsService.dzpSaveInvoice(pramsMap, userInfo, QsfsEnum.DRQS.getQsfsDm(), invoiceType);
                }
            }
            boolean results = (Boolean)result[0];
            String desc = (String)result[1];
            TDxRecordInvoice recordInvoice = (TDxRecordInvoice)result[2];
            // 扫码签收信息拼装返回
            if (results) {
                tDxInvoice.setInvoiceType(recordInvoice.getInvoiceType());
                if(StringUtils.isNotBlank(recordInvoice.getEleInvoiceNo())){
                    tDxInvoice.setEleInvoiceNo(recordInvoice.getEleInvoiceNo());
                }
                tDxInvoice.setInvoiceAmount(recordInvoice.getInvoiceAmount());
                tDxInvoice.setTaxAmount(recordInvoice.getTaxAmount());
                tDxInvoice.setGfName(recordInvoice.getGfName());
                tDxInvoice.setGfTaxNo(recordInvoice.getGfTaxNo());
                tDxInvoice.setXfName(recordInvoice.getXfName());
                tDxInvoice.setXfTaxNo(recordInvoice.getXfTaxNo());
                tDxInvoice.setInvoiceDate(recordInvoice.getInvoiceDate());
                tDxInvoice.setQsDate(DateUtils.getSqlDateLong());
                tDxInvoice.setQsStatus(FpqsjgEnum.YQS.getQsjgDm());
                tDxInvoice.setQsType(QsfsEnum.SMQS.getQsfsDm());
                tDxInvoice.setInvoiceStatus(recordInvoice.getInvoiceStatus());
                tDxInvoice.setTotalAmount(recordInvoice.getTotalAmount());
                tDxInvoice.setCreateDate(DateUtils.getSqlDateLong());
                tDxInvoice.setCheckCode(recordInvoice.getCheckCode());
                tDxInvoice.setInvoiceRemark(recordInvoice.getRemark());
                tDxInvoice.setNotes(desc);
            } else {
                tDxInvoice.setQsDate(DateUtils.getSqlDateLong());
                tDxInvoice.setQsStatus(FpqsjgEnum.WQS.getQsjgDm());
                tDxInvoice.setQsType(QsfsEnum.SMQS.getQsfsDm());
                tDxInvoice.setCreateDate(DateUtils.getSqlDateLong());
                tDxInvoice.setNotes(desc);
            }
            SmqsWqsfpVO qsjg = this.convertToSmqsView(tDxInvoice);
            returnList.add(qsjg);
        }
        json.put("datalist", returnList);
        return super.responseResult(json);
    }

    @Override
    public String checkExcelFp(JSONArray detailArray) {
        String msg = null;
        for (int i = 0; i < detailArray.size(); i++) {
            JSONObject invoice = detailArray.getJSONObject(i);
            String xh = invoice.getString("xh");
            String invoiceCode = invoice.getString("invoiceCode");
            String invoiceNo = invoice.getString("invoiceNo");
            String invoiceAmount = invoice.getString("invoiceAmount");
            String checkCode = invoice.getString("checkCode");

            if(StringUtils.isNotEmpty(invoiceNo)&&invoiceNo.length()==20){
                //如果是20位发票号码，不验证代码号码
            }else{
                msg = validateInvoiceInfo(invoiceCode, invoiceNo);
            }
            if (msg == null) {
                InvoiceUtil invoiceUtil = new InvoiceUtil(invoiceCode);
                if (FplxEnum.ZP.getFplxDm().equals(invoiceUtil.getFplxdm())
                        || FplxEnum.DZZP.getFplxDm().equals(invoiceUtil.getFplxdm())
                        || FplxEnum.JDC.getFplxDm().equals(invoiceUtil.getFplxdm())
                        || FplxEnum.ESC.getFplxDm().equals(invoiceUtil.getFplxdm())
                        || (StringUtils.isNotEmpty(invoiceNo)&&invoiceNo.length()==20)
                    ) {
                    invoiceUtil.setJe(invoiceAmount);
                    if (!invoiceUtil.jeValid()) {
                        msg = "金额不正确";
                    }
                    if (StringUtils.isNotBlank(checkCode)) {
                        invoiceUtil.setJym(checkCode);
                        if (!invoiceUtil.jymValid()) {
                            msg = "校验码不正确";
                        }
                    }
                } else {
                    if (StringUtils.isNotBlank(invoiceAmount)) {
                        invoiceUtil.setJe(invoiceAmount);
                        if (!invoiceUtil.jeValid()) {
                            msg = "金额不正确";
                        }
                    }
                    invoiceUtil.setJym(checkCode);
                    if (!invoiceUtil.jymValid()) {
                        msg = "校验码不正确";
                    }
                }
            }
            if (msg != null) {
                msg = "第" + xh + "行：" + msg;
                break;
            }
        }
        return msg;
    }

    public static void main(String[] args) {
        //InvoiceUtil invoiceUtil = new InvoiceUtil(null);
        //System.out.println(invoiceUtil.getFplxdm());
        Object[] result = new Object[3];
        System.out.println((Boolean)result[0]);
        if((true && (Boolean) result[0])){
            System.out.println("进来");
        }

    }

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

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

        String company = (String)pramsMap.get("company");
        String menuId = (String)pramsMap.get("menuId");
        JSONObject json = tabulateRedisService.getTabulateMenu(company, menuId);


        List<Tax> list = (List<Tax>)pramsMap.get("orgList");
        if (list == null || list.size() == 0) {
            json.put("datalist", new ArrayList<QsjgQueryVO>());
            json.put("total", 0);
            return super.responseResult(json);
        }

        PageHelper.startPage(curr, size);
        List<TDxInvoice> pageList = signInvoiceSmService.selectQsfpList(pramsMap);
        PageInfo<TDxInvoice> pageInfo = new PageInfo<>(pageList);
        List<TDxInvoice> resultList = pageInfo.getList();

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

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

            for (int i = 0; i < resultList.size(); i++) {
                QsjgQueryVO mxlb = this.convertToQslbView(resultList.get(i), start + i);
                returnList.add(mxlb);
            }
        }
        if (curr == 1) {
            QsInvoiceCount selectQsfpListCount = signInvoiceSmService.selectQsfpListCount(pramsMap);
            String hjje = "0.00";
            String hjse = "0.00";
            if (selectQsfpListCount != null) {
                hjje = AmountFormatUtil.fmtMicrometer(selectQsfpListCount.getSumInvoiceAmount());
                hjse = AmountFormatUtil.fmtMicrometer(selectQsfpListCount.getSumTaxAmount());
            }
            json.put("hjje", hjje);
            json.put("hjse", hjse);
        }
        json.put("datalist", returnList);

        return super.responseResult(json);
    }

    /**
     * 转换成扫描查询结果显示
     *
     * @param tDxInvoice
     *            扫描信息
     * @param i
     *            业务类型列表
     * @return 返回
     */
    private QsjgQueryVO convertToQslbView(TDxInvoice tDxInvoice, int i) {
        // List<DictdetaModel> qsfsModels = dictdetaServcice.selectDictdeta("qsType");
        // List<DictdetaModel> qsztModels = dictdetaServcice.selectDictdeta("qsStatus");
        String qsStatus = tDxInvoice.getQsStatus();
        String qsType = tDxInvoice.getQsType();
        Date invoiceDate = tDxInvoice.getInvoiceDate();

        QsjgQueryVO qsjg = new QsjgQueryVO();
        qsjg.setVoucherNumber(tDxInvoice.getVoucherNumber());
        qsjg.setId(String.valueOf(tDxInvoice.getId()));
        qsjg.setXh(String.valueOf(i));
        qsjg.setNotes(tDxInvoice.getNotes());
        qsjg.setQsDate(DateUtils.dateToStr(tDxInvoice.getQsDate()));
        // 字典转换
        qsjg.setQsStatus(dictdetaServcice.queryDictName(DictConstant.QS_RESULTS, qsStatus));
        qsjg.setQsType(dictdetaServcice.queryDictName(DictConstant.QS_TYPE, qsType));

        qsjg.setDelState(!FpqsjgEnum.YQS.getQsjgDm().equals(qsStatus));
        qsjg.setQsStatus2(qsStatus);
        qsjg.setUserName(tDxInvoice.getUserName());

        /* if (QsfsEnum.APPQS.getQsfsDm().equals(qsType)) {
            qsjg.setImgState(false);
        } else if (QsfsEnum.DRQS.getQsfsDm().equals(qsType)) {
            qsjg.setImgState(false);
        } else if (QsfsEnum.PDFQS.getQsfsDm().equals(qsType)) {
            qsjg.setImgState(true);
        } else if (QsfsEnum.SGQS.getQsfsDm().equals(qsType)) {
            qsjg.setImgState(false);
        } else if (QsfsEnum.SMQS.getQsfsDm().equals(qsType)) {
            qsjg.setImgState(false);
        } else if (QsfsEnum.SMYQS.getQsfsDm().equals(qsType)) {
            qsjg.setImgState(true);
        }*/
        qsjg.setImgState(StringUtils.isNotBlank(tDxInvoice.getImagePath()));

        qsjg.setEditState(FpqsjgEnum.WQS.getQsjgDm().equals(qsStatus)
                && (QsfsEnum.SMYQS.getQsfsDm().equals(qsType) || QsfsEnum.PDFQS.getQsfsDm().equals(qsType)));

        qsjg.setSigningState(FpqsjgEnum.WQS.getQsjgDm().equals(qsStatus)
                && !(QsfsEnum.SMYQS.getQsfsDm().equals(qsType) || QsfsEnum.PDFQS.getQsfsDm().equals(qsType)));
        qsjg.setRemark(tDxInvoice.getRemark());
        qsjg.setGfName(tDxInvoice.getGfName());
        qsjg.setXfName(tDxInvoice.getXfName());
        qsjg.setGfTaxNo(tDxInvoice.getGfTaxNo());
        qsjg.setXfTaxNo(tDxInvoice.getXfTaxNo());
        qsjg.setInvoiceCode(tDxInvoice.getInvoiceCode());
        qsjg.setInvoiceNo(tDxInvoice.getInvoiceNo());
        qsjg.setEleInvoiceNo(tDxInvoice.getEleInvoiceNo());

        qsjg.setInvoiceDate(invoiceDate != null ? DateUtils.dateToStr(tDxInvoice.getInvoiceDate()) : "");
        qsjg.setInvoiceAmount((tDxInvoice.getInvoiceAmount() == null) ? ""
                : AmountFormatUtil.fmtMicrometer(MathUtil.round(tDxInvoice.getInvoiceAmount().toPlainString())));
        qsjg.setTaxAmount((tDxInvoice.getTaxAmount() == null) ? ""
                : AmountFormatUtil.fmtMicrometer(MathUtil.round(tDxInvoice.getTaxAmount().toPlainString())));
        qsjg.setTotalAmount(tDxInvoice.getTotalAmount() == null ? ""
                : AmountFormatUtil.fmtMicrometer(MathUtil.round(tDxInvoice.getTotalAmount().toPlainString())));
        qsjg.setBusinessName(tDxInvoice.getDeptName());
        qsjg.setBusinessCode(tDxInvoice.getDeptId());
        qsjg.setScanId((tDxInvoice.getScanId() == null) ? "" : tDxInvoice.getScanId());
        qsjg.setInvoiceType(tDxInvoice.getInvoiceType());
        qsjg.setCreateDate(DateUtils.dateToStrLong(tDxInvoice.getCreateDate()));
        qsjg.setUuid(tDxInvoice.getUuid());
        if (tDxInvoice.getCheckCode() != null) {

            qsjg.setCheckCode(tDxInvoice.getCheckCode());
        }
        qsjg.setSettlementNo(tDxInvoice.getSettlementNo());
        qsjg.setSettleSource(tDxInvoice.getSettleSource());
        if ("0".equals(tDxInvoice.getSettlementStatus())) {
            qsjg.setSettlementStatus("未结算");
        } else if ("1".equals(tDxInvoice.getSettlementStatus())) {
            qsjg.setSettlementStatus("已结算");
        }
        if (FplxEnum.ZP.getFplxDm().equals(tDxInvoice.getInvoiceType())
                || FplxEnum.DZZP.getFplxDm().equals(tDxInvoice.getInvoiceType())
                || FplxEnum.JDC.getFplxDm().equals(tDxInvoice.getInvoiceType())
                || FplxEnum.TXF.getFplxDm().equals(tDxInvoice.getInvoiceType())) {

            String authStatus = "0,5,6";
            if (tDxInvoice.getAuthStatus() == null || "".equals(tDxInvoice.getAuthStatus())
                    || authStatus.contains(tDxInvoice.getAuthStatus())) {
                qsjg.setAuthStatus("未勾选");
                qsjg.setGxState(false);
            } else {
                qsjg.setAuthStatus("已勾选");
                qsjg.setGxState(true);
            }
        } else {
            qsjg.setAuthStatus("未勾选");
            qsjg.setGxState(false);
        }
        return qsjg;
    }

    /**
     * 转换成扫描查询结果显示
     *
     * @param tDxInvoice
     *            扫描信息
     * @param i
     *            业务类型列表
     * @return 返回
     */
    private QsjgQueryVO convertTodelView(TDxInvoiceDel tDxInvoice, int i) {
        // List<DictdetaModel> qsfsModels = dictdetaServcice.selectDictdeta("qsType");
        String qsType = tDxInvoice.getQsType();
        Date invoiceDate = tDxInvoice.getInvoiceDate();
        QsjgQueryVO qsjg = new QsjgQueryVO();
        qsjg.setId(String.valueOf(tDxInvoice.getId()));
        qsjg.setXh(String.valueOf(i));
        qsjg.setNotes(tDxInvoice.getNotes());
        qsjg.setQsDate(DateUtils.dateToStr(tDxInvoice.getQsDate()));
        qsjg.setUserName(tDxInvoice.getUserName());
        qsjg.setQsType(dictdetaServcice.queryDictName(DictConstant.QS_TYPE, qsType));
        // if (qsfsModels != null) {
        // for (DictdetaModel model : qsfsModels) {
        // if (model.getDictcode().equals(qsType)) {
        // qsjg.setQsType(model.getDictname());
        // }
        // }
        // }
        if (QsfsEnum.APPQS.getQsfsDm().equals(qsType)) {
            qsjg.setImgState(false);
        } else if (QsfsEnum.DRQS.getQsfsDm().equals(qsType)) {
            qsjg.setImgState(false);
        } else if (QsfsEnum.PDFQS.getQsfsDm().equals(qsType)) {
            qsjg.setImgState(true);
        } else if (QsfsEnum.SGQS.getQsfsDm().equals(qsType)) {
            qsjg.setImgState(false);
        } else if (QsfsEnum.SMQS.getQsfsDm().equals(qsType)) {
            qsjg.setImgState(false);
        } else if (QsfsEnum.SMYQS.getQsfsDm().equals(qsType)) {
            qsjg.setImgState(true);
        }
        qsjg.setGfName(tDxInvoice.getGfName());
        qsjg.setXfName(tDxInvoice.getXfName());
        qsjg.setGfTaxNo(tDxInvoice.getGfTaxNo());
        qsjg.setXfTaxNo(tDxInvoice.getXfTaxNo());
        qsjg.setInvoiceCode(tDxInvoice.getInvoiceCode());
        qsjg.setInvoiceNo(tDxInvoice.getInvoiceNo());
        qsjg.setInvoiceDate(invoiceDate != null ? DateUtils.dateToStr(tDxInvoice.getInvoiceDate()) : "");
        qsjg.setInvoiceAmount((tDxInvoice.getInvoiceAmount() == null) ? ""
                : AmountFormatUtil.fmtMicrometer(MathUtil.round(tDxInvoice.getInvoiceAmount().toPlainString())));
        qsjg.setTaxAmount((tDxInvoice.getTaxAmount() == null) ? ""
                : AmountFormatUtil.fmtMicrometer(MathUtil.round(tDxInvoice.getTaxAmount().toPlainString())));
        qsjg.setTotalAmount(tDxInvoice.getTotalAmount() == null ? ""
                : AmountFormatUtil.fmtMicrometer(MathUtil.round(tDxInvoice.getTotalAmount().toPlainString())));
        qsjg.setScanId((tDxInvoice.getScanId() == null) ? "" : tDxInvoice.getScanId());
        qsjg.setInvoiceType(tDxInvoice.getInvoiceType());
        qsjg.setCreateDate(DateUtils.dateToStrLong(tDxInvoice.getScanDate()));
        qsjg.setUuid(tDxInvoice.getUuid());
        if (tDxInvoice.getCheckCode() != null) {

            qsjg.setCheckCode(tDxInvoice.getCheckCode());
        }
        return qsjg;
    }

    /**
     * 根据businessCode获取对应名称用于页面显示
     *
     * @param businessCode
     *            业务单元编码
     * @param businessList
     *            业务单元信息
     * @return 返回
     */

    private String getBusinessName(String businessCode, List<Business> businessList) {
        String businessName = "";
        if (StringUtils.isNotBlank(businessCode) && businessList != null && businessList.size() > 0) {
            for (Business business : businessList) {
                if (StringUtils.isNotBlank(business.getBusinessCode())
                        && business.getBusinessCode().equals(businessCode)) {
                    businessName = StringHelper.trim(business.getBusinessName(), "");
                    break;
                }
            }
        }
        return businessName;
    }

    @Override
    public String ecQsfp(Map<String, String> pramsMap, UserInfo userInfo) {

        JSONObject invoiceDetail = JSONObject.parseObject(pramsMap.get("ids"));
        JSONArray detailArray = (JSONArray)invoiceDetail.get("ids");

        List<Long> idList = new ArrayList<>(detailArray.size());
        for (Object o : detailArray) {
            JSONObject idJson = (JSONObject)o;
            idList.add(idJson.getLong("id"));
        }
        int failureCount = 0;

        int successCount = 0;
        // 查询扫描信息
        DynamicContextHolder.push(pramsMap.get("dbName") + DbConstant.BUSINESS_READ);
        Collection<TDxInvoice> invoiceList = signInvoiceSmService.listByIds(idList);
        for (TDxInvoice tDxInvoice : invoiceList) {
            String userName = pramsMap.get("userName");

            String invoiceType = tDxInvoice.getInvoiceType();
            String invoiceCode = tDxInvoice.getInvoiceCode();
            String invoiceNo = tDxInvoice.getInvoiceNo();
            String invoiceDate = DateUtils.dateToStr(tDxInvoice.getInvoiceDate());
            String invoiceAmount = (tDxInvoice.getInvoiceAmount() == null) ? ""
                    : MathUtil.round(tDxInvoice.getInvoiceAmount().toPlainString());
            String taxAmount =
                    (tDxInvoice.getTaxAmount() == null) ? "" : MathUtil.round(tDxInvoice.getTaxAmount().toPlainString());
            String totalAmount = (tDxInvoice.getTotalAmount() == null) ? ""
                    : MathUtil.round(tDxInvoice.getTotalAmount().toPlainString());
            String checkCode = tDxInvoice.getCheckCode();
            String gfsh = tDxInvoice.getGfTaxNo();
            String xfsh = tDxInvoice.getXfTaxNo();

            pramsMap.put("invoiceType", invoiceType);
            pramsMap.put("invoiceCode", invoiceCode);
            pramsMap.put("invoiceNo", invoiceNo);
            pramsMap.put("invoiceDate", invoiceDate);
            if (StringUtils.isNotBlank(invoiceAmount)) {
                pramsMap.put("invoiceAmount", invoiceAmount);
            }
            if (StringUtils.isNotBlank(taxAmount)) {
                pramsMap.put("taxAmount", taxAmount);
            }
            if (StringUtils.isNotBlank(totalAmount)) {
                pramsMap.put("totalAmount", totalAmount);
            }
            if (StringUtils.isNotBlank(gfsh)) {
                pramsMap.put("gfsh", gfsh);
            }
            if (StringUtils.isNotBlank(xfsh)) {
                pramsMap.put("xfsh", xfsh);
            }
            if (StringUtils.isNotBlank(checkCode)) {
                pramsMap.put("checkCode", checkCode);
            }
            // 签收返回数据信息
            Object[] result = new Object[2];
            // 底账表签收校验
            if (FplxEnum.ZP.getFplxDm().equals(invoiceType) || FplxEnum.TXF.getFplxDm().equals(invoiceType)
                    || FplxEnum.JDC.getFplxDm().equals(invoiceType) || FplxEnum.DZZP.getFplxDm().equals(invoiceType)
                    || (FplxEnum.QDZZP.getFplxDm().equals(invoiceType))|| (FplxEnum.ZZDZ.getFplxDm().equals(invoiceType))
                    || (FplxEnum.SDFP_JDCTYXSFP.getFplxDm().equals(invoiceType))|| (FplxEnum.ESCDZ.getFplxDm().equals(invoiceType))
                    || (FplxEnum.ZZJDC.getFplxDm().equals(invoiceType))|| (FplxEnum.ZZESC.getFplxDm().equals(invoiceType))
                    //|| FplxEnum.TLKP.getFplxDm().equals(invoiceType)
                    //|| FplxEnum.HKDZFP.getFplxDm().equals(invoiceType)
            ) {
                result = fpqsService.zpSaveInvoice(pramsMap, userInfo, tDxInvoice.getQsType(), invoiceType,null);
            } else if (FplxEnum.QDPP.getFplxDm().equals(invoiceType)) {
                pramsMap.put("invoiceAmount", totalAmount);
                JSONObject jsonObject = fpqsService.checkInvoice(pramsMap, userInfo, tDxInvoice.getQsType(), invoiceType);
                String resultCode = jsonObject.getString("resultCode");
                if (jsonObject.containsKey("returnCode")) {
                    result[0] = false;
                } else if (!"0001".equals(resultCode)) {
                    result[0] = false;
                }
                if (StringUtils.isNotBlank(jsonObject.getString("invoiceType"))) {
                    invoiceType = jsonObject.getString("invoiceType");
                    result = fpqsService.qdSaveInvoice(pramsMap, userInfo, tDxInvoice.getQsType(), invoiceType, jsonObject);
                }
            } else {
                // 查验签收规则
                result = fpqsService.dzpSaveInvoice(pramsMap, userInfo, tDxInvoice.getQsType(), invoiceType);
            }
            boolean results = (Boolean) result[0];
            if (results) {
                successCount++;
            } else {
                failureCount++;
            }

        }

        return "签收成功：" + successCount + "条 \n ; 签收失败：" + failureCount + "条";
    }

    @Override
    public String requestValidate(Map<String, String> pramsMap) {
        DynamicContextHolder.push(pramsMap.get("dbName") + DbConstant.BUSINESS_READ);
        String del = null;
        if (pramsMap.containsKey("del")) {
            del = pramsMap.get("del");
        }
        return signInvoiceSmService.requestValidate(pramsMap.get("uuid"), pramsMap.get("userId"), del);
    }

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

        JSONObject checkInfo;
        String invoiceCode = pramsMap.get("invoiceCode");
        String invoiceNo = pramsMap.get("invoiceNo");
        String uuid = invoiceCode + invoiceNo;

        DynamicContextHolder.push(pramsMap.get("dbName") + DbConstant.BUSINESS_READ);
        QueryWrapper<TDxRecordInvoice> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("uuid", uuid);
        TDxRecordInvoice invoiceRecord = super.getOne(queryWrapper);

        if (invoiceRecord != null) {
            checkInfo = signSaveInvoiceInfoService.createInvoiceInfo(invoiceRecord, pramsMap.get("dbName"));
            return super.responseResult(checkInfo);
        } else {
            return null;
        }

    }

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

        JSONObject changeInfo = JSONObject.parseObject(pramsMap.get("changeInfo"));
        String reason = changeInfo.getString("reason");
        JSONArray cancleArray = changeInfo.getJSONArray("uuids");;
        int successCount = 0;

        for (int i = 0; i < cancleArray.size(); i++) {
            JSONObject uuidJson = cancleArray.getJSONObject(i);
            String uuid = uuidJson.getString("uuid");

            DynamicContextHolder.push(pramsMap.get("dbName") + DbConstant.BUSINESS_READ);
            QueryWrapper<TDxRecordInvoice> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("uuid", uuid);

            TDxRecordInvoice dxRecordInvoice = super.getOne(queryWrapper);

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

            // 更新扫描表
            TDxInvoice dxInvoice = new TDxInvoice();
            dxInvoice.setQsStatus("0");
            if ("1".equals(dxRecordInvoice.getRzhYesorno())) {
                dxInvoice.setNotes("取消签收,发票已认证");
            } else {

                dxInvoice.setNotes("取消签收");
            }
            dxInvoice.setUuid(uuid);

            this.cancleYqsxx(uuid, dxInvoice, dxRecordInvoice);
            successCount++;

            // 增加发票日志
            InvoiceLog log = new InvoiceLog();
            log.setInputName(pramsMap.get("userName"));
            log.setInputStatus("5");
            log.setInvoiceCode(uuidJson.getString("invoiceCode"));
            log.setInvoiceNo(uuidJson.getString("invoiceNo"));
            log.setCreateDate(new Date());
            log.setRemark(reason);
            for (QsfsEnum e : QsfsEnum.values()) {
                assert e.getQsfsMc(e.getIndex()) != null;
                if (Objects.equals(e.getQsfsMc(e.getIndex()), uuidJson.getString("qsType"))) {
                    log.setQsType(e.getQsfsDm(e.getIndex()));
                }
            }
            log.setType("4");
            List<InvoiceLog> logs = new ArrayList<>();
            logs.add(log);
            invoiceLogService.toInvoiceLog(logs);

        }

        return "取消签收成功：" + successCount + "条;\n取消签收失败：" + (cancleArray.size() - successCount) + "条";
    }

    /**
     * 撤销已签收信息
     *
     * @param uuid
     *            uuid
     * @param dxInvoice
     *            扫描信息
     * @param dxRecordInvoice
     *            查询条件
     */
    @Transactional(rollbackFor = Exception.class)
    public void cancleYqsxx(String uuid, TDxInvoice dxInvoice, TDxRecordInvoice dxRecordInvoice) {

        String xmlFlag = "";

        TDxInvoiceImg invoiceIma = signInvoiceImgDao.selectOne(new QueryWrapper<TDxInvoiceImg>().eq("scan_id", dxRecordInvoice.getScanId()));
        if(ObjectUtils.isNotEmpty(invoiceIma)){
            if (StringUtils.isNotBlank(invoiceIma.getImage())) {
                if (invoiceIma.getImage().toUpperCase().endsWith("XML")) {
                    xmlFlag = CommonUtil.removeXmlFlag(dxRecordInvoice.getXmlFlag(),"4");
                }
                if (invoiceIma.getImage().toUpperCase().endsWith("PDF")) {
                    xmlFlag = CommonUtil.removeXmlFlag(dxRecordInvoice.getXmlFlag(),"5");
                }
                if (invoiceIma.getImage().toUpperCase().endsWith("OFD")) {
                    xmlFlag = CommonUtil.removeXmlFlag(dxRecordInvoice.getXmlFlag(),"6");
                }
            }
        }

        // 更新底账表签收状态为未签收
        this.baseMapper.updateQsxx(uuid,xmlFlag);
        /*if (FplxEnum.ZP.getFplxDm().equals(dxRecordInvoice.getInvoiceType())
            || FplxEnum.DZZP.getFplxDm().equals(dxRecordInvoice.getInvoiceType())
            || FplxEnum.JDC.getFplxDm().equals(dxRecordInvoice.getInvoiceType())
            || FplxEnum.TXF.getFplxDm().equals(dxRecordInvoice.getInvoiceType())) {

            // 更新底账表签收状态为未签收
            this.baseMapper.updateQsxx(uuid);
        } else {
            super.removeById(dxRecordInvoice);
        }*/
        signInvoiceDao.qxqs(dxInvoice);
    }

    @Override
    public String yqsxxChangeBusiness(Map<String, String> pramsMap) {
        String msg = null;

        JSONObject changeInfo = JSONObject.parseObject(pramsMap.get("changeInfo"));
        String businessCode = pramsMap.get("businessCode");
        String businessName = "";
        if (pramsMap.get("businessName") != null) {
            businessName = pramsMap.get("businessName");
        }
        JSONArray changeArray = changeInfo.getJSONArray("ids");

        List<String> uuidList = new ArrayList<>();
        for (int i = 0; i < changeArray.size(); i++) {
            JSONObject uuidJson = changeArray.getJSONObject(i);
            String uuid = uuidJson.getString("id");
            uuidList.add(uuid);
        }

        DynamicContextHolder.push(pramsMap.get("dbName") + DbConstant.BUSINESS_WRITE);
        // 更新底账表业务单元
        TDxRecordInvoice recordInvoice = new TDxRecordInvoice();
        recordInvoice.setDeptId(businessCode);
        recordInvoice.setDeptName(businessName);
        UpdateWrapper<TDxRecordInvoice> updateWrapper = new UpdateWrapper<>();
        updateWrapper.in("uuid", uuidList);

        // 更新扫描表业务单元
        TDxInvoice dxInvoice = new TDxInvoice();
        dxInvoice.setDeptId(businessCode);
        dxInvoice.setDeptName(businessName);
        UpdateWrapper<TDxInvoice> updateDxInvoiceWrapper = new UpdateWrapper<>();
        updateDxInvoiceWrapper.in("uuid", uuidList);
        this.changeBussiness(recordInvoice, updateWrapper, dxInvoice, updateDxInvoiceWrapper);

        return msg;
    }

    /**
     * 批量变更业务单元
     *
     * @param recordInvoice
     *            抵账信息
     * @param updateWrapper
     *            查询条件
     * @param dxInvoice
     *            扫描信息
     * @param updateDxInvoiceWrapper
     *            查询条件
     */
    @Transactional(rollbackFor = Exception.class)
    public void changeBussiness(TDxRecordInvoice recordInvoice, UpdateWrapper<TDxRecordInvoice> updateWrapper,
                                TDxInvoice dxInvoice, UpdateWrapper<TDxInvoice> updateDxInvoiceWrapper) {
        super.update(recordInvoice, updateWrapper);
        signInvoiceSmService.update(dxInvoice, updateDxInvoiceWrapper);
    }

    @Override
    public boolean getRzhYesNo(Map<String, String> pramsMap) {
        boolean msg = false;

        String uuids = pramsMap.get("uuids");
        JSONArray cancleArray = JSONArray.parseArray(uuids);
        List<String> uuidList = new ArrayList<>();
        for (int i = 0; i < cancleArray.size(); i++) {
            JSONObject uuidJson = cancleArray.getJSONObject(i);
            String uuid = uuidJson.getString("uuid");
            uuidList.add(uuid);
        }

        DynamicContextHolder.push(pramsMap.get("dbName") + DbConstant.BUSINESS_READ);
        QueryWrapper<TDxRecordInvoice> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("uuid", uuidList);
        List<TDxRecordInvoice> list = super.list(queryWrapper);
        if (list.size() > 0) {
            for (TDxRecordInvoice tDxRecordInvoice : list) {
                if ("1".equals(tDxRecordInvoice.getRzhYesorno())) {
                    msg = true;
                    return msg;
                }
            }
        }
        return msg;
    }

    @Override
    public String yqsxxAddRemark(Map<String, String> pramsMap) {
        String msg = null;
        JSONObject changeInfo = JSONObject.parseObject(pramsMap.get("changeInfo"));
        String remark = pramsMap.get("remark");

        JSONArray changeArray = changeInfo.getJSONArray("ids");

        List<String> uuidList = new ArrayList<>();
        for (int i = 0; i < changeArray.size(); i++) {
            JSONObject uuidJson = changeArray.getJSONObject(i);
            String uuid = uuidJson.getString("id");
            uuidList.add(uuid);
        }

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

        // 更新扫描表备注
        TDxInvoice dxInvoice = new TDxInvoice();
        dxInvoice.setRemark(remark);
        UpdateWrapper<TDxInvoice> updateDxInvoiceWrapper = new UpdateWrapper<>();
        updateDxInvoiceWrapper.in("uuid", uuidList);
        signInvoiceSmService.update(dxInvoice, updateDxInvoiceWrapper);

        return msg;
    }

    @Override
    public String getRecord(Map<String, String> pramsMap) {
        JSONObject parse = (JSONObject)JSONObject.parse(pramsMap.get("uuid"));
        String uuid = parse.getString("uuid");

        JSONObject json = new JSONObject();

        DynamicContextHolder.push(pramsMap.get("dbName") + DbConstant.BUSINESS_READ);
        QueryWrapper<TDxRecordInvoice> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("uuid", uuid);
        TDxRecordInvoice record = this.getOne(queryWrapper);
        if (record != null) {
            record.setReturnDate(DateUtils.dateToStr(record.getInvoiceDate()));

        }
        json.put("data", record);

        return super.responseResult(json);
    }

    @Override
    public String batchDel(Map<String, String> pramsMap) {
        JSONObject invoiceDetail = JSONObject.parseObject(pramsMap.get("ids"));
        JSONArray detailArray = (JSONArray)invoiceDetail.get("ids");

        List<Long> idList = new ArrayList<>(detailArray.size());
        for (Object o : detailArray) {
            JSONObject idJson = (JSONObject)o;
            idList.add(idJson.getLong("id"));
        }
        int failureCount = 0;

        int successCount = 0;
        // 查询扫描信息
        DynamicContextHolder.push(pramsMap.get("dbName") + DbConstant.BUSINESS_READ);
        Collection<TDxInvoice> invoiceList = signInvoiceSmService.listByIds(idList);
        for (TDxInvoice tDxInvoice : invoiceList) {

            try {
                boolean deleteElec = false;
                if ("1".equals(tDxInvoice.getQsStatus())) {
                        DynamicContextHolder.push(pramsMap.get("dbName") + DbConstant.BUSINESS_WRITE);
                    TDxRecordInvoice dxRecordInvoice = super.getOne(new QueryWrapper<TDxRecordInvoice>().eq("uuid", tDxInvoice.getUuid()));
                    String xmlFlag = "";

                    TDxInvoiceImg invoiceIma = signInvoiceImgDao.selectOne(new QueryWrapper<TDxInvoiceImg>().eq("scan_id", tDxInvoice.getScanId()));
                    if (StringUtils.isNotBlank(invoiceIma.getImage())) {
                        if (invoiceIma.getImage().toUpperCase().endsWith("XML")) {
                            xmlFlag = CommonUtil.removeXmlFlag(dxRecordInvoice.getXmlFlag(),"4");
                        }
                        if (invoiceIma.getImage().toUpperCase().endsWith("PDF")) {
                            xmlFlag = CommonUtil.removeXmlFlag(dxRecordInvoice.getXmlFlag(),"5");
                        }
                        if (invoiceIma.getImage().toUpperCase().endsWith("OFD")) {
                            xmlFlag = CommonUtil.removeXmlFlag(dxRecordInvoice.getXmlFlag(),"6");
                        }
                    }
                        // 更新底账表签收状态为未签收
                        this.baseMapper.updateQsxx(tDxInvoice.getUuid(),xmlFlag);

                }
                deleteElec = signElecInvoiceService.deleteElec(tDxInvoice.getScanId(), pramsMap.get("dbName"));
                if (deleteElec) {
                    successCount++;
                    QueryWrapper<TDxInvoiceDel> query2 = new QueryWrapper<>();
                    query2.eq("uuid", tDxInvoice.getUuid());
                    TDxInvoiceDel selectDel = signInvoiceDelDao.selectOne(query2);

                    DynamicContextHolder.push(pramsMap.get("dbName") + DbConstant.BUSINESS_WRITE);
                    if (selectDel != null) {
                        // 再次删除只更新时间
                        selectDel.setQsDate(tDxInvoice.getQsDate());
                        selectDel.setQsType(tDxInvoice.getQsType());
                        selectDel.setUpdateDate(DateUtils.getSqlDateLong());
                        signInvoiceDelDao.updateById(selectDel);
                    } else {
                        // 存扫描删除表
                        TDxInvoiceDel insertDel = new TDxInvoiceDel();
                        insertDel.setCheckCode(tDxInvoice.getCheckCode());
                        insertDel.setCompany(tDxInvoice.getCompany());
                        insertDel.setCreateDate(DateUtils.getSqlDateLong());
                        insertDel.setGfName(tDxInvoice.getGfName());
                        insertDel.setGfTaxNo(tDxInvoice.getGfTaxNo());
                        insertDel.setInvoiceAmount(tDxInvoice.getInvoiceAmount());
                        insertDel.setInvoiceCode(tDxInvoice.getInvoiceCode());
                        insertDel.setInvoiceDate(tDxInvoice.getInvoiceDate());
                        insertDel.setInvoiceNo(tDxInvoice.getInvoiceNo());
                        insertDel.setInvoiceSerialNo(tDxInvoice.getInvoiceSerialNo());
                        insertDel.setInvoiceType(tDxInvoice.getInvoiceType());
                        insertDel.setNotes(tDxInvoice.getNotes());
                        insertDel.setQsDate(tDxInvoice.getQsDate());
                        insertDel.setQsType(tDxInvoice.getQsType());
                        insertDel.setScanId(tDxInvoice.getScanId());
                        insertDel.setTaxAmount(tDxInvoice.getTaxAmount());
                        insertDel.setTotalAmount(tDxInvoice.getTotalAmount());
                        insertDel.setUpdateDate(DateUtils.getSqlDateLong());
                        insertDel.setUserAccount(tDxInvoice.getUserAccount());
                        insertDel.setUserName(tDxInvoice.getUserName());
                        insertDel.setUuid(tDxInvoice.getUuid());
                        insertDel.setXfName(tDxInvoice.getXfName());
                        insertDel.setXfTaxNo(tDxInvoice.getXfTaxNo());
                        insertDel.setScanDate(tDxInvoice.getCreateDate());

                        signInvoiceDelDao.insert(insertDel);
                    }
                } else {
                    failureCount++;
                }

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

        }
        return "删除成功：" + successCount + "条 \n ; 删除失败：" + failureCount + "条";
    }

    @Override
    public String selectDelfpList(Map<String, Object> pramsMap, int curr, int size) {
        DynamicContextHolder.push(pramsMap.get("dbName") + DbConstant.BUSINESS_READ);

        String company = (String)pramsMap.get("company");
        String menuId = (String)pramsMap.get("menuId");
        JSONObject json = tabulateRedisService.getTabulateMenu(company, menuId);

        PageHelper.startPage(curr, size);
        List<TDxInvoiceDel> pageList = signInvoiceDelDao.selectDelfpList(pramsMap);
        PageInfo<TDxInvoiceDel> pageInfo = new PageInfo<>(pageList);
        List<TDxInvoiceDel> resultList = pageInfo.getList();

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

        List<QsjgQueryVO> returnList = new ArrayList<>();
        if (resultList != null && resultList.size() > 0) {

            int start = new Long(pageInfo.getStartRow()).intValue();

            for (int i = 0; i < resultList.size(); i++) {
                QsjgQueryVO mxlb = this.convertTodelView(resultList.get(i), start + i);
                returnList.add(mxlb);
            }
        }
        if (curr == 1) {
            QsInvoiceCount selectQsfpListCount = signInvoiceDelDao.selectDelfpListCount(pramsMap);
            if (selectQsfpListCount != null) {

                json.put("hjje", AmountFormatUtil.fmtMicrometer(selectQsfpListCount.getSumInvoiceAmount()));
                json.put("hjse", AmountFormatUtil.fmtMicrometer(selectQsfpListCount.getSumTaxAmount()));
            }
        }
        json.put("datalist", returnList);

        return super.responseResult(json);
    }

    @Override
    public String forceSign(Map<String, String> pramsMap) {
        JSONObject json = new JSONObject();

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

        TDxInvoice tDxInvoice = new TDxInvoice();
        tDxInvoice.setUserAccount(pramsMap.get("userId"));
        tDxInvoice.setUserName(pramsMap.get("userName"));

        tDxInvoice.setScanId(pramsMap.get("scanId"));
        String invoiceCode = pramsMap.get("invoiceCode");
        String invoiceNo = pramsMap.get("invoiceNo");
        String uuid = invoiceCode + invoiceNo;

        tDxInvoice.setInvoiceCode(invoiceCode);
        tDxInvoice.setInvoiceNo(invoiceNo);
        tDxInvoice.setUuid(uuid);
        tDxInvoice.setInvoiceDate(DateUtils.strToDate(pramsMap.get("invoiceDate")));
        tDxInvoice.setGfTaxNo(pramsMap.get("gfsh"));
        tDxInvoice.setXfTaxNo(pramsMap.get("xfsh"));
        tDxInvoice.setGfName(pramsMap.get("gfmc"));
        tDxInvoice.setXfName(pramsMap.get("xfmc"));
        tDxInvoice.setForceSign("1");

        if (pramsMap.get("invoiceAmount") != null && !"".equals(pramsMap.get("invoiceAmount"))) {
            tDxInvoice.setInvoiceAmount(new BigDecimal(pramsMap.get("invoiceAmount")));
        } else {
            tDxInvoice.setInvoiceAmount(new BigDecimal("0.00"));
        }

        if (pramsMap.get("taxAmount") != null && !"".equals(pramsMap.get("taxAmount"))) {
            tDxInvoice.setTaxAmount(new BigDecimal(pramsMap.get("taxAmount")));
        } else {
            tDxInvoice.setTaxAmount(new BigDecimal("0.00"));
        }

        tDxInvoice.setTotalAmount(tDxInvoice.getInvoiceAmount().add(tDxInvoice.getTaxAmount()));
        tDxInvoice.setUpdateDate(DateUtils.getSqlDateLong());
        if (pramsMap.containsKey("checkCode")) {
            tDxInvoice.setCheckCode(pramsMap.get("checkCode"));
        }

        String userName = pramsMap.get("userName");
        InvoiceUtil iu = new InvoiceUtil(invoiceCode);
        String invoiceType = iu.getFplxdm();
        String invoiceDate = pramsMap.get("invoiceDate");
        tDxInvoice.setInvoiceType(invoiceType);
        tDxInvoice.setInvoiceDate(DateUtils.strToDate(invoiceDate));
        String qsType;

        boolean isExits = false;
        // 查看扫描表是否存在
        TDxInvoice invoiceScanInfo = this.getScaninfo(uuid, pramsMap.get("dbName"));

        if (invoiceScanInfo != null) {
            isExits = true;
            qsType = invoiceScanInfo.getQsType();
            if (invoiceScanInfo.getScanId().equals(tDxInvoice.getScanId())) {
                // 如果已存在的发票是当前修改的扫描发票
                tDxInvoice.setUpdateByScanId(true);
            }
            if ("1".equals(invoiceScanInfo.getQsStatus())) {
                tDxInvoice.setNotes("该发票已签收成功，请勿重复操作");
                tDxInvoice.setQsDate(invoiceScanInfo.getQsDate());
                tDxInvoice.setUserName(invoiceScanInfo.getUserName());
                tDxInvoice.setQsStatus(invoiceScanInfo.getQsStatus());
                tDxInvoice.setInvoiceCode(invoiceCode);
                tDxInvoice.setInvoiceNo(invoiceNo);
                tDxInvoice.setInvoiceDate(invoiceScanInfo.getInvoiceDate());
                tDxInvoice.setXfName(invoiceScanInfo.getXfName());
                tDxInvoice.setGfTaxNo(invoiceScanInfo.getGfTaxNo());
                tDxInvoice.setXfTaxNo(invoiceScanInfo.getXfTaxNo());
                tDxInvoice.setInvoiceAmount(invoiceScanInfo.getInvoiceAmount());
                tDxInvoice.setTaxAmount(invoiceScanInfo.getTaxAmount());
                tDxInvoice.setCheckCode(invoiceScanInfo.getCheckCode());
                SmyqsWqsfpVO qsjg = this.convertToSmyqsView(tDxInvoice, invoiceDate, 0);
                json.put("data", qsjg);
                return super.responseResult(json);
            }

        } else {
            DynamicContextHolder.push(pramsMap.get("dbName") + DbConstant.BUSINESS_READ);
            // 直接查询扫描表是否存在信息
            QueryWrapper<TDxInvoice> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("scan_id", pramsMap.get("scanId"));
            TDxInvoice invoiceSm = signInvoiceSmService.getOne(queryWrapper);
            qsType = invoiceSm.getQsType();
            // uuid没找到，按scanId修改
            tDxInvoice.setUpdateByScanId(true);
        }

        String notes = this.validateInvoiceInfo(invoiceCode, invoiceNo);

        if (notes != null) {
            // 信息校验失败
            DynamicContextHolder.push(pramsMap.get("dbName") + DbConstant.BUSINESS_WRITE);
            tDxInvoice.setNotes(notes);
            tDxInvoice.setQsDate(DateUtils.getSqlDateLong());
            tDxInvoice.setUpdateDate(DateUtils.getSqlDateLong());
            SmyqsWqsfpVO qsjg = this.convertToSmyqsView(tDxInvoice, invoiceDate, 1);
            json.put("data", qsjg);
            return super.responseResult(json);
        } else {
            // 专票对比四要素
            if (FplxEnum.ZP.getFplxDm().equals(invoiceType) || FplxEnum.TXF.getFplxDm().equals(invoiceType)
                    || FplxEnum.JDC.getFplxDm().equals(invoiceType) || FplxEnum.DZZP.getFplxDm().equals(invoiceType)) {

                List<TDxRecordInvoice> invoices = this.getInvoiceList(uuid);
                if (invoices == null || invoices.size() == 0) {
                    DynamicContextHolder.push(pramsMap.get("dbName") + DbConstant.BUSINESS_WRITE);
                    // 底账表不存在对应发票
                    tDxInvoice.setNotes("无底账信息，签收失败");
                    tDxInvoice.setQsDate(DateUtils.getSqlDateLong());
                    tDxInvoice.setUpdateDate(DateUtils.getSqlDateLong());
                    // 修改扫描信息
                    SmyqsWqsfpVO qsjg = this.convertToSmyqsView(tDxInvoice, invoiceDate, 0);
                    json.put("data", qsjg);
                    return super.responseResult(json);
                } else {
                    notes = this.compareInvoiceInfo(invoices.get(0), pramsMap);
                    if (notes != null) {
                        DynamicContextHolder.push(pramsMap.get("dbName") + DbConstant.BUSINESS_WRITE);
                        // 信息比对不一致
                        tDxInvoice.setNotes(notes);
                        tDxInvoice.setQsDate(DateUtils.getSqlDateLong());
                        tDxInvoice.setUpdateDate(DateUtils.getSqlDateLong());
                        // 修改扫描信息
                        SmyqsWqsfpVO qsjg = this.convertToSmyqsView(tDxInvoice, invoiceDate, 0);
                        json.put("data", qsjg);
                        return super.responseResult(json);
                    } else {
                        // 直接签收专票
                        DynamicContextHolder.push(pramsMap.get("dbName") + DbConstant.BUSINESS_WRITE);
                        TDxRecordInvoice invoiceUpdate = new TDxRecordInvoice();
                        invoiceUpdate.setId(invoices.get(0).getId());
                        invoiceUpdate.setQsStatus(FpqsjgEnum.YQS.getQsjgDm());
                        invoiceUpdate.setQsType(qsType);
                        invoiceUpdate.setLastUpdateDate(new Date());
                        invoiceUpdate.setQsDate(DateUtils.getSqlDateLong());
                        invoiceUpdate.setQsName(userName);
                        if (tDxInvoice.getDeptId() != null) {

                            invoiceUpdate.setDeptId(tDxInvoice.getDeptId());
                            invoiceUpdate.setDeptName(tDxInvoice.getDeptName());
                        }
                        super.updateById(invoiceUpdate);

                        // 设置签收成功结果
                        this.succSmqs(tDxInvoice, invoices.get(0), qsType);

                        // 增加发票签收日志
                        InvoiceLog log = new InvoiceLog();
                        log.setInputName(userName);
                        log.setInputStatus("1");
                        log.setInvoiceCode(tDxInvoice.getInvoiceCode());
                        log.setInvoiceNo(tDxInvoice.getInvoiceNo());
                        log.setQsType(qsType);
                        log.setType("3");
                        log.setCreateDate(new Date());
                        List<InvoiceLog> logs = new ArrayList<>();
                        logs.add(log);
                        invoiceLogService.toInvoiceLog(logs);

                    }
                }
            } else {
                Map<String, String> tax = getTax();
                String name = tax.get(tDxInvoice.getGfTaxNo());

                if (StringUtils.isNotBlank(name) && StringUtils.isNoneBlank(tDxInvoice.getGfName()) && !CompareNameUtils
                        .changeBrackets(name).equals(CompareNameUtils.changeBrackets(tDxInvoice.getGfName().trim()))) {

                    // 校验购方名称
                    tDxInvoice.setQsStatus(FpqsjgEnum.WQS.getQsjgDm());
                    tDxInvoice.setNotes("登录人公司名称与发票的购方名称不一致");
                } else {
                    tDxInvoice.setNotes("签收成功");
                    tDxInvoice.setQsStatus(FpqsjgEnum.YQS.getQsjgDm());

                    // 签收成功存底账
                    List<TDxRecordInvoice> invoices = this.getInvoiceList(uuid);
                    DynamicContextHolder.push(pramsMap.get("dbName") + DbConstant.BUSINESS_WRITE);
                    TDxRecordInvoice invoiceUpdate = new TDxRecordInvoice();
                    invoiceUpdate.setInvoiceType(tDxInvoice.getInvoiceType());
                    invoiceUpdate.setInvoiceCode(tDxInvoice.getInvoiceCode());
                    invoiceUpdate.setInvoiceNo(tDxInvoice.getInvoiceNo());
                    invoiceUpdate.setGfName(tDxInvoice.getGfName());
                    invoiceUpdate.setGfTaxNo(tDxInvoice.getGfTaxNo());
                    invoiceUpdate.setXfTaxNo(tDxInvoice.getXfTaxNo());
                    invoiceUpdate.setXfName(tDxInvoice.getXfName());
                    invoiceUpdate.setInvoiceAmount(tDxInvoice.getInvoiceAmount());
                    invoiceUpdate.setTaxAmount(tDxInvoice.getTaxAmount());
                    invoiceUpdate.setInvoiceDate(tDxInvoice.getInvoiceDate());
                    invoiceUpdate.setUuid(uuid);
                    invoiceUpdate.setCheckCode(tDxInvoice.getCheckCode());
                    invoiceUpdate.setQsDate(DateUtils.getSqlDateLong());
                    invoiceUpdate.setQsName(pramsMap.get("userName"));
                    invoiceUpdate.setQsStatus(FpqsjgEnum.YQS.getQsjgDm());
                    invoiceUpdate.setQsType(qsType);
                    invoiceUpdate.setCompany(pramsMap.get("company"));
                    invoiceUpdate.setTotalAmount(tDxInvoice.getTotalAmount());
                    if (invoices == null || invoices.size() == 0) {
                        invoiceUpdate.setCreateDate(DateUtils.getSqlDateLong());
                        invoiceUpdate.setLastUpdateDate(DateUtils.getSqlDateLong());
                        super.save(invoiceUpdate);
                    } else {
                        invoiceUpdate.setId(invoices.get(0).getId());
                        invoiceUpdate.setLastUpdateDate(DateUtils.getSqlDateLong());
                        super.updateById(invoiceUpdate);

                    }
                }
            }
            // 普票直接签收

            DynamicContextHolder.push(pramsMap.get("dbName") + DbConstant.BUSINESS_WRITE);
            if (!isExits) {

                if (tDxInvoice.getUpdateByScanId()) {
                    // 已存在扫描记录
                    UpdateWrapper<TDxInvoice> updateWrapper = new UpdateWrapper<>();
                    updateWrapper.eq("scan_id", tDxInvoice.getScanId());
                    tDxInvoice.setUpdateDate(new Date());
                    tDxInvoice.setQsDate(DateUtils.getSqlDateLong());
                    tDxInvoice.setCreateDate(null);
                    signInvoiceSmService.update(tDxInvoice, updateWrapper);
                    SmyqsWqsfpVO qsjg = this.convertToSmyqsView(tDxInvoice, null, 0);
                    json.put("data", qsjg);
                    return super.responseResult(json);
                } else {
                    // 不存在扫描记录
                    tDxInvoice.setInvoiceSerialNo(Long.valueOf(scanIdUtils.createSerialNum()));
                    signInvoiceSmService.save(tDxInvoice);
                    SmyqsWqsfpVO qsjg = this.convertToSmyqsView(tDxInvoice, null, 0);
                    json.put("data", qsjg);
                    return super.responseResult(json);
                }
            } else {
                // 已存在扫描记录
                // 已存在扫描记录,且存在的记录非当前扫描修改记录，先删再更新
                if (!tDxInvoice.getUpdateByScanId()) {

                    UpdateWrapper<TDxInvoice> delWrapper = new UpdateWrapper<>();
                    delWrapper.eq("scan_id", tDxInvoice.getScanId());
                    signInvoiceSmService.remove(delWrapper);
                }

                UpdateWrapper<TDxInvoice> updateWrapper = new UpdateWrapper<>();
                updateWrapper.eq("uuid", tDxInvoice.getUuid());
                tDxInvoice.setQsDate(DateUtils.getSqlDateLong());
                tDxInvoice.setUpdateDate(new Date());
                tDxInvoice.setCreateDate(null);
                signInvoiceSmService.update(tDxInvoice, updateWrapper);

                SmyqsWqsfpVO qsjg = this.convertToSmyqsView(tDxInvoice, null, 0);
                json.put("data", qsjg);
                return super.responseResult(json);
            }
        }

    }

    private Map<String, String> getTax() {
        String data = BaseContextHandler.getUserInfo();
        JSONObject jsonObject = JSONObject.parseObject(data);
        UserInfo userInfo = jsonObject.toJavaObject(UserInfo.class);
        List<Tax> org = userInfo.getOrg();
        Map<String, String> map = new HashMap<>();
        if (org != null && org.size() > 0) {
            for (Tax tax : org) {
                map.put(tax.getTaxno(), tax.getTaxname());
            }
        }
        return map;
    }

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

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

        String company = (String)pramsMap.get("company");
        String menuId = (String)pramsMap.get("menuId");
        JSONObject json = tabulateRedisService.getTabulateMenu(company, menuId);
        if (curr == 1) {
            String hjje = "0.00";
            String hjse = "0.00";
            QsInvoiceCount selectQsfpListCount = signInvoiceSmService.selectQsfpListCountMryx(pramsMap);
            if (selectQsfpListCount != null) {
                hjje = AmountFormatUtil.fmtMicrometer(selectQsfpListCount.getSumInvoiceAmount());
                hjse = AmountFormatUtil.fmtMicrometer(selectQsfpListCount.getSumTaxAmount());
            }
            json.put("hjje", hjje);
            json.put("hjse", hjse);
        }
        PageHelper.startPage(curr, size);
        List<TDxInvoice> pageList = signInvoiceSmService.selectQsfpListMryx(pramsMap);
        PageInfo<TDxInvoice> pageInfo = new PageInfo<>(pageList);
        List<TDxInvoice> resultList = pageInfo.getList();

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

        List<QsjgQueryVO> returnList = new ArrayList<>();
        if (resultList != null && resultList.size() > 0) {

            int start = new Long(pageInfo.getStartRow()).intValue();

            for (int i = 0; i < resultList.size(); i++) {
                QsjgQueryVO mxlb = this.convertToQslbView(resultList.get(i), start + i);
                returnList.add(mxlb);
            }
        }

        json.put("datalist", returnList);

        return super.responseResult(json);
    }

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

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

        invoice.setInvoiceType(invoiceType);
        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"));
        try {
            invoice.setTaxAmount(queryInvoiceResult.getBigDecimal("taxAmount"));
        } catch (Exception e) {
            invoice.setTaxAmount(new BigDecimal("0"));
        }
        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;
    }

    @Override
    public String saveSettle(Map<String, Object> pramsMap) {
        String msg = null;
        JSONObject changeInfo = JSONObject.parseObject((String)pramsMap.get("changeInfo"));
        JSONArray changeArray = changeInfo.getJSONArray("uuids");

        List<String> uuidList = new ArrayList<>();
        for (int i = 0; i < changeArray.size(); i++) {
            JSONObject uuidJson = changeArray.getJSONObject(i);
            String uuid = uuidJson.getString("uuid");
            uuidList.add(uuid);
        }
        pramsMap.put("uuids", uuidList);
        DynamicContextHolder.push(pramsMap.get("dbName") + DbConstant.BUSINESS_WRITE);
        // 更新底账表结算信息
        signInvoiceDao.saveRecodSettlementNo(pramsMap);
        // 更新扫描表结算信息
        signInvoiceDao.saveSettlementNo(pramsMap);

        return msg;
    }

    @Override
    public String cancelRelate(Map<String, String> pramsMap) {
        String msg = null;
        JSONObject changeInfo = JSONObject.parseObject(pramsMap.get("changeInfo"));
        JSONArray changeArray = changeInfo.getJSONArray("uuids");

        List<String> uuidList = new ArrayList<>();
        for (int i = 0; i < changeArray.size(); i++) {
            JSONObject uuidJson = changeArray.getJSONObject(i);
            String uuid = uuidJson.getString("uuid");
            uuidList.add(uuid);
        }
        DynamicContextHolder.push(pramsMap.get("dbName") + DbConstant.BUSINESS_WRITE);
        // 更新底账表结算信息
        signInvoiceDao.cancelRecodSettle(uuidList);
        // 更新扫描表结算信息
        signInvoiceDao.cancelSettle(uuidList);

        return msg;
    }

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

        String msg = null;
        JSONObject changeInfo = JSONObject.parseObject((String)pramsMap.get("changeInfo"));
        JSONArray changeArray = changeInfo.getJSONArray("uuids");

        List<String> uuidList = new ArrayList<>();
        for (int i = 0; i < changeArray.size(); i++) {
            JSONObject uuidJson = changeArray.getJSONObject(i);
            String uuid = uuidJson.getString("uuid");
            uuidList.add(uuid);
        }
        pramsMap.put("uuids", uuidList);
        DynamicContextHolder.push(pramsMap.get("dbName") + DbConstant.BUSINESS_WRITE);
        // 更新底账表结算信息
        signInvoiceDao.updateRecodUser(pramsMap);
        // 更新扫描表结算信息
        signInvoiceDao.updateUser(pramsMap);

        return msg;
    }

    /**
     * 构建统计实体集
     *
     * @param queryInvoiceResult
     *            响应实体
     * @return 抵账统计实体
     */
    @Override
    public List<TDxRecordInvoiceStatistics> buildRecordInvoiceStatisticsList(JSONObject queryInvoiceResult) {
        List<TDxRecordInvoiceDetail> recordInvoiceDetail =
                signSaveInvoiceInfoService.getRecordInvoiceDetail(queryInvoiceResult);
        // 定义返回值
        final List<TDxRecordInvoiceStatistics> recordInvoiceStatisticsList = new ArrayList<>();
        // 最终要的结果
        final Map<String, List<TDxRecordInvoiceDetail>> resultMap = new HashMap<>();
        // 按税率分组
        recordInvoiceDetail.forEach(dataItem -> {
            if (!"原价合计".equals(dataItem.getGoodsName().trim()) && !"折扣额合计".equals(dataItem.getGoodsName().trim())
                    && !"(详见销货清单)".equals(dataItem.getGoodsName().trim())
                    && !"（详见销货清单）".equals(dataItem.getGoodsName().trim())
                    && org.apache.commons.lang.StringUtils.isNotEmpty(dataItem.getTaxRate())) {
                if (resultMap.containsKey(dataItem.getTaxRate())) {
                    resultMap.get(dataItem.getTaxRate()).add(dataItem);
                } else {
                    final List<TDxRecordInvoiceDetail> list = new ArrayList<>();
                    list.add(dataItem);
                    resultMap.put(dataItem.getTaxRate(), list);
                }
            }
        });
        String invoiceType = queryInvoiceResult.getString("invoiceType");
        // 循环遍历map获取每组明细，并循环遍历每组里的明细组装抵账统计数据
        for (Map.Entry<String, List<TDxRecordInvoiceDetail>> entry : resultMap.entrySet()) {
            // 获取每组明细
            final List<TDxRecordInvoiceDetail> detailList = entry.getValue();
            // 定义抵账统计实体
            final TDxRecordInvoiceStatistics recordInvoiceStatistics = new TDxRecordInvoiceStatistics();
            // 税额
            BigDecimal taxAmount = new BigDecimal("0.0");
            // 金额
            BigDecimal detailAmount = new BigDecimal("0.0");
            // 循环赋值
            for (TDxRecordInvoiceDetail invoiceDetail : detailList) {
                BigDecimal bigDecimal;
                try {
                    bigDecimal = new BigDecimal(invoiceDetail.getTaxAmount());
                } catch (Exception e) {
                    bigDecimal = new BigDecimal("0");
                }
                taxAmount = taxAmount.add(bigDecimal);
                detailAmount = detailAmount.add(new BigDecimal(invoiceDetail.getDetailAmount()));

            }
            // 价税合计
            final BigDecimal totalAmount = taxAmount.add(detailAmount);
            // 税率
            recordInvoiceStatistics.setTaxRate(entry.getKey());
//            if(FplxEnum.QDZZP.getFplxDm().equals(invoiceType) || FplxEnum.QDPP.getFplxDm().equals(invoiceType)){
//                // 发票号码
//                recordInvoiceStatistics.setInvoiceNo(queryInvoiceResult.getString("invoiceCode")+queryInvoiceResult.getString("invoiceNo"));
//            }else {
//                // 发票号码
//                recordInvoiceStatistics.setInvoiceNo(queryInvoiceResult.getString("invoiceNo"));
//                // 发票代码
//                recordInvoiceStatistics.setInvoiceCode(queryInvoiceResult.getString("invoiceCode"));
//            }
            //// 发票号码
            recordInvoiceStatistics.setInvoiceNo(queryInvoiceResult.getString("invoiceNo"));
            // 发票代码
            recordInvoiceStatistics.setInvoiceCode(queryInvoiceResult.getString("invoiceCode"));
            // 税额
            recordInvoiceStatistics.setTaxAmount(taxAmount);
            // 金额
            recordInvoiceStatistics.setDetailAmount(detailAmount);
            // 价税合计
            recordInvoiceStatistics.setTotalAmount(totalAmount);
            // 放入集合
            recordInvoiceStatisticsList.add(recordInvoiceStatistics);
        }
        // 返回
        return recordInvoiceStatisticsList;
    }

    @Override
    public String getUser(Map<String, String> pramsMap) {
        JSONObject json = new JSONObject();
        DynamicContextHolder.push(DbConstant.BASICS_READ);

        List<Map<String, String>> users = this.baseMapper.getUser(pramsMap.get("company"));

        json.put("dataList", users);
        return super.responseResult(json);
    }

    public TDxRecordInvoice updateRecordInvoice(JSONObject queryInvoiceResult, TDxRecordInvoice invoice) {

        invoice.setInvoiceAmount(queryInvoiceResult.getBigDecimal("invoiceAmount"));
        invoice.setTaxAmount(queryInvoiceResult.getBigDecimal("taxAmount"));
        invoice.setTotalAmount(queryInvoiceResult.getBigDecimal("totalAmount"));
        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"));
        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.setLastUpdateDate(new Date());
        return invoice;
    }
}
