package com.dxhy.jxpt.baseService.cpyAuthInvoice.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.dxhy.api.model.config.UserInfo;
import com.dxhy.api.model.config.sys.SysEnterpriseConfigEntity;
import com.dxhy.api.model.cpy.cpyInvoice.TDxRecordInvoiceCpyVo;
import com.dxhy.api.model.cpy.pageImport.CpyImportInvioceReq;
import com.dxhy.api.model.db.TdxInvoiceCpyGxEntity;
import com.dxhy.api.model.db.TdxRecordInvoiceDetailEntity;
import com.dxhy.api.model.db.TdxRecordInvoiceEntity;
import com.dxhy.api.model.db.TdxSpbmCpyInvoiceEntity;
import com.dxhy.common.constant.ConfigureConstant;
import com.dxhy.common.constant.DictConstant;
import com.dxhy.common.service.DictdetaServcice;
import com.dxhy.common.service.TabulateRedisService;
import com.dxhy.common.service.impl.MpBaseServiceImpl;
import com.dxhy.common.util.AmountFormatUtil;
import com.dxhy.common.util.MathUtil;
import com.dxhy.common.utils.CommonUtil;
import com.dxhy.common.utils.DateUtils;
import com.dxhy.common.utils.R;
import com.dxhy.jxpt.baseService.config.dao.SysEnterpriseConfigDao;
import com.dxhy.jxpt.baseService.cpyAuthInvoice.dao.CpyRecordInvoiceDao;
import com.dxhy.jxpt.baseService.cpyAuthInvoice.service.CpyAuthInvoiceService;
import com.dxhy.jxpt.baseService.dao.TDxRecordInvoiceDetailDao;
import com.dxhy.jxpt.baseService.dao.TdxInvoiceCpyGxDao;
import com.dxhy.jxpt.baseService.dao.TdxRecordInvoiceDao;
import com.dxhy.jxpt.baseService.dao.TdxSpbmCpyInvoiceDao;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.text.DecimalFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Description 成品油发票勾选业务
 * @Author wangruwei
 * @Date 2024/7/12 10:10
 **/
@Service("cpyAuthInvoiceService")
@Slf4j
public class CpyAuthInvoiceServiceImpl extends MpBaseServiceImpl<CpyRecordInvoiceDao, TdxRecordInvoiceEntity> implements CpyAuthInvoiceService {

    @Resource
    private TdxSpbmCpyInvoiceDao tdxSpbmCpyInvoiceDao;

    @Resource
    private TdxInvoiceCpyGxDao tdxInvoiceCpyGxDao;
    @Resource
    private CpyRecordInvoiceDao cpyRecordInvoiceDao;

    @Resource
    private TdxRecordInvoiceDao tdxRecordInvoiceDao;

    @Resource
    private SysEnterpriseConfigDao sysEnterpriseConfigDao;

    @Resource
    private TDxRecordInvoiceDetailDao tDxRecordInvoiceDetailDao;

    @Resource
    private DictdetaServcice dictdetaServcice;

    @Resource
    private TabulateRedisService tabulateRedisService;


    /**
     * @Description 成品油发票勾选-页面查询接口
     * @param pramsMap
     * @Return java.lang.Object
     * @Author wangruwei
     * @Date 2024/7/12 10:42
     **/
    @Override
    public Object selectAuthPageList(Map<String, Object> pramsMap, int curr, int size) {
        JSONObject json = new JSONObject();
        try {
            String company = (String)pramsMap.get("company");
            String menuId = (String)pramsMap.get("menuId");
            json = tabulateRedisService.getTabulateMenu(company, menuId);
            // 合计信息,仅第一页时需要统计，减少数据库压力
            if (curr == 1) {

                String hjsl = "0";
                String hjje = "0.00";
                String hjse = "0.00";
                List<TDxRecordInvoiceCpyVo> hjList = super.baseMapper.selectAuthPageListHj(pramsMap);
                TDxRecordInvoiceCpyVo hjxx = hjList.get(0);
                hjsl = hjxx.getHjsl();
                if (!"0".equals(hjsl)) {
                    hjje = AmountFormatUtil.fmtMicrometer(MathUtil.round(hjxx.getHjje()));
                    hjse = AmountFormatUtil.fmtMicrometer(MathUtil.round(hjxx.getHjse()));
                }
                json.put("hjsl", hjsl);
                json.put("hjje", hjje);
                json.put("hjse", hjse);
            }

            PageHelper.startPage(curr, size);
            List<TDxRecordInvoiceCpyVo> pageList = super.baseMapper.selectAuthPageList(pramsMap);
            PageInfo<TDxRecordInvoiceCpyVo> pageInfo = new PageInfo<>(pageList);
            List<TDxRecordInvoiceCpyVo> resultList = pageInfo.getList();
            // 用于页面返回list对象
            if (resultList.size() > 0) {
                int start = (int)pageInfo.getStartRow();
                for (int i = 0; i < resultList.size(); i++) {
                    resultList.get(i).setXh(String.valueOf(i + start));

                    pageList.get(i)
                            .setSelect(true);
                    //设置是否可勾选
                    String notAllowCheck = getCheckedStatus(resultList.get(i));
                    if(StringUtils.isNotBlank(notAllowCheck)){
                        pageList.get(i)
                                .setSelect(false);
                        pageList.get(i)
                                .setNotAllowCheckStr(notAllowCheck);
                    }

                    if(ObjectUtil.isNotEmpty(resultList.get(i).getInvoiceAmount())){
                        resultList.get(i).setInvoiceAmountStr(
                                AmountFormatUtil.fmtMicrometer(MathUtil.round(resultList.get(i).getInvoiceAmount().toString()) ));
                    }
                    if(ObjectUtil.isNotEmpty(resultList.get(i).getTaxAmount())){
                        resultList.get(i)
                                .setTaxAmountStr(AmountFormatUtil.fmtMicrometer(MathUtil.round(resultList.get(i).getTaxAmount().toString())));
                    }
                    //发票状态
                    resultList.get(i)
                            .setInvoiceStatus(dictdetaServcice.queryDictName(DictConstant.INVOICE_STATUS, resultList.get(i).getInvoiceStatus()));
                    //发票风险等级
                    String glzt = resultList.get(i).getGlzt();
                    resultList.get(i).setGlzt(dictdetaServcice.queryDictName(DictConstant.GLZT, glzt));
                    //红字锁定标识
                    resultList.get(i).setLqHzsdbs(dictdetaServcice.queryDictName(DictConstant.HZSDZT, resultList.get(i).getLqHzsdbs()));
                    //成品油异常标识
                    resultList.get(i).setLqCpyycbs(dictdetaServcice.queryDictName(DictConstant.CPY_YCBS, resultList.get(i).getLqCpyycbs()));
                    //消费税用途
                    resultList.get(i).setLqXfsyt(dictdetaServcice.queryDictName(DictConstant.XFSYT, resultList.get(i).getLqXfsyt()));
                    //用途处理状态
                    resultList.get(i).setGxclzt(dictdetaServcice.queryDictName(DictConstant.CPY_GXCLZT, resultList.get(i).getGxclzt()));

                }
            }
            // 设置记录总数
            json.put("total", pageInfo.getTotal());
            json.put("datalist", resultList);
            if("0".equals(pramsMap.get("tabNum"))||"3".equals(pramsMap.get("tabNum"))){
                json.put("selection", true);
            }
            json.put("tabNum", pramsMap.get("tabNum"));
        } catch (Exception e) {
            // 统一设置操作异常标识
            json = super.errorResult(e);
        }
        return super.responseResult(json);
    }
    /**
     * @Description 成品油状态-页面状态统计接口
     * @Return java.lang.Object
     * @Author wangruwei
     * @Date 2024/7/12 10:42
     *
     * @param params*/
    @Override
    public Object selectCountStatusPage(Map<String, Object> params) {
        List<TdxInvoiceCpyGxEntity> invoiceCpyGxList = cpyRecordInvoiceDao.selectCountStatusPage(params);
        //筛选出进行中 状态是1,2，失败的数据 状态是3
        int ingCount = invoiceCpyGxList.stream().filter(e -> "1".equals(e.getGxclzt()) || "2".equals(e.getGxclzt())).collect(Collectors.toList()).size();
        int failCount = invoiceCpyGxList.stream().filter(e -> "3".equals(e.getGxclzt())).collect(Collectors.toList()).size();
        JSONObject json = new JSONObject();
        json.put("ingCount",ingCount>999?"999+":ingCount);
        json.put("failCount",failCount>999?"999+":failCount);
        return super.responseResult(json);
    }


    /**
     * @Description 成品油状态-选中发票提示勾选总吨数
     * @param
     * @Return java.lang.Object
     * @Author wangruwei
     * @Date 2024/7/16 17:09
     **/
    @Override
    public Object selInvoiceCount(List<String> uuidList) {
        //查找发票明细数据
        List<TdxRecordInvoiceDetailEntity> detailList = tDxRecordInvoiceDetailDao.selectList(new LambdaQueryWrapper<TdxRecordInvoiceDetailEntity>()
                .in(TdxRecordInvoiceDetailEntity::getUuid, uuidList));
        log.info("发票对应的所有明细数量:{}",detailList.size());
        //查找成品油税编
        List<TdxSpbmCpyInvoiceEntity> spbmCpyList = tdxSpbmCpyInvoiceDao.selectList(new LambdaQueryWrapper<TdxSpbmCpyInvoiceEntity>().eq(TdxSpbmCpyInvoiceEntity::getSfhzx, "N"));
        //商品编码列表
        List<String> spbmList = spbmCpyList.stream().map(TdxSpbmCpyInvoiceEntity::getSpbm).collect(Collectors.toList());
        //筛选出编码对应的名称  编码--名称
        Map<String, String> spBmToMc = spbmCpyList.stream().collect(Collectors.toMap(
                TdxSpbmCpyInvoiceEntity::getSpbm,
                TdxSpbmCpyInvoiceEntity::getSphfwmc,
                (existing, replacement) -> existing // 如果key重复，保留第一个value
        ));
        log.info("成品油商品编码数据查询完成");

        //筛选出属于成品油的明细，按税编分组  税编--明细list
        Map<String, List<TdxRecordInvoiceDetailEntity>> groupSpbm = detailList.stream().filter(e -> spbmList.contains(e.getGoodsNum()))
                .collect(Collectors.groupingBy(TdxRecordInvoiceDetailEntity::getGoodsNum));
        log.info("筛选完属于成品油的明细，共{}种",groupSpbm.size());

        JSONObject json = new JSONObject();
        //汇总出展示到前端的数据
        Map<String,Object> resultMap = new HashMap();
        groupSpbm.keySet().forEach(key -> {
            List<TdxRecordInvoiceDetailEntity> tdxRecordInvoiceDetailEntities = groupSpbm.get(key);
            TdxSpbmCpyInvoiceEntity tdxSpbmCpyInvoiceEntity = spbmCpyList.stream().filter(e -> key.equals(e.getSpbm())).findFirst().get();
            if(tdxRecordInvoiceDetailEntities.size()>0){
                resultMap.put(spBmToMc.get(key),sumDetailCount(tdxRecordInvoiceDetailEntities,tdxSpbmCpyInvoiceEntity)+"吨" );
            }
        });

        json.put("selNum", uuidList.size());
        json.put("selGroup", resultMap);

        //统计出各项的总数
        return super.responseResult(json);
    }

    /**
     * @Description 成品油批量勾选入库接口
     * @Return java.lang.Object
     * @Author wangruwei
     * @Date 2024/7/16 14:25
     **/
    @Override
    public Object cpyGxByUuids(List<String> uuidList, UserInfo userInfo) {
        //页面可勾选，现在直接判断t_dx_invoice_cpy_gx里的状态，可勾选的入库
        List<TdxInvoiceCpyGxEntity> tdxInvoiceCpyGxEntities = tdxInvoiceCpyGxDao.selectList(new LambdaQueryWrapper<TdxInvoiceCpyGxEntity>()
                .in(TdxInvoiceCpyGxEntity::getGxclzt,  Arrays.asList("0","3"))
                .in(TdxInvoiceCpyGxEntity::getUuid, uuidList));
        log.info("筛选出状态为0和3的数据，更新为勾选中,筛选出要更新的数据{}条",tdxInvoiceCpyGxEntities.size());
        //页面可勾选，现在直接判断t_dx_invoice_cpy_gx里的状态，可勾选的入库

        if(tdxInvoiceCpyGxEntities.size()>0){
            List<String> updateUuidList = tdxInvoiceCpyGxEntities.stream().map(TdxInvoiceCpyGxEntity::getUuid).collect(Collectors.toList());
            TdxInvoiceCpyGxEntity updateCpygx = new TdxInvoiceCpyGxEntity();
            updateCpygx.setGxclzt("1");
            updateCpygx.setCzr(userInfo.getId());
            updateCpygx.setCzrName(userInfo.getUsername());
            updateCpygx.setCzsj(new Date());
            int update = tdxInvoiceCpyGxDao.update(updateCpygx, new LambdaUpdateWrapper<TdxInvoiceCpyGxEntity>()
                    .in(TdxInvoiceCpyGxEntity::getUuid, updateUuidList));
            log.info("更新完成，本次更新{}条",update);
        }else{
            log.info("没有要更新的数据");
        }

        JSONObject json = new JSONObject();
        json.put("code","0000");
        json.put("message","处理成功");
        return super.responseResult(json);
    }



    /**
     * @Description 成品油全部勾选入库接口--根据页面查询条件提示勾选总吨数
     * @param
     * @Return java.lang.Object
     * @Author wangruwei
     * @Date 2024/7/16 17:09
     **/
    @Override
    public Map<String, Object> cpyGxBySelConditionCount(Map<String, Object> pramsMap) {
        Map<String,Object> result = new HashMap();
        //找到所有符合条件的数据
        List<TDxRecordInvoiceCpyVo> selList = super.baseMapper.selectAuthPageList(pramsMap);
        log.info("页面条件查询出条数:{}",selList.size());
        //筛选出可勾选的数据uuid集合
        List<String> uuids = selList.stream().filter(e -> StringUtils.isBlank(getCheckedStatus(e))).map(TDxRecordInvoiceCpyVo::getUuid).collect(Collectors.toList());
        log.info("其中可勾选的数量:{}",uuids.size());
        if(uuids.size()==0){
            result.put("code", "9998");
            result.put("msg", "没有可勾选数据");
            return result;
        }
        log.info("调勾选显示吨数方法，获取数据");
        result.put("code", "0000");
        result.put("data", selInvoiceCount(uuids));
        return result;
    }

    /**
     * @Description 成品油全部勾选入库接口--根据页面查询条件全部勾选
     * @param pramsMap
     * @param userInfo
     * @Return java.lang.Object
     * @Author wangruwei
     * @Date 2024/7/16 14:25
     **/
    @Override
    public Object cpyGxBySelCondition(Map<String, Object> pramsMap, UserInfo userInfo) {
        //找到所有符合条件的数据
        List<TDxRecordInvoiceCpyVo> selList = super.baseMapper.selectAuthPageList(pramsMap);
        log.info("页面条件查询出条数:{}",selList.size());
        //筛选出可勾选的数据uuid集合
        List<String> uuids = selList.stream().filter(e -> StringUtils.isBlank(getCheckedStatus(e))).map(TDxRecordInvoiceCpyVo::getUuid).collect(Collectors.toList());
        log.info("其中可勾选的数量:{}",uuids.size());
        log.info("调勾选入库方法");
        return cpyGxByUuids(uuids, userInfo);
    }

    /**
     * @Description 成品油导入勾选-发票
     * @param cpyImportInvioceReqList
     * @param gfshAll
     * @Return java.lang.Object
     * @Author wangruwei
     * @Date 2024/7/17 10:43
     **/
    @Override
    public ResponseEntity<R> cpyImportInvoice(List<CpyImportInvioceReq> cpyImportInvioceReqList, UserInfo userInfo, List<String> gfshAll) {
        //验证数据是否合法
        List<String> errorMsgList = checkDrParam(cpyImportInvioceReqList,gfshAll);
        if (!CollectionUtils.isEmpty(errorMsgList)) {
            log.info("参数校验未通过");
            return ResponseEntity.ok(R.error(9998, "参数校验未通过").put("data", errorMsgList));
        }

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

        List<String> uuidlist = new LinkedList();
        cpyImportInvioceReqList.stream().forEach(param->{
            try {
                String fpdm = param.getFpdm();
                String fphm = param.getFphm();
                String sdhm = null;
                if (StringUtils.isBlank(fpdm) && StringUtils.isNotBlank(fphm) && fphm.length() == 20) {
                    //判断为数电号码
                    sdhm = fphm;
                }
                TdxRecordInvoiceEntity invoice = null;
                if (StringUtils.isNotBlank(sdhm)) {
                    invoice = tdxRecordInvoiceDao.selectOne(new LambdaQueryWrapper<TdxRecordInvoiceEntity>().eq(TdxRecordInvoiceEntity::getEleInvoiceNo, sdhm));
                } else {
                    invoice = tdxRecordInvoiceDao.selectOne(new LambdaQueryWrapper<TdxRecordInvoiceEntity>().eq(TdxRecordInvoiceEntity::getInvoiceCode, fpdm).eq(TdxRecordInvoiceEntity::getInvoiceNo,fphm));
                }
                //执行勾选操作
                uuidlist.add(invoice.getUuid());

            } catch (Exception e) {
                log.info("业务处理异常：{}", e);
                return;
            }
        });
        //调导入勾选方法
        cpyGxByUuids(uuidlist,userInfo);
        //调查询勾选各项吨数，给到前端
        Object gxSucData = selInvoiceCount(uuidlist);
        log.info("导入勾选完成");
        return ResponseEntity.ok(R.ok().put("data", gxSucData));

    }



    //-------------------------------方法部分-----------------------------------------------------------------------------------

    /**
    * @Description 格式化吨，变为千分位，小数后面的0去掉
    * @param dunStr
    * @Return java.lang.String
    * @Author wangruwei
    * @Date 2024/7/17 15:10
    **/
    public static String formateDunNumStr(String dunStr){
        // 将字符串转换为双精度浮点数
        double number = Double.parseDouble(dunStr);

        // 创建DecimalFormat实例，设置格式
        DecimalFormat df = new DecimalFormat("#,##0.##########");

        // 格式化数字并返回结果
        return df.format(number);
    }

    public static void main(String[] args) {
        System.out.println(formateDunNumStr("123456.12345600"));
    }

    private List<String> checkDrParam(List<CpyImportInvioceReq> reqList, List<String> gfshAll) {
        int index = 0;
        List<String> errorMsgList = new ArrayList<>();
        for (CpyImportInvioceReq param : reqList) {
            String error = null;
            index ++;
            String fpdm = param.getFpdm();
            String fphm = param.getFphm();
            String kprq = param.getKprq();
            String sdhm = null;
            if (StringUtils.isNotBlank(fpdm)) {
                if (fpdm.length() != 10 && fpdm.length() != 12) {
                    error = "第"+index+ "条数据：发票代码不为空时，发票代码长度应为10或者12";
                    log.info("error");
                    errorMsgList.add(error);
                    continue;
                }
                if (!CommonUtil.checkStrNum(fpdm)) {
                    error = "第"+index+ "条数据：发票代码不为空时，发票代码必须为数字";
                    log.info("error");
                    errorMsgList.add(error);
                    continue;
                }
                if (StringUtils.isBlank(fphm) || fphm.length() != 8) {
                    error = "第"+index+ "条数据：发票代码不为空时，发票号码长度必须为8";
                    log.info("error");
                    errorMsgList.add(error);
                    continue;
                }
            }else{
                if (StringUtils.isBlank(fphm) || fphm.length() != 20) {
                    error = "第"+index+ "条数据：发票代码为空时，发票号码长度必须为20";
                    log.info("error");
                    errorMsgList.add(error);
                    continue;
                }
            }
            if (!CommonUtil.checkStrNum(fphm)) {
                error = "第"+index+ "条数据：发票号码必须为数字";
                log.info("error");
                errorMsgList.add(error);
                continue;
            }

            if (StringUtils.isBlank(kprq)) {
                error = "第"+index+ "条数据：开票日期必填";
                log.info("error");
                errorMsgList.add(error);
                continue;
            }
            if(!DateUtils.checkStrFormat(kprq, "yyyy-MM-dd")){
                error = "第"+index+ "条数据：开票日期格式不正确";
                log.info("error");
                errorMsgList.add(error);
                continue;
            }
            if (StringUtils.isBlank(fpdm) && StringUtils.isNotBlank(fphm) && fphm.length() == 20) {
                //判断为数电号码
                sdhm = fphm;
            }

            TdxRecordInvoiceEntity invoice = null;
            //代码号码和开票日期同步验证
            if (StringUtils.isNotBlank(sdhm)) {
                invoice = tdxRecordInvoiceDao.selectOne(new LambdaQueryWrapper<TdxRecordInvoiceEntity>()
                        .eq(TdxRecordInvoiceEntity::getEleInvoiceNo, sdhm)
                        .likeRight(TdxRecordInvoiceEntity::getInvoiceDate, kprq)
                );
            } else {
                invoice = tdxRecordInvoiceDao.selectOne(new LambdaQueryWrapper<TdxRecordInvoiceEntity>()
                        .eq(TdxRecordInvoiceEntity::getInvoiceCode, fpdm).eq(TdxRecordInvoiceEntity::getInvoiceNo,fphm)
                        .likeRight(TdxRecordInvoiceEntity::getInvoiceDate, kprq)
                );
            }

            if (invoice == null) {
                error = "第"+index+ "条数据：底账库不存在该发票";
                log.info("error");
                errorMsgList.add(error);
                continue;
            }

            SysEnterpriseConfigEntity enterpriseConfig = sysEnterpriseConfigDao.selectOne(new QueryWrapper<SysEnterpriseConfigEntity>().eq("nsrsbh", invoice.getGfTaxNo()));
            if (enterpriseConfig == null) {
                error = "第"+index+ "条数据：未查询到该购方税号："+invoice.getGfTaxNo()+"的配置信息";
                log.info("error");
                errorMsgList.add(error);
                continue;
            }

            if (!enterpriseConfig.getJrfs().equals(ConfigureConstant.STRING_1)) {
                error = "第"+index+ "条数据：该购方税号：："+invoice.getGfTaxNo()+"为非乐企税号不支持成品油勾选";
                log.info("error");
                errorMsgList.add(error);
                continue;
            }

            if(!gfshAll.contains(invoice.getGfTaxNo())){
                error = "第"+index+ "条数据：无发票所属税号操作权限";
                log.info("error");
                errorMsgList.add(error);
                continue;
            }
            //1.5.校验发票有效抵扣税额是否大于等于0，如果不满足则返回“负数发票不允许勾选”
            if(ObjectUtil.isNotEmpty(invoice.getDkTaxAmount())){
                if(invoice.getDkTaxAmount()<0){
                    error = "第"+index+ "条数据：负数发票不允许勾选";
                    log.info("error");
                    errorMsgList.add(error);
                    continue;
                }
            }else{
                if("1".equals(invoice.getIsRed())){
                    error = "第"+index+ "条数据：负数发票不允许勾选";
                    log.info("error");
                    errorMsgList.add(error);
                    continue;
                }
            }

            //1.6.校验发票是否为成品油发票  在cpygx里有数据，则是成品油发票
            TdxInvoiceCpyGxEntity tdxInvoiceCpyGxEntity = tdxInvoiceCpyGxDao.selectOne(new LambdaQueryWrapper<TdxInvoiceCpyGxEntity>().eq(TdxInvoiceCpyGxEntity::getUuid, invoice.getUuid()));
            if (ObjectUtil.isEmpty(tdxInvoiceCpyGxEntity)) {
                error = "第"+index+ "条数据：非成品油发票不允许导入";
                log.info("error");
                errorMsgList.add(error);
                continue;
            }

            //1.7.校验成品油消费税用途是否为 未勾选库存（或者判断系统中的用途处理状态是否为未申请、申请失败）否则返回“发票当前发票已在处理中、已勾选入库，不可重复提交勾选入库”
            if("1".equals(tdxInvoiceCpyGxEntity.getGxclzt())||"2".equals(tdxInvoiceCpyGxEntity.getGxclzt())||"4".equals(tdxInvoiceCpyGxEntity.getGxclzt())){
                error = "第"+index+ "条数据：当前发票已做入库操作，不允许重复勾选入库";
                log.info("error");
                errorMsgList.add(error);
                continue;
            }

            //1.8.校验发票状态是否为正常、部分红冲，如果不满足则返回“发票状态异常”
            if( !("0".equals(invoice.getInvoiceStatus())||"7".equals(invoice.getInvoiceStatus()))){
                error = "第"+index+ "条数据：发票状态异常";
                log.info("error");
                errorMsgList.add(error);
                continue;
            }

            //1.9.校验红字锁定标识是否为锁定，如果不满足则返回“红字锁定状态异常”
            if("Y".equals(invoice.getLqHzsdbs())){
                error = "第"+index+ "条数据：红字锁定状态异常";
                log.info("error");
                errorMsgList.add(error);
                continue;
            }
            //1.10.校验发票风险等级是否为正常、疑似异常，如果不满足则返回“发票风险等级异常”
            if( !( "0".equals(invoice.getGlzt())||"2".equals(invoice.getGlzt()))){
                error = "第"+index+ "条数据：发票风险等级异常";
                log.info("error");
                errorMsgList.add(error);
                continue;
            }

            //1.11.校验成品油异常标识是否正常，如果不满足则返回“成品油异常标识异常”
            if( StringUtils.isBlank(invoice.getLqCpyycbs())||"9".equals(invoice.getLqCpyycbs())){

            }else{
                error = "第"+index+ "条数据：成品油异常标识异常";
                log.info("error");
                errorMsgList.add(error);
                continue;
            }

            //1.12.q_xfsyt非00的不应该导入成功
            if( StringUtils.isNotBlank(invoice.getLqXfsyt())&&!"00".equals(invoice.getLqXfsyt())){
                error = "第"+index+ "条数据：消费税用途异常";
                log.info("error");
                errorMsgList.add(error);
                continue;
            }
        }
        return errorMsgList;
    }

    /**
    * @Description 计算明细里成品油吨数
    * @param detailList     发票明细表--同一个税编的明细集合
    * @param spbmCpyInvoiceEntity    成品油税编表
    * @Return void
    * @Author wangruwei
    * @Date 2024/7/16 17:45
    **/
    public static String sumDetailCount(List<TdxRecordInvoiceDetailEntity> detailList,TdxSpbmCpyInvoiceEntity spbmCpyInvoiceEntity){
        //总吨数
        String totalDun = "0";
        //计量单位换算标准（升/千克）
        String jldwhs = spbmCpyInvoiceEntity.getJldwhs();
        for (int i = 0; i < detailList.size(); i++) {
            TdxRecordInvoiceDetailEntity detailItem = detailList.get(i);
            if(StringUtils.isNotBlank(detailItem.getNum())){
                if("升".equals(detailItem.getUnit())){
                    //变成吨
                    String itemDun = MathUtil.divide(MathUtil.divide(detailItem.getNum(), jldwhs,6), "1000",6);
                    totalDun = MathUtil.add(totalDun, itemDun);
                }else if("吨".equals(detailItem.getUnit())){
                    totalDun = MathUtil.add(totalDun, detailItem.getNum());
                }else{
                    //不处理
                }
            }
        }
        if("0".equals(totalDun)){
            return "0";
        }else{
            return formateDunNumStr(totalDun);
        }
    }

    /**
    * @Description 获取当前发票可勾选状态
    * @param tDxRecordInvoiceCpyVo
     * @Return void
    * @Author wangruwei
    * @Date 2024/7/15 17:59
    **/
    private String getCheckedStatus(TDxRecordInvoiceCpyVo tDxRecordInvoiceCpyVo) {
        //不可选原因
        List<String> notSelMsg = new LinkedList();

        /*1可勾选成品油消费税发票判断条件如下：
        1.1判断发票为蓝字发票
        1.2校验发票类型：
        1.2.1增值税专用发票 特殊票种标识为08、18：成品油
        1.2.2增值税电子专用发票 特殊票种标识为08、18：成品油
        1.2.3电子发票（增值税专用发票） 特定要素为01：成品油
        1.2.4纸质发票（增值税专用发票） 特定要素为01：成品油
        1.3校验发票中是否含有成品油商品编码，只要含有范围内的编码才允许勾选
        1.1~1.3为发票是否可以在经销企业页发票库存中是否可以看到这张发票。
        上述在取票时候就已筛选

        1.4~1.7 判断发票是否可勾选（复选框是否禁用）
        1.1判断发票为蓝字发票
        1.4校验发票状态：发票状态为正常、部分红冲
        1.5校验红字锁定标识：未锁定
        1.6校验异常凭证状态：非异常凭证（正常、疑似异常凭证）
        1.7校验成品油异常标识：正常*/
        if(ObjectUtil.isNotEmpty(tDxRecordInvoiceCpyVo.getInvoiceAmount())){
            if(tDxRecordInvoiceCpyVo.getInvoiceAmount()<0){
                notSelMsg.add("负数发票");
            }
        }else{
            //如果金额为空。判断红蓝票标识
            if("1".equals(tDxRecordInvoiceCpyVo.getIsRed())){
                notSelMsg.add("负数发票");
            }
        }

        //1.4校验发票状态：发票状态为正常、部分红冲
        if("0".equals(tDxRecordInvoiceCpyVo.getInvoiceStatus())||"7".equals(tDxRecordInvoiceCpyVo.getInvoiceStatus())){

        }else{
            notSelMsg.add("发票状态异常");
        }
        //1.5校验红字锁定标识：未锁定
        if("N".equals(tDxRecordInvoiceCpyVo.getLqHzsdbs())){

        }else{
            notSelMsg.add("红字锁定");
        }
        //1.6校验异常凭证状态：非异常凭证（正常、疑似异常凭证）
        if("0".equals(tDxRecordInvoiceCpyVo.getGlzt())||"2".equals(tDxRecordInvoiceCpyVo.getGlzt())){

        }else{
            notSelMsg.add("发票风险等级异常");
        }
        //1.7校验成品油异常标识：正常
        if(StringUtils.isBlank(tDxRecordInvoiceCpyVo.getLqCpyycbs())||"9".equals(tDxRecordInvoiceCpyVo.getLqCpyycbs())){

        }else{
            notSelMsg.add("成品油标识异常");
        }

        String showStr = String.join(",", notSelMsg);
        if(StringUtils.isNotBlank(showStr)){
            showStr+="。不允许勾选库存";
        }
        return showStr;
    }



}
