package com.dxhy.customs.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dxhy.api.model.config.Business;
import com.dxhy.api.model.config.Tax;
import com.dxhy.api.model.config.UserInfo;
import com.dxhy.common.constant.DbConstant;
import com.dxhy.common.constant.DictConstant;
import com.dxhy.common.datasource.config.DynamicContextHolder;
import com.dxhy.common.enums.DataSourceEnum;
import com.dxhy.common.enums.QSignStatusEnum;
import com.dxhy.common.enums.QsfsEnum;
import com.dxhy.common.service.CustomsLogService;
import com.dxhy.common.service.DictdetaServcice;
import com.dxhy.common.service.TabulateRedisService;
import com.dxhy.common.service.impl.MpBaseServiceImpl;
import com.dxhy.common.util.*;
import com.dxhy.common.utils.DateUtils;
import com.dxhy.common.vo.CustomsLog;
import com.dxhy.customs.constants.*;
import com.dxhy.customs.dao.CustomsRecordDao;
import com.dxhy.customs.dao.CustomsScanLogDao;
import com.dxhy.customs.entity.TdxCustoms;
import com.dxhy.api.model.custom.TdxCustomsRecord;
import com.dxhy.api.model.custom.TDxScanCustomsLog;
import com.dxhy.customs.model.CustomsInsertImpotVO;
import com.dxhy.customs.model.CustomsSignVO;
import com.dxhy.common.utils.ResultData;
import com.dxhy.customs.model.TdxCustomsRecordDTO;
import com.dxhy.customs.service.CustomsRecordService;
import com.dxhy.customs.service.CustomsService;
import com.dxhy.customs.service.CustomsSignService;
import com.dxhy.customs.utils.DateUtil;
import com.dxhy.customs.utils.ObjectUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

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

/**
 * @author dxhy
 */
@SuppressWarnings({"AlibabaMethodTooLong", "AlibabaUndefineMagicConstant"})
@Service("customsSignService")
@Slf4j
public class CustomsSignServiceImpl extends MpBaseServiceImpl<CustomsRecordDao, TdxCustomsRecord>
    implements CustomsSignService {

    @Resource
    private ScanIdUtils scanIdUtils;
    @Resource
    private CustomsService customsService;
    @Resource
    private CustomsRecordService customsRecordService;
    @Resource
    private CustomsLogService logService;
    @Resource
    private TabulateRedisService tabulateRedisService;
    @Resource
    private CustomsScanLogDao scanLogDao;
    @Resource
    private DictdetaServcice dictdetaServcice;

    @Override
    public String queryManualSign(Page page, TdxCustomsRecordDTO entity, UserInfo userInfo) throws Exception {
        DynamicContextHolder.push(userInfo.getDbName() + DbConstant.BUSINESS_READ);
        entity.setParam(page);
        if (StringUtils.isEmpty(entity.getGfTaxNo())) {
            entity.setBuyTaxNoFromUser(userInfo);
        }

        ResultData<Object> resultData = new ResultData<>();
        JSONObject tabulateMenu = tabulateRedisService.getTabulateMenu(userInfo.getCompany(), entity.getMenuId());
        resultData.putTabulateMenu(tabulateMenu);

        if (entity.getGfTaxNo() == null && CollectionUtils.isEmpty(entity.getGfTaxNoList())) {
            return resultData.getPageData(null).toJsonBase();
        }

        // 合计信息,仅第一页时需要统计，减少数据库压力
        Map mapTj = null;
        if (entity.getCurr() == 1) {
            mapTj = this.baseMapper.queryManualSignHj(entity);
        }

        Page<Map<String, Object>> result = this.baseMapper.queryManualSign(page, entity);
        if (ResultData.isEmpty(result)) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            for (int i = 0; i < page.getRecords().size(); i++) {
                Map<String, Object> map = result.getRecords().get(i);
                map.put("index",
                    String.valueOf((((page.getCurrent() == 0 ? 1 : page.getCurrent()) - 1) * page.getSize()) + i + 1));

                //字典相关转换
                String applyCheck = (String) map.get("applyCheck");
                map.put("applyCheck", dictdetaServcice.queryDictName(DictConstant.APPLY_CHECK,applyCheck));

                String checkStatus = (String) map.get("checkStatus");
                map.put("checkStatus", dictdetaServcice.queryDictName(DictConstant.CHECK_STATUS,checkStatus));

                String dataSources =(String) map.get("dataSources");
                map.put("dataSources",dictdetaServcice.queryDictName(DictConstant.JKSCJFS,dataSources));

                String glzt = (String) map.get("glzt");
                map.put("glzt",StringUtils.isBlank(glzt)?"正常":dictdetaServcice.queryDictName(DictConstant.GLZT,glzt));

                String auditStatus = (String)map.get("auditStatus");
                map.put("auditStatus",dictdetaServcice.queryDictName(DictConstant.AUDIT_STATUS,auditStatus));

                String entryDiscrepancy =(String) map.get("entryDiscrepancy");
                map.put("entryDiscrepancy",dictdetaServcice.queryDictName(DictConstant.ENTRY_DISCREPANCY,entryDiscrepancy));

                if (StringUtils.isNotBlank((String)map.get("taxAmount"))) {
                    map.put("taxAmount",
                            AmountFormatUtil.fmtMicrometer(new BigDecimal(ObjectUtil.fixNull(map.get("taxAmount")))
                                    .setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString()));
                }

                if (map.get("fillInDate") != null) {
                    map.put("fillInDate", map.get("fillInDate"));
                }
            }
        }

        return resultData.getTjData(mapTj).getPageData(result).toJsonBase();
    }

    @Override
    public String batchSign(String costomsInfo, UserInfo userInfo) {
        DynamicContextHolder
            .push(StringUtils.defaultString(userInfo.getDbName(), "business") + DbConstant.BUSINESS_READ);
        JSONObject jsonObject = JSONObject.parseObject(costomsInfo);
        JSONArray jsonArray = jsonObject.getJSONArray("ids");
        String businessCode = jsonObject.getString("businessCode");
        String businessName = "";
        if (org.apache.commons.lang3.StringUtils.isNoneBlank(businessCode) && !"99".equals(businessCode)) {
            List<Business> businessList = userInfo.getBusiness();
            for (Business business : businessList) {
                if (business.getBusinessCode().equals(businessCode)) {
                    businessName = business.getBusinessName();
                }
            }
        }
        int i = 0, fail = 0;
        if (jsonArray != null && jsonArray.size() > 0) {
            List<CustomsLog> logList = new ArrayList<>();
            for (int j = 0; j < jsonArray.size(); j++) {
                String id = jsonArray.getString(j);
                TdxCustomsRecord record = this.baseMapper.selectById(id);

                CustomsLog customsLog = new CustomsLog();
                customsLog.setCustomsCode(record.getCustomsCode());
                customsLog.setQsType("4");
                customsLog.setCreateDate(new Date());
                customsLog.setType("3");
                customsLog.setInputName(userInfo.getLoginname());

                record.setDeptId(businessCode);
                record.setDeptName(businessName);
                // 采集数据
                if ("0".equals(record.getDataSources())) {

                    if (!"0".equals(record.getGlzt())) {
                        insertTdxCustoms(record, QSignStatusEnum.A.getKey(), QsfsEnum.SGQS.getQsfsDm(), "签收失败！管理状态异常",
                            userInfo);
                        fail++;
                        customsLog.setInputStatus("2");
                        logList.add(customsLog);
                        continue;
                    } else if (!"0".equals(record.getEntryDiscrepancy())) {
                        insertTdxCustoms(record, QSignStatusEnum.A.getKey(), QsfsEnum.SGQS.getQsfsDm(), "签收失败！含录入不符项",
                            userInfo);
                        fail++;
                        customsLog.setInputStatus("2");
                        logList.add(customsLog);
                        continue;
                    }
                } else {// 录入数据
                    if (!"1".equals(record.getAuditStatus()) && "0".equals(record.getApplyCheck())) {
                        insertTdxCustoms(record, QSignStatusEnum.A.getKey(), QsfsEnum.SGQS.getQsfsDm(),
                            "签收失败！稽核状态不相符稽核状态为：" + AuditStatusEnum.getVal(record.getAuditStatus()), userInfo);
                        fail++;
                        customsLog.setInputStatus("2");
                        logList.add(customsLog);
                        continue;
                    } else if ("1".equals(record.getApplyCheck()) && "1".equals(record.getCheckStatus())) {
                        insertTdxCustoms(record, QSignStatusEnum.A.getKey(), QsfsEnum.SGQS.getQsfsDm(),
                            "签收失败！核查结果为不允许抵扣/退税", userInfo);
                        fail++;
                        customsLog.setInputStatus("2");
                        logList.add(customsLog);
                        continue;
                    }
                }

                sign(record, userInfo, QsfsEnum.SGQS.getQsfsDm());
                TdxCustoms customs =
                    insertTdxCustoms(record, QSignStatusEnum.B.getKey(), QsfsEnum.SGQS.getQsfsDm(), "签收成功！", userInfo);
                i++;
                this.baseMapper.updateById(record);
                customsLog.setInputStatus("1");
                logList.add(customsLog);
            }

            if (logList.size() > 0) {
                logService.toCustomsLog(logList);
            }
        }

        return "签收成功" + i + "条；签收失败" + fail + "条";
    }

    @Override
    public String infoCollect(String costomsInfo, UserInfo userInfo) {
        DynamicContextHolder.push(
            StringUtils.defaultString(ObjectUtil.fixNull(userInfo.getDbName()), "business") + DbConstant.BUSINESS_READ);
        JSONObject jsonObject = JSONObject.parseObject(costomsInfo);
        JSONArray jsonArray = jsonObject.getJSONArray("customs");
        String gfTaxNo = jsonObject.getString("gfTaxNo");
        List<CustomsInsertImpotVO> datalist = new ArrayList<>();
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject json = jsonArray.getJSONObject(i);
            String customsCode = json.getString("customsCode");
            String gfTaxNoJson = json.getString("gfTaxNo");
            String fillInDate = json.getString("fillInDate");
            String taxAmount = json.getString("taxAmount");

            CustomsInsertImpotVO vo = new CustomsInsertImpotVO();
            vo.setJkdwsh(gfTaxNoJson);
            vo.setJkshm(customsCode);
            vo.setSkje(taxAmount);
            vo.setTfrq(fillInDate);
            datalist.add(vo);
        }

        Map<String, Object> pramsMap = new HashMap<>(16);
        String s = JSONObject.toJSONString(datalist);
        List<String> gfshList = UserInfoUtil.getGfshAll(userInfo.getOrg());
        pramsMap.put("dbName", userInfo.getDbName());
        pramsMap.put("gfsh", gfshList);
        pramsMap.put("datalist", JSONObject.toJSON(s));

        return customsRecordService.submitImportCustoms(pramsMap, userInfo);
    }

    @Override
    public String importSign(Map<String, String> pramsMap, UserInfo userInfo) {
        DynamicContextHolder.push(
            StringUtils.defaultString(ObjectUtil.fixNull(userInfo.getDbName()), "business") + DbConstant.BUSINESS_READ);
        String businessCode = pramsMap.get("businessCode");
        String company = pramsMap.get("company");
        String datalist = pramsMap.get("datalist");
        String menuId = pramsMap.get("menuId");
        JSONArray jsonArray = JSONArray.parseArray(datalist);
        String businessName = "";
        List<Business> businessList = new ArrayList<>();
        if (org.apache.commons.lang3.StringUtils.isNoneBlank(businessCode) && !"99".equals(businessCode)) {
            businessList = userInfo.getBusiness();
            for (Business business : businessList) {
                if (business.getBusinessCode().equals(businessCode)) {
                    businessName = business.getBusinessName();
                }
            }
        }
        List<String> gfshAll = UserInfoUtil.getGfshAll(userInfo.getOrg());

        List<CustomsSignVO> returnList = new ArrayList<>();
        List<CustomsLog> logList = new ArrayList<>();
        for (int i = 0; i < jsonArray.size(); i++) {
            CustomsSignVO param = jsonArray.getObject(i, CustomsSignVO.class);
            param.setIndex(String.valueOf(i + 1));
            returnList.add(param);
            String qsStatus = "1";

            LambdaQueryWrapper<TdxCustoms> customsLambdaQueryWrapper = new LambdaQueryWrapper<>();
            customsLambdaQueryWrapper.eq(TdxCustoms::getCustomsCode, param.getCustomsCode());
            TdxCustoms tDxCustoms = customsService.getOne(customsLambdaQueryWrapper);
            if (tDxCustoms != null && "1".equals(tDxCustoms.getQsStatus())) {
                signToVO(tDxCustoms, param, false);
                param.setNotes("该票据已签收成功！请勿重复操作");
                param.setCollectState(false);
                continue;
            }

            if (!ObjectUtil.checkData(param.getGfTaxNo(), param.getCustomsCode(), param.getFillInDate(),
                param.getTaxAmount())) {
                param.setNotes("数据不全");
                continue;
            }

            LambdaQueryWrapper<TdxCustomsRecord> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(TdxCustomsRecord::getCustomsCode, param.getCustomsCode());
            TdxCustomsRecord one = this.baseMapper.selectOne(wrapper);

            if (one == null) {
                TdxCustoms customs = new TdxCustoms();
                customs.setNotes("签收失败！无此票据，需数据采集");
                customs.setQsStatus("0");
                customs.setCustomsCode(param.getCustomsCode());
                customs.setGfTaxNo(param.getGfTaxNo());
                customs.setCreateDate(DateUtils.getSqlDateLong());
                customs.setFillInDate(DateUtils.strToDate(param.getFillInDate()));
                customs.setTaxAmount(param.getTaxAmount());
                customs.setDeptId(businessCode);
                customs.setDeptName(businessName);
                customs.setUserAccount(userInfo.getId());
                customs.setUserName(userInfo.getUsername());
                customs.setScanId(UUID.randomUUID().toString());
                customs.setInvoiceSerialNo(Long.valueOf(scanIdUtils.createSerialNum()));
                customs.setQsDate(DateUtils.getSqlDateLong());
                customs.setQsType(QsfsEnum.DRQS.getQsfsDm());
                if (tDxCustoms == null) {
                    DynamicContextHolder
                        .push(StringUtils.defaultString(ObjectUtil.fixNull(userInfo.getDbName()), "business")
                            + DbConstant.BUSINESS_WRITE);
                    customsService.save(customs);
                } else {
                    customs.setId(tDxCustoms.getId());
                    DynamicContextHolder
                        .push(StringUtils.defaultString(ObjectUtil.fixNull(userInfo.getDbName()), "business")
                            + DbConstant.BUSINESS_WRITE);
                    customsService.updateById(customs);
                }
                signToVO(customs, param, true);
                param.setCollectState(true);
                param.setEditState(true);
                continue;
            }
            one.setDeptName(businessName);
            one.setDeptId(businessCode);
            Double oTaxAmount = Double.valueOf(one.getTaxAmount());
            Double pTaxAmount = Double.valueOf(param.getTaxAmount());

            CustomsLog customsLog = new CustomsLog();
            customsLog.setCustomsCode(one.getCustomsCode());
            customsLog.setQsType("3");
            customsLog.setCreateDate(new Date());
            customsLog.setType("3");
            customsLog.setInputName(userInfo.getLoginname());
            if (gfshAll.size() == 0 || !gfshAll.contains(one.getGfTaxNo())) {
                qsStatus = "0";
                tDxCustoms = insertTdxCustoms(one, qsStatus, QsfsEnum.DRQS.getQsfsDm(), "签收失败！无税号权限", userInfo);
                signToVO(tDxCustoms, param, true);
                param.setCollectState(false);
                param.setEditState(true);
                customsLog.setInputStatus("2");
                logList.add(customsLog);
                continue;
            }

            if (!DateUtil.compare(one.getFillInDate(), DateUtil.strToDate(param.getFillInDate()))) {
                qsStatus = "0";
                tDxCustoms = insertTdxCustoms(one, qsStatus, QsfsEnum.DRQS.getQsfsDm(), "签收失败！填发日期与底账不一致", userInfo);
                signToVO(tDxCustoms, param, true);
                param.setCollectState(false);
                param.setEditState(true);
                customsLog.setInputStatus("2");
                logList.add(customsLog);
                continue;
            }

            if (!oTaxAmount.equals(pTaxAmount)) {
                qsStatus = "0";
                tDxCustoms = insertTdxCustoms(one, qsStatus, QsfsEnum.DRQS.getQsfsDm(), "签收失败！税款金额与底账不一致", userInfo);
                signToVO(tDxCustoms, param, true);
                param.setCollectState(false);
                param.setEditState(true);
                customsLog.setInputStatus("2");
                logList.add(customsLog);
                continue;
            }

            if (!param.getGfTaxNo().trim().equals(one.getGfTaxNo())) {
                qsStatus = "0";
                tDxCustoms = insertTdxCustoms(one, qsStatus, QsfsEnum.DRQS.getQsfsDm(), "签收失败！缴款单位与底账不一致", userInfo);
                signToVO(tDxCustoms, param, true);
                param.setCollectState(false);
                param.setEditState(true);
                customsLog.setInputStatus("2");
                logList.add(customsLog);
                continue;
            }

            // 采集数据
            if ("0".equals(one.getDataSources())) {

                if (!"0".equals(one.getGlzt())) {
                    qsStatus = "0";
                    tDxCustoms = insertTdxCustoms(one, qsStatus, QsfsEnum.DRQS.getQsfsDm(), "签收失败！管理状态异常", userInfo);
                    signToVO(tDxCustoms, param, true);
                    param.setCollectState(false);
                    param.setEditState(true);
                    customsLog.setInputStatus("2");
                    logList.add(customsLog);
                    continue;
                } else if (!"0".equals(one.getEntryDiscrepancy())) {
                    qsStatus = "0";
                    tDxCustoms = insertTdxCustoms(one, qsStatus, QsfsEnum.DRQS.getQsfsDm(), "签收失败！含录入不符项", userInfo);
                    signToVO(tDxCustoms, param, true);
                    param.setCollectState(false);
                    param.setEditState(true);
                    customsLog.setInputStatus("2");
                    logList.add(customsLog);
                    continue;
                }
            } else {
                // 录入数据
                if ("2".equals(one.getCollectUploadStatus())) {
                    // 上传税局成功

                    if (!"1".equals(one.getAuditStatus()) && "0".equals(one.getApplyCheck())) {
                        qsStatus = "0";
                        tDxCustoms = insertTdxCustoms(one, qsStatus, QsfsEnum.DRQS.getQsfsDm(),
                            "签收失败！稽核状态不相符,稽核状态为：" + AuditStatusEnum.getVal(one.getAuditStatus()), userInfo);
                        signToVO(tDxCustoms, param, true);
                        param.setCollectState(false);
                        param.setEditState(true);
                        customsLog.setInputStatus("2");
                        logList.add(customsLog);
                        continue;
                    } else if ("1".equals(one.getApplyCheck()) && "1".equals(one.getCheckStatus())) {
                        qsStatus = "0";
                        tDxCustoms =
                            insertTdxCustoms(one, qsStatus, QsfsEnum.DRQS.getQsfsDm(), "签收失败！核查结果为不允许抵扣/退税", userInfo);
                        signToVO(tDxCustoms, param, true);
                        param.setCollectState(false);
                        param.setEditState(true);
                        customsLog.setInputStatus("2");
                        logList.add(customsLog);
                        continue;
                    }
                } else {// 还未成功上传税局
                    qsStatus = "0";
                    tDxCustoms =
                        insertTdxCustoms(one, qsStatus, QsfsEnum.DRQS.getQsfsDm(), "签收失败！该录入缴款书还未上传成功", userInfo);
                    signToVO(tDxCustoms, param, true);
                    param.setCollectState(false);
                    param.setEditState(true);
                    customsLog.setInputStatus("2");
                    logList.add(customsLog);
                    continue;
                }
            }
            sign(one, userInfo, QsfsEnum.DRQS.getQsfsDm());
            tDxCustoms = insertTdxCustoms(one, qsStatus, QsfsEnum.DRQS.getQsfsDm(), "签收成功！", userInfo);
            this.baseMapper.updateById(one);
            signToVO(tDxCustoms, param, false);
            param.setCollectState(false);
            customsLog.setInputStatus("1");
            logList.add(customsLog);
        }

        if (logList.size() > 0) {
            logService.toCustomsLog(logList);
        }

        ResultData resultData = new ResultData<>();
        JSONObject tabulateMenu = tabulateRedisService.getTabulateMenu(company, menuId);
        resultData.putTabulateMenu(tabulateMenu);

        return resultData.setDataList(returnList).toJsonBase();
    }

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

    @Override
    public String querySign(Page page, TdxCustomsRecordDTO entity, UserInfo userInfo) throws Exception {

        DynamicContextHolder.push(userInfo.getDbName() + DbConstant.BUSINESS_READ);
        entity.setUserAccount(userInfo.getId());
        entity.setParam(page);
        List<Business> businessList = userInfo.getBusiness();
        if (StringUtils.isEmpty(entity.getGfTaxNo())) {
            entity.setBuyTaxNoFromUser(userInfo);
        }

        ResultData<Object> resultData = new ResultData<>();
        JSONObject tabulateMenu = tabulateRedisService.getTabulateMenu(userInfo.getCompany(), entity.getMenuId());
        resultData.putTabulateMenu(tabulateMenu);

        if (entity.getGfTaxNo() == null && CollectionUtils.isEmpty(entity.getGfTaxNoList())) {
            return resultData.getPageData(null).toJsonBase();
        }

        // 合计信息,仅第一页时需要统计，减少数据库压力
        Map mapTj = null;
        if (entity.getCurr() == 1) {
            mapTj = this.baseMapper.querySignHj(entity);
        }

        Page<Map<String, Object>> result = this.baseMapper.querySign(page, entity);
        if (ResultData.isEmpty(result)) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            for (int i = 0; i < page.getRecords().size(); i++) {
                Map<String, Object> map = result.getRecords().get(i);
                map.put("index",
                    String.valueOf((((page.getCurrent() == 0 ? 1 : page.getCurrent()) - 1) * page.getSize()) + i + 1));
                if ("1".equals(map.get("qsStatus"))) {
                    map.put("delState", false);
                } else {
                    map.put("delState", true);
                    map.put("editState", true);
                }
                //字典转换
                String qsStatus = (String) map.get("qsStatus");
                map.put("qsStatus", dictdetaServcice.queryDictName(DictConstant.QS_RESULTS,qsStatus));

                String auditStatus = (String)map.get("auditStatus");
                map.put("auditStatus",dictdetaServcice.queryDictName(DictConstant.AUDIT_STATUS,auditStatus));

                String applyCheck = (String) map.get("applyCheck");
                map.put("applyCheck", dictdetaServcice.queryDictName(DictConstant.APPLY_CHECK,applyCheck));

                String checkStatus = (String) map.get("checkStatus");
                map.put("checkStatus", dictdetaServcice.queryDictName(DictConstant.CHECK_STATUS,checkStatus));

                String dataSources =(String) map.get("dataSources");
                map.put("dataSources",dictdetaServcice.queryDictName(DictConstant.JKSCJFS,dataSources));

                String glzt = (String) map.get("glzt");
                map.put("glzt",StringUtils.isBlank(glzt)?"正常":dictdetaServcice.queryDictName(DictConstant.GLZT,glzt));

                String entryDiscrepancy =(String) map.get("entryDiscrepancy");
                map.put("entryDiscrepancy",dictdetaServcice.queryDictName(DictConstant.ENTRY_DISCREPANCY,entryDiscrepancy));

                String qsType =(String) map.get("qsType");
                map.put("qsType",dictdetaServcice.queryDictName(DictConstant.QS_TYPE,qsType));

//                map.put("qsStatus", QsStatusEnum.getVal(ObjectUtil.fixNull(map.get("qsStatus"))));
//                map.put("qsType", QsTypeEnum.getVal(ObjectUtil.fixNull(map.get("qsType"))));
//                map.put("dataSources", DataSourceEnum.getVal(ObjectUtil.fixNull(map.get("dataSources"))));
//                map.put("glzt", GlztEnum.getVal(ObjectUtil.fixNull(map.get("glzt"))));
//                map.put("auditStatus", AuditStatusEnum.getVal(ObjectUtil.fixNull(map.get("auditStatus"))));
//                map.put("applyCheck", ApplyCheckEnum.getVal(ObjectUtil.fixNull(map.get("applyCheck"))));
//                map.put("checkStatus", CheckStatusEnum.getVal(ObjectUtil.fixNull(map.get("checkStatus"))));

                if(cn.hutool.core.util.ObjectUtil.isNotEmpty(map.get("taxAmount"))){
                    map.put("taxAmount",
                            AmountFormatUtil.fmtMicrometer(new BigDecimal(ObjectUtil.fixNull(map.get("taxAmount")))
                                    .setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString()));
                }


                if (map.get("fillInDate") != null) {
                    map.put("fillInDate", map.get("fillInDate"));
                }
                if (map.get("qsDate") != null) {
                    map.put("qsDate", map.get("qsDate"));
                }
                String notes = map.get("notes").toString();
                if (notes.contains("需数据采集")) {
                    map.put("collectState", true);
                } else {
                    map.put("collectState", false);
                }
            }
        }
        return resultData.getTjData(mapTj).getPageData(result).toJsonBase();
    }

    @Override
    public String cancelSign(List<String> idList, UserInfo userInfo) {
        DynamicContextHolder
            .push(StringUtils.defaultString(userInfo.getDbName(), "business") + DbConstant.BUSINESS_READ);
        int i = 0, fail = 0;
        if (idList != null && idList.size() > 0) {
            List<CustomsLog> logList = new ArrayList<>();
            for (String id : idList) {
                TdxCustoms tDxCustoms = customsService.getById(id);
                CustomsLog customsLog = new CustomsLog();
                customsLog.setCreateDate(new Date());
                customsLog.setType("4");
                customsLog.setInputName(userInfo.getLoginname());
                if (tDxCustoms != null) {
                    customsLog.setCustomsCode(tDxCustoms.getCustomsCode());
                    customsLog.setQsType(tDxCustoms.getQsType());
                    cancelSignCustomScan(tDxCustoms);
                    customsService.updateById(tDxCustoms);
                    int re = this.baseMapper.updateRecordSign(tDxCustoms.getCustomsCode());
                    if (re > 0) {

                        i++;
                        customsLog.setInputStatus("5");
                        logList.add(customsLog);
                    } else {
                        fail++;
                        customsLog.setInputStatus("6");
                        logList.add(customsLog);
                    }
                } else {
                    customsLog.setInputStatus("6");
                    logList.add(customsLog);
                    fail++;
                }
            }

            if (logList.size() > 0) {
                logService.toCustomsLog(logList);
            }
        }

        return "取消签收成功" + i + "条, 失败" + fail + "条";
    }

    @Override
    public String changeBusiness(TdxCustomsRecordDTO entity, UserInfo userInfo) {
        DynamicContextHolder
            .push(StringUtils.defaultString(userInfo.getDbName(), "business") + DbConstant.BUSINESS_READ);
        List<String> idList = entity.getIds();
        if (idList != null && idList.size() > 0) {
            for (String id : idList) {
                String businessName = "";
                TdxCustoms one = customsService.getById(id);
                if (one != null) {
                    one.setDeptId(entity.getBusinessCode());
                    List<Business> businessList = userInfo.getBusiness();
                    for (Business business : businessList) {
                        if (business.getBusinessCode().equals(entity.getBusinessCode())) {
                            businessName = business.getBusinessName();
                        }
                    }
                    one.setDeptName(businessName);
                    customsService.updateById(one);
                }

                LambdaQueryWrapper<TdxCustomsRecord> wrapper = new LambdaQueryWrapper<>();
                wrapper.eq(TdxCustomsRecord::getCustomsCode, one.getCustomsCode());
                TdxCustomsRecord record = this.baseMapper.selectOne(wrapper);

                record.setDeptId(entity.getBusinessCode());
                record.setDeptName(businessName);
                this.baseMapper.updateById(record);
            }
        }
        return "修改成功";
    }

    @Override
    public String changeRemark(TdxCustomsRecordDTO entity, UserInfo userInfo) {
        DynamicContextHolder
            .push(StringUtils.defaultString(userInfo.getDbName(), "business") + DbConstant.BUSINESS_READ);
        List<String> idList = entity.getIds();
        if (idList != null && idList.size() > 0) {
            for (String id : idList) {
                TdxCustoms one = customsService.getById(id);
                if (one != null) {
                    one.setRemark(entity.getRemark());
                    customsService.updateById(one);
                }

            }
        }
        return "修改成功";
    }

    @Override
    public String scanBatchSign(List<String> idList, UserInfo userInfo) {
        DynamicContextHolder
            .push(StringUtils.defaultString(userInfo.getDbName(), "business") + DbConstant.BUSINESS_READ);
        int i = 0, fail = 0;
        List<String> gfshAll = UserInfoUtil.getGfshAll(userInfo.getOrg());
        if (idList != null && idList.size() > 0) {
            List<CustomsLog> logList = new ArrayList<>();
            for (String id : idList) {
                TdxCustoms one = customsService.getById(id);
                LambdaQueryWrapper<TdxCustomsRecord> wrapper = new LambdaQueryWrapper<>();
                wrapper.eq(TdxCustomsRecord::getCustomsCode, one.getCustomsCode());
                TdxCustomsRecord record = this.baseMapper.selectOne(wrapper);

                CustomsLog customsLog = new CustomsLog();
                customsLog.setCustomsCode(one.getCustomsCode());
                customsLog.setQsType(one.getQsType());
                customsLog.setCreateDate(new Date());
                customsLog.setType("3");
                customsLog.setInputName(userInfo.getLoginname());

                if (record != null) {

                    if (gfshAll == null || gfshAll.size() == 0 || !gfshAll.contains(record.getGfTaxNo())) {
                        one.setNotes("签收失败！无税号权限");
                        one.setQsDate(DateUtils.getSqlDateLong());
                        one.setUpdateDate(DateUtils.getSqlDateLong());
                        customsService.updateById(one);
                        fail++;
                        customsLog.setInputStatus("2");
                        logList.add(customsLog);
                        continue;
                    }

                    if ("0".equals(record.getDataSources())) {
                        // 采集数据

                        if (!"0".equals(record.getGlzt())) {
                            one.setNotes("签收失败！管理状态异常");
                            one.setQsDate(DateUtils.getSqlDateLong());
                            one.setUpdateDate(DateUtils.getSqlDateLong());
                            customsService.updateById(one);
                            fail++;
                            customsLog.setInputStatus("2");
                            logList.add(customsLog);
                            continue;
                        } else if (!"0".equals(record.getEntryDiscrepancy())) {
                            one.setNotes("签收失败！含录入不符项");
                            one.setQsDate(DateUtils.getSqlDateLong());
                            one.setUpdateDate(DateUtils.getSqlDateLong());
                            customsService.updateById(one);
                            fail++;
                            customsLog.setInputStatus("2");
                            logList.add(customsLog);
                            continue;
                        }
                    } else {// 录入数据
                        if ("2".equals(record.getCollectUploadStatus())) {

                            if (!"1".equals(record.getAuditStatus()) && "0".equals(record.getApplyCheck())) {
                                one.setNotes("签收失败！稽核状态不相符稽核状态为：" + AuditStatusEnum.getVal(record.getAuditStatus()));
                                one.setQsDate(DateUtils.getSqlDateLong());
                                one.setUpdateDate(DateUtils.getSqlDateLong());
                                customsService.updateById(one);
                                fail++;
                                customsLog.setInputStatus("2");
                                logList.add(customsLog);
                                continue;
                            } else if ("1".equals(record.getApplyCheck()) && "1".equals(record.getCheckStatus())) {
                                one.setNotes("签收失败！核查结果为不允许抵扣/退税");
                                one.setQsDate(DateUtils.getSqlDateLong());
                                one.setUpdateDate(DateUtils.getSqlDateLong());
                                customsService.updateById(one);
                                fail++;
                                customsLog.setInputStatus("2");
                                logList.add(customsLog);
                                continue;
                            }
                        } else {
                            one.setNotes("签收失败！该录入缴款书还未上传成功");
                            one.setQsDate(DateUtils.getSqlDateLong());
                            one.setUpdateDate(DateUtils.getSqlDateLong());
                            customsService.updateById(one);
                            fail++;
                            customsLog.setInputStatus("2");
                            logList.add(customsLog);
                            continue;
                        }
                    }

                    record.setDeptId(one.getDeptId());
                    record.setDeptName(one.getDeptName());
                    TdxCustoms tDxCustoms = getTdxCustoms(record, userInfo);
                    tDxCustoms.setCreateDate(one.getCreateDate());
                    tDxCustoms.setId(one.getId());
                    tDxCustoms.setNotes("签收成功！");
                    tDxCustoms.setQsStatus("1");
                    tDxCustoms.setQsDate(DateUtils.getSqlDateLong());
                    tDxCustoms.setUpdateDate(DateUtils.getSqlDateLong());
                    customsService.updateById(tDxCustoms);

                    sign(record, userInfo, one.getQsType());
                    this.baseMapper.updateById(record);
                    i++;
                    customsLog.setInputStatus("1");
                    logList.add(customsLog);
                } else {
                    one.setNotes("签收失败！无此票据，需数据采集");
                    one.setQsDate(DateUtils.getSqlDateLong());
                    one.setUpdateDate(DateUtils.getSqlDateLong());
                    customsService.updateById(one);
                    fail++;
                }

            }

            if (logList.size() > 0) {
                logService.toCustomsLog(logList);
            }
        }

        return "签收成功" + i + "条,签收失败" + fail + "条";
    }

    private void cancelSignCustomScan(TdxCustoms record) {
        record.setQsStatus(QSignStatusEnum.A.getKey());
        record.setNotes("取消签收！");
    }

    private TdxCustoms insertTdxCustoms(TdxCustomsRecord one, String qsStatus, String qsType, UserInfo userInfo) {
        LambdaQueryWrapper<TdxCustoms> tdxCustomsWrapper = new LambdaQueryWrapper<>();
        tdxCustomsWrapper.eq(TdxCustoms::getCustomsCode, one.getCustomsCode());
        TdxCustoms tDxCustoms = customsService.getOne(tdxCustomsWrapper);
        if (tDxCustoms == null) {
            tDxCustoms = getTdxCustoms(one, userInfo);
            sign(tDxCustoms, qsType, qsStatus);
            customsService.save(tDxCustoms);
        } else {
            sign(tDxCustoms, qsType, qsStatus);
            customsService.updateById(tDxCustoms);
        }
        return tDxCustoms;
    }

    private TdxCustoms updateTdxCustoms(TdxCustomsRecord one, String qsStatus, String qsType, String notes,
        UserInfo userInfo, TdxCustoms customs) {
        DynamicContextHolder.push(StringUtils.defaultString(ObjectUtil.fixNull(userInfo.getDbName()), "business")
            + DbConstant.BUSINESS_WRITE);
        Long id = customs.getId();
        if ("1".equals(qsStatus)) {
            customs = getTdxCustoms(one, userInfo);
        }
        customs.setUpdateDate(new Date());
        customs.setId(id);
        sign(customs, qsType, qsStatus);
        customs.setNotes(notes);
        customsService.updateById(customs);
        return customs;
    }

    private TdxCustoms insertTdxCustoms(TdxCustomsRecord one, String qsStatus, String qsType, String notes,
        UserInfo userInfo) {
        DynamicContextHolder.push(StringUtils.defaultString(ObjectUtil.fixNull(userInfo.getDbName()), "business")
            + DbConstant.BUSINESS_WRITE);
        LambdaQueryWrapper<TdxCustoms> tdxCustomsWrapper = new LambdaQueryWrapper<>();
        tdxCustomsWrapper.eq(TdxCustoms::getCustomsCode, one.getCustomsCode());
        TdxCustoms tDxCustoms = customsService.getOne(tdxCustomsWrapper);
        if (tDxCustoms == null) {
            tDxCustoms = getTdxCustoms(one, userInfo);
            tDxCustoms.setCreateDate(new Date());
            tDxCustoms.setNotes(notes);
            tDxCustoms.setScanId(UUID.randomUUID().toString());
            tDxCustoms.setInvoiceSerialNo(Long.valueOf(scanIdUtils.createSerialNum()));
            sign(tDxCustoms, qsType, qsStatus);
            customsService.save(tDxCustoms);
        } else {
            Long id = tDxCustoms.getId();
            tDxCustoms = getTdxCustoms(one, userInfo);
            tDxCustoms.setUpdateDate(new Date());
            tDxCustoms.setId(id);
            sign(tDxCustoms, qsType, qsStatus);
            tDxCustoms.setNotes(notes);
            customsService.updateById(tDxCustoms);
        }
        return tDxCustoms;
    }

    private void sign(TdxCustoms record, String qsType, String qsStatus) {
        record.setQsStatus(qsStatus);
        record.setQsDate(new Date());
        record.setQsType(qsType);
    }

    private void signFail(TdxCustomsRecord entity, UserInfo userInfo) {
        entity.setQsStatus("0");
        entity.setQsDate(new Date());
        entity.setQsUser(userInfo.getUsername());

    }

    private List<String> getTaxNoList(UserInfo userInfo) {
        List buyCompanyList = new ArrayList<>();
        for (Tax code : userInfo.getOrg()) {
            buyCompanyList.add(code.getTaxno());
        }
        return buyCompanyList;
    }

    private TdxCustoms getTdxCustoms(TdxCustomsRecord record, UserInfo userInfo) {
        TdxCustoms entity = new TdxCustoms();
        entity.setGfName(record.getGfName());
        entity.setGfTaxNo(record.getGfTaxNo());
        entity.setCustomsCode(record.getCustomsCode());
        entity.setPayerOneTaxno(record.getPayerOneTaxno());
        entity.setPayerOneName(record.getPayerOneName());
        entity.setPayerTwoTaxno(record.getPayerTwoTaxno());
        entity.setPayerTwoName(record.getPayerTwoName());
        entity.setFillInDate(record.getFillInDate());
        entity.setDataType(record.getDataType());
        entity.setTaxAmount(record.getTaxAmount());
        entity.setAuditStatus(record.getAuditStatus());
        entity.setApplyCheck(record.getApplyCheck());
        entity.setCheckStatus(record.getCheckStatus());
        entity.setEntryDiscrepancy(record.getEntryDiscrepancy());
        entity.setDeptId(record.getDeptId());
        entity.setDeptName(record.getDeptName());
        entity.setGlzt(record.getGlzt());
        entity.setXxly(record.getXxly());
        entity.setDataSources(record.getDataSources());
        entity.setUserName(userInfo.getUsername());
        entity.setCompany(userInfo.getCompany());
        entity.setUserAccount(userInfo.getId());
        return entity;
    }

    private void sign(TdxCustomsRecord record, UserInfo userInfo, String qsType) {
        record.setQsStatus("1");
        record.setQsDate(new Date());
        record.setQsUser(userInfo.getUsername());
        record.setQsType(qsType);
    }

    private void sign(TdxCustoms record, String qsType) {
        record.setQsStatus("1");
        record.setQsDate(new Date());
        record.setQsType(qsType);
    }

    private CustomsSignVO signToVO(TdxCustoms customs, CustomsSignVO customsSignVO, boolean delState) {

        customsSignVO.setNotes(customs.getNotes());
        customsSignVO.setQsStatus(QsStatusEnum.getVal(customs.getQsStatus()));
        customsSignVO.setGfName(customs.getGfName());
        customsSignVO
            .setDataSources(customs.getDataSources() == null ? "" : DataSourceEnum.getVal(customs.getDataSources()));
        customsSignVO.setGlzt(customs.getGlzt() == null ? "" : GlztEnum.getVal(customs.getGlzt()));
        customsSignVO
            .setAuditStatus(customs.getAuditStatus() == null ? "" : AuditStatusEnum.getVal(customs.getAuditStatus()));
        customsSignVO
            .setApplyCheck(customs.getApplyCheck() == null ? "" : ApplyCheckEnum.getVal(customs.getApplyCheck()));
        customsSignVO
            .setCheckStatus(customs.getCheckStatus() == null ? "" : CheckStatusEnum.getVal(customs.getCheckStatus()));
        customsSignVO.setEntryDiscrepancy(
            customs.getEntryDiscrepancy() == null ? "" : EntryDiscrepancyEnum.getVal(customs.getEntryDiscrepancy()));
        customsSignVO.setScanId(customs.getScanId());
        customsSignVO.setQsUser(customs.getUserName());
        customsSignVO.setQsDate(DateUtils.dateToStr(customs.getQsDate()));
        customsSignVO.setDeptName(customs.getDeptName());
        customsSignVO.setDelState(delState);
        customsSignVO.setId(customs.getId());
        return customsSignVO;
    }

    @Override
    public String editCustoms(TdxCustomsRecord entity, UserInfo userInfo) throws Exception {
        Map<String, Object> data = new HashMap();
        DynamicContextHolder.push(
            StringUtils.defaultString(ObjectUtil.fixNull(userInfo.getDbName()), "business") + DbConstant.BUSINESS_READ);
        List<String> gfshAll = UserInfoUtil.getGfshAll(userInfo.getOrg());
        if (entity.getId() != null) {
            String qsStatus = "1";
            LambdaQueryWrapper<TdxCustoms> customsLambdaQueryWrapper = new LambdaQueryWrapper<>();
            customsLambdaQueryWrapper.eq(TdxCustoms::getCustomsCode, entity.getCustomsCode());
            customsLambdaQueryWrapper.ne(TdxCustoms::getId, entity.getId());
            List<TdxCustoms> qsList = customsService.list(customsLambdaQueryWrapper);
            if (qsList != null && qsList.size() > 0) {
                data.put("code", "-1");
                data.put("msg", "已存在签收记录");
                return new ResultData().putData(data).toJsonBase();
            }

            if (!ObjectUtil.checkData(entity.getGfTaxNo(), entity.getCustomsCode(), entity.getFillInDate(),
                entity.getTaxAmount())) {
                data.put("code", "-1");
                data.put("msg", "数据不全");
                return new ResultData().putData(data).toJsonBase();
            }

            LambdaQueryWrapper<TdxCustomsRecord> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(TdxCustomsRecord::getCustomsCode, entity.getCustomsCode());
            TdxCustomsRecord one = this.baseMapper.selectOne(wrapper);
            LambdaQueryWrapper<TdxCustoms> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(TdxCustoms::getId, entity.getId());
            TdxCustoms customs = customsService.getOne(queryWrapper);
            customs.setCustomsCode(entity.getCustomsCode());
            customs.setGfTaxNo(entity.getGfTaxNo());
            customs.setGfName(getGfmcByGfsh(entity.getGfTaxNo(), userInfo.getOrg()));
            customs.setFillInDate(entity.getFillInDate());
            customs.setTaxAmount(entity.getTaxAmount());
            if (one == null) {
                customs.setNotes("签收失败！无此票据，需数据采集");
                customs.setQsStatus("0");
                qsStatus = "0";
                updateTdxCustoms(one, qsStatus, customs.getQsType(), "签收失败！无此票据，需数据采集", userInfo, customs);
                data.put("code", "0");
                data.put("msg", "修改完成");
                data.put("data", customs);
                data.put("collectState", false);
                data.put("editState", true);
                data.put("delState", true);
                return new ResultData().putData(data).toJsonBase();
            }
            one.setDeptName(customs.getDeptName());
            one.setDeptId(customs.getDeptId());
            Double oTaxAmount = Double.valueOf(one.getTaxAmount());
            Double pTaxAmount = Double.valueOf(entity.getTaxAmount());

            CustomsLog customsLog = new CustomsLog();
            customsLog.setCustomsCode(one.getCustomsCode());
            customsLog.setQsType("3");
            customsLog.setCreateDate(new Date());
            customsLog.setType("3");
            customsLog.setInputName(userInfo.getLoginname());
            if (gfshAll.size() == 0 || !gfshAll.contains(one.getGfTaxNo())) {
                qsStatus = "0";
                customs.setNotes("签收失败！无税号权限");
                customs.setQsStatus(qsStatus);
                updateTdxCustoms(one, qsStatus, customs.getQsType(), "签收失败！无税号权限", userInfo, customs);
                data.put("code", "0");
                data.put("msg", "修改完成");
                data.put("data", customs);
                data.put("collectState", false);
                data.put("editState", true);
                data.put("delState", true);
                return new ResultData().putData(data).toJsonBase();
            }

            if (!DateUtil.compare(one.getFillInDate(), entity.getFillInDate())) {
                qsStatus = "0";
                customs.setNotes("签收失败！填发日期与底账不一致");
                customs.setQsStatus(qsStatus);
                updateTdxCustoms(one, qsStatus, customs.getQsType(), "签收失败！填发日期与底账不一致", userInfo, customs);
                data.put("code", "0");
                data.put("msg", "修改完成");
                data.put("data", customs);
                data.put("collectState", false);
                data.put("editState", true);
                data.put("delState", true);
                return new ResultData().putData(data).toJsonBase();
            }

            if (!oTaxAmount.equals(pTaxAmount)) {
                qsStatus = "0";
                customs.setNotes("签收失败！税款金额与底账不一致");
                customs.setQsStatus(qsStatus);
                updateTdxCustoms(one, qsStatus, customs.getQsType(), "签收失败！税款金额与底账不一致", userInfo, customs);
                data.put("code", "0");
                data.put("msg", "修改完成");
                data.put("data", customs);
                data.put("collectState", false);
                data.put("editState", true);
                data.put("delState", true);
                return new ResultData().putData(data).toJsonBase();
            }

            if (!entity.getGfTaxNo().trim().equals(one.getGfTaxNo())) {
                qsStatus = "0";
                customs.setNotes("签收失败！缴款单位与底账不一致");
                customs.setQsStatus(qsStatus);
                updateTdxCustoms(one, qsStatus, customs.getQsType(), "签收失败！缴款单位与底账不一致", userInfo, customs);
                data.put("code", "0");
                data.put("msg", "修改完成");
                data.put("data", customs);
                data.put("collectState", false);
                data.put("editState", true);
                data.put("delState", true);
                return new ResultData().putData(data).toJsonBase();
            }

            // 采集数据
            if ("0".equals(one.getDataSources())) {

                if (!"0".equals(one.getGlzt())) {
                    qsStatus = "0";
                    customs.setNotes("签收失败！管理状态异常");
                    customs.setQsStatus(qsStatus);
                    updateTdxCustoms(one, qsStatus, customs.getQsType(), "签收失败！管理状态异常", userInfo, customs);
                    data.put("code", "0");
                    data.put("msg", "修改完成");
                    data.put("data", customs);
                    data.put("collectState", false);
                    data.put("editState", true);
                    data.put("delState", true);
                    return new ResultData().putData(data).toJsonBase();
                } else if (!"0".equals(one.getEntryDiscrepancy())) {
                    qsStatus = "0";
                    customs.setNotes("签收失败！含录入不符项");
                    customs.setQsStatus(qsStatus);
                    updateTdxCustoms(one, qsStatus, customs.getQsType(), "签收失败！含录入不符项", userInfo, customs);
                    data.put("code", "0");
                    data.put("msg", "修改完成");
                    data.put("data", customs);
                    data.put("collectState", false);
                    data.put("editState", true);
                    data.put("delState", true);
                    return new ResultData().putData(data).toJsonBase();
                }
            } else {
                // 录入数据
                if ("2".equals(one.getCollectUploadStatus())) {
                    // 上传税局成功

                    if (!"1".equals(one.getAuditStatus()) && "0".equals(one.getApplyCheck())) {
                        qsStatus = "0";
                        customs.setNotes("签收失败！稽核状态不相符,稽核状态为：" + AuditStatusEnum.getVal(one.getAuditStatus()));
                        customs.setQsStatus(qsStatus);
                        updateTdxCustoms(one, qsStatus, customs.getQsType(),
                            "签收失败！稽核状态不相符,稽核状态为：" + AuditStatusEnum.getVal(one.getAuditStatus()), userInfo, customs);
                        data.put("code", "0");
                        data.put("msg", "修改完成");
                        data.put("data", customs);
                        data.put("collectState", false);
                        data.put("editState", true);
                        data.put("delState", true);
                        return new ResultData().putData(data).toJsonBase();
                    } else if ("1".equals(one.getApplyCheck()) && "1".equals(one.getCheckStatus())) {
                        qsStatus = "0";
                        customs.setNotes("签收失败！核查结果为不允许抵扣/退税");
                        customs.setQsStatus(qsStatus);
                        updateTdxCustoms(one, qsStatus, customs.getQsType(), "签收失败！核查结果为不允许抵扣/退税", userInfo, customs);
                        data.put("code", "0");
                        data.put("msg", "修改完成");
                        data.put("data", customs);
                        data.put("collectState", false);
                        data.put("editState", true);
                        data.put("delState", true);
                        return new ResultData().putData(data).toJsonBase();
                    }
                } else {// 还未成功上传税局
                    qsStatus = "0";
                    customs.setNotes("签收失败！该录入缴款书还未上传成功");
                    customs.setQsStatus(qsStatus);
                    updateTdxCustoms(one, qsStatus, customs.getQsType(), "签收失败！该录入缴款书还未上传成功", userInfo, customs);
                    data.put("code", "0");
                    data.put("msg", "修改完成");
                    data.put("data", customs);
                    data.put("collectState", false);
                    data.put("editState", true);
                    data.put("delState", true);
                    return new ResultData().putData(data).toJsonBase();
                }
            }
            sign(one, userInfo, QsfsEnum.DRQS.getQsfsDm());
            updateTdxCustoms(one, qsStatus, customs.getQsType(), "签收成功！", userInfo, customs);
            customs.setNotes("签收成功");
            customs.setQsStatus(qsStatus);
            log.info("发票:{}签收状态:{},签收描述:{}",one.getCustomsCode(),customs.getQsStatus(),customs.getNotes());
            data.put("code", "0");
            data.put("msg", "修改完成");
            data.put("data", customs);
            data.put("collectState", false);
            data.put("editState", false);
            data.put("delState", false);
            this.baseMapper.updateById(one);
            return new ResultData().putData(data).toJsonBase();
        } else {
            data.put("code", "-1");
            data.put("msg", "id不能为空");
            data.put("collectState", false);
            data.put("editState", false);
            data.put("delState", false);
            return new ResultData().putData(data).toJsonBase();
        }
    }

    private String getGfmcByGfsh(String gfsh, List<Tax> orgList) {
        String gfmc = "";
        for (Tax org : orgList) {
            if (gfsh.equals(org.getTaxno())) {
                gfmc = org.getTaxname();
                if (StringHelper.isBlank(gfmc)) {
                    gfmc = "";
                }
                break;
            }
        }
        return gfmc;
    }

    @Override
    public String scanSign(Map<String, String> pramsMap, UserInfo userInfo) throws Exception {
        DynamicContextHolder.push(
            StringUtils.defaultString(ObjectUtil.fixNull(userInfo.getDbName()), "business") + DbConstant.BUSINESS_READ);
        String businessCode = pramsMap.get("businessCode");
        String company = pramsMap.get("company");
        String menuId = pramsMap.get("menuId");
        String pch = pramsMap.get("pch");
        String businessName = "";
        List<Business> businessList = new ArrayList<>();
        if (org.apache.commons.lang3.StringUtils.isNoneBlank(businessCode) && !"99".equals(businessCode)) {
            businessList = userInfo.getBusiness();
            for (Business business : businessList) {
                if (business.getBusinessCode().equals(businessCode)) {
                    businessName = business.getBusinessName();
                }
            }
        }
        List<String> gfshAll = UserInfoUtil.getGfshAll(userInfo.getOrg());

        List<TDxScanCustomsLog> scanCustomsLogs = scanLogDao.getScanLog(pch);
        List<CustomsSignVO> returnList = new ArrayList<>();
        List<CustomsLog> logList = new ArrayList<>();
        if (scanCustomsLogs != null && scanCustomsLogs.size() > 0) {

            for (int i = 0; i < scanCustomsLogs.size(); i++) {

                TDxScanCustomsLog scanCustoms = scanCustomsLogs.get(i);
                CustomsSignVO param = new CustomsSignVO();
                param.setIndex(String.valueOf(i + 1));
                param.setCustomsCode(scanCustoms.getCustomsCode());
                param.setFillInDate(DateUtils.dateToStr(scanCustoms.getFillInDate()));
                param.setTaxAmount(scanCustoms.getAmount());
                returnList.add(param);
                String qsStatus = "1";

                LambdaQueryWrapper<TdxCustoms> customsLambdaQueryWrapper = new LambdaQueryWrapper<>();
                customsLambdaQueryWrapper.eq(TdxCustoms::getCustomsCode, scanCustoms.getCustomsCode());
                TdxCustoms tDxCustoms = customsService.getOne(customsLambdaQueryWrapper);
                if (tDxCustoms != null && "1".equals(tDxCustoms.getQsStatus())) {
                    signToVO(tDxCustoms, param, false);
                    param.setNotes("该票据已签收成功！请勿重复操作");
                    param.setCollectState(false);
                    continue;
                }

                LambdaQueryWrapper<TdxCustomsRecord> wrapper = new LambdaQueryWrapper<>();
                wrapper.eq(TdxCustomsRecord::getCustomsCode, param.getCustomsCode());
                TdxCustomsRecord one = this.baseMapper.selectOne(wrapper);

                if (one == null) {
                    TdxCustoms customs = new TdxCustoms();
                    customs.setNotes("签收失败！无此票据，需数据采集");
                    customs.setQsStatus("0");
                    customs.setCustomsCode(param.getCustomsCode());
                    customs.setGfTaxNo(param.getGfTaxNo());
                    customs.setCreateDate(DateUtils.getSqlDateLong());
                    customs.setFillInDate(DateUtils.strToDate(param.getFillInDate()));
                    customs.setTaxAmount(param.getTaxAmount());
                    customs.setDeptId(businessCode);
                    customs.setDeptName(businessName);
                    customs.setUserAccount(userInfo.getId());
                    customs.setUserName(userInfo.getUsername());
                    customs.setScanId(UUID.randomUUID().toString());
                    customs.setInvoiceSerialNo(Long.valueOf(scanIdUtils.createSerialNum()));
                    customs.setQsDate(DateUtils.getSqlDateLong());
                    customs.setQsType(QsfsEnum.DRQS.getQsfsDm());
                    if (tDxCustoms == null) {

                        DynamicContextHolder
                            .push(StringUtils.defaultString(ObjectUtil.fixNull(userInfo.getDbName()), "business")
                                + DbConstant.BUSINESS_WRITE);
                        customsService.save(customs);
                    }
                    signToVO(customs, param, true);
                    param.setCollectState(true);
                    continue;
                }
                one.setDeptName(businessName);
                one.setDeptId(businessCode);
                Double oTaxAmount = Double.valueOf(one.getTaxAmount());
                Double pTaxAmount = Double.valueOf(param.getTaxAmount());

                CustomsLog customsLog = new CustomsLog();
                customsLog.setCustomsCode(one.getCustomsCode());
                customsLog.setQsType("3");
                customsLog.setCreateDate(new Date());
                customsLog.setType("3");
                customsLog.setInputName(userInfo.getLoginname());
                if (gfshAll.size() == 0 || !gfshAll.contains(one.getGfTaxNo())) {
                    qsStatus = "0";
                    tDxCustoms = insertTdxCustoms(one, qsStatus, QsfsEnum.DRQS.getQsfsDm(), "签收失败！无税号权限", userInfo);
                    signToVO(tDxCustoms, param, true);
                    param.setCollectState(false);
                    customsLog.setInputStatus("2");
                    logList.add(customsLog);
                    continue;
                }

                if (!DateUtil.compare(one.getFillInDate(), DateUtil.strToDate(param.getFillInDate()))) {
                    qsStatus = "0";
                    tDxCustoms =
                        insertTdxCustoms(one, qsStatus, QsfsEnum.DRQS.getQsfsDm(), "签收失败！填发日期与底账不一致", userInfo);
                    signToVO(tDxCustoms, param, true);
                    param.setCollectState(false);
                    customsLog.setInputStatus("2");
                    logList.add(customsLog);
                    continue;
                }

                if (!oTaxAmount.equals(pTaxAmount)) {
                    qsStatus = "0";
                    tDxCustoms =
                        insertTdxCustoms(one, qsStatus, QsfsEnum.DRQS.getQsfsDm(), "签收失败！税款金额与底账不一致", userInfo);
                    signToVO(tDxCustoms, param, true);
                    param.setCollectState(false);
                    customsLog.setInputStatus("2");
                    logList.add(customsLog);
                    continue;
                }

                // 采集数据
                if ("0".equals(one.getDataSources())) {

                    if (!"0".equals(one.getGlzt())) {
                        qsStatus = "0";
                        tDxCustoms =
                            insertTdxCustoms(one, qsStatus, QsfsEnum.DRQS.getQsfsDm(), "签收失败！管理状态异常", userInfo);
                        signToVO(tDxCustoms, param, true);
                        param.setCollectState(false);
                        customsLog.setInputStatus("2");
                        logList.add(customsLog);
                        continue;
                    } else if (!"0".equals(one.getEntryDiscrepancy())) {
                        qsStatus = "0";
                        tDxCustoms =
                            insertTdxCustoms(one, qsStatus, QsfsEnum.DRQS.getQsfsDm(), "签收失败！含录入不符项", userInfo);
                        signToVO(tDxCustoms, param, true);
                        param.setCollectState(false);
                        customsLog.setInputStatus("2");
                        logList.add(customsLog);
                        continue;
                    }
                } else {
                    // 录入数据
                    if ("2".equals(one.getCollectUploadStatus())) {
                        // 上传税局成功

                        if (!"1".equals(one.getAuditStatus()) && "0".equals(one.getApplyCheck())) {
                            qsStatus = "0";
                            tDxCustoms = insertTdxCustoms(one, qsStatus, QsfsEnum.DRQS.getQsfsDm(),
                                "签收失败！稽核状态不相符,稽核状态为：" + AuditStatusEnum.getVal(one.getAuditStatus()), userInfo);
                            signToVO(tDxCustoms, param, true);
                            param.setCollectState(false);
                            customsLog.setInputStatus("2");
                            logList.add(customsLog);
                            continue;
                        } else if ("1".equals(one.getApplyCheck()) && "1".equals(one.getCheckStatus())) {
                            qsStatus = "0";
                            tDxCustoms = insertTdxCustoms(one, qsStatus, QsfsEnum.DRQS.getQsfsDm(),
                                "签收失败！核查结果为不允许抵扣/退税", userInfo);
                            signToVO(tDxCustoms, param, true);
                            param.setCollectState(false);
                            customsLog.setInputStatus("2");
                            logList.add(customsLog);
                            continue;
                        }
                    } else {// 还未成功上传税局
                        qsStatus = "0";
                        tDxCustoms =
                            insertTdxCustoms(one, qsStatus, QsfsEnum.DRQS.getQsfsDm(), "签收失败！该录入缴款书还未上传成功", userInfo);
                        signToVO(tDxCustoms, param, true);
                        param.setCollectState(false);
                        customsLog.setInputStatus("2");
                        logList.add(customsLog);
                        continue;
                    }
                }
                sign(one, userInfo, QsfsEnum.DRQS.getQsfsDm());
                tDxCustoms = insertTdxCustoms(one, qsStatus, QsfsEnum.DRQS.getQsfsDm(), "签收成功！", userInfo);
                this.baseMapper.updateById(one);
                signToVO(tDxCustoms, param, false);
                param.setCollectState(false);
                customsLog.setInputStatus("1");
                logList.add(customsLog);
            }

        }
        if (logList.size() > 0) {
            logService.toCustomsLog(logList);
        }

        ResultData resultData = new ResultData<>();
        JSONObject tabulateMenu = tabulateRedisService.getTabulateMenu(company, menuId);
        resultData.putTabulateMenu(tabulateMenu);

        return resultData.setDataList(returnList).toJsonBase();
    }
}
