package com.dxhy.dkdj.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.dxhy.api.model.config.UserInfo;
import com.dxhy.api.model.config.sys.SysEnterpriseConfigEntity;
import com.dxhy.api.model.dkdj.DkdjAuthExcel;
import com.dxhy.api.model.dkdj.DkdjAuthReq;
import com.dxhy.api.model.dkdj.TdxZzsDkdjwspzEntity;
import com.dxhy.api.model.dkdj.TdxZzsDkdjwspzVo;
import com.dxhy.base.dao.BaseSysEnterpriseConfigDao;
import com.dxhy.base.dao.BaseTDxDkCountDao;
import com.dxhy.base.dao.BaseTDxTaxCurrentDao;
import com.dxhy.base.entity.BaseTDxDkCount;
import com.dxhy.base.entity.BaseTDxTaxCurrent;
import com.dxhy.common.constant.ConfigureConstant;
import com.dxhy.common.constant.DbConstant;
import com.dxhy.common.constant.DictConstant;
import com.dxhy.common.datasource.config.DynamicContextHolder;
import com.dxhy.common.enums.BdkStatusEnum;
import com.dxhy.common.service.DictdetaServcice;
import com.dxhy.common.service.impl.MpBaseServiceImpl;
import com.dxhy.common.util.AmountFormatUtil;
import com.dxhy.common.util.MathUtil;
import com.dxhy.common.util.UserInfoUtil;
import com.dxhy.common.utils.DateUtils;
import com.dxhy.dkdj.dao.DkdjDao;
import com.dxhy.dkdj.service.DkdjService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

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

/**
 * @Description 代扣代缴业务层
 * @Author wangruwei
 * @Date 2023/11/28 11:24
 **/
@Service("dkdjService")
@Slf4j
public class DkdjServiceImpl  extends MpBaseServiceImpl<DkdjDao, TdxZzsDkdjwspzEntity> implements DkdjService {

    @Resource
    private DkdjDao tDxLqRzInvoiceDao;

    @Resource
    private BaseTDxTaxCurrentDao baseTDxTaxCurrentDao;

    @Resource
    private BaseTDxDkCountDao basetdxDkCountDao;

    @Resource
    private BaseSysEnterpriseConfigDao baseSysEnterpriseConfigDao;

    @Resource
    private DictdetaServcice dictdetaServcice;

    /**
     * @Description 代扣代缴查询页面
     * @param pramsMap
     * @Return java.lang.Object
     * @Author wangruwei
     * @Date 2023/11/28 11:38
     **/
    @Override
    public Object dkdjAuthPage(Map<String, Object> pramsMap, int curr, int size) {
        JSONObject json = new JSONObject();
        DynamicContextHolder.push(pramsMap.get("dbName") + DbConstant.BUSINESS_READ);

        try {
            //json = tabulateRedisService.getTabulateMenu(company, menuId);

            // 合计信息,仅第一页时需要统计，减少数据库压力
            if (curr == 1) {
                String hjje = "0.00";
                String sjje = "0.00";
                String hjyxse = "0";
                List<TdxZzsDkdjwspzEntity> hjList = super.baseMapper.selectDkdjAuthPageHj(pramsMap);
                if (hjList.size()>0) {
                    TdxZzsDkdjwspzEntity hjxx = hjList.get(0);
                    hjje = AmountFormatUtil.fmtMicrometer(MathUtil.round(hjxx.getJsje()));
                    sjje = AmountFormatUtil.fmtMicrometer(MathUtil.round(hjxx.getSjje()));
                    hjyxse = AmountFormatUtil.fmtMicrometer(MathUtil.round(hjxx.getYxse()));
                }
                json.put("hjje", hjje);
                json.put("sjje", sjje);
                json.put("hjyxse", hjyxse);
            }

            List<String> gfshList = (List<String>) pramsMap.get("kjywrsbh");
            List<BaseTDxDkCount> dkCountList = new LinkedList();
            Map<String, BaseTDxTaxCurrent> taxCurrentMap = new HashMap<>();
            Map<String, SysEnterpriseConfigEntity> gfInfoMap = new HashMap();
            for (String gfsh:gfshList) {
                DynamicContextHolder.push("business" + DbConstant.BUSINESS_READ);
                BaseTDxTaxCurrent tdxTaxCurrent = baseTDxTaxCurrentDao.selectOne(
                        new QueryWrapper<BaseTDxTaxCurrent>().eq("taxno", gfsh));
                if(ObjectUtil.isNotEmpty(tdxTaxCurrent)){
                    taxCurrentMap.put(gfsh, tdxTaxCurrent);
                    //当前税款所属期
                    String currentTaxPeriod = tdxTaxCurrent.getCurrentTaxPeriod();

                    log.info("查询所传税号是否已统计成功，用作限制是否可勾选。");
                    BaseTDxDkCount tdxDkCountEntity = basetdxDkCountDao.selectOne(new LambdaQueryWrapper<BaseTDxDkCount>()
                            .eq(BaseTDxDkCount::getTaxno,gfsh)
                            .eq(BaseTDxDkCount::getSkssq, currentTaxPeriod));
                    if (ObjectUtil.isNotEmpty(tdxDkCountEntity)) {
                        dkCountList.add(tdxDkCountEntity);
                    }
                    DynamicContextHolder.push(DbConstant.BASICS_READ);
                    SysEnterpriseConfigEntity sysEnterpriseConfigEntity = baseSysEnterpriseConfigDao.selectOne(new LambdaQueryWrapper<SysEnterpriseConfigEntity>().eq(SysEnterpriseConfigEntity::getNsrsbh, gfsh));
                    gfInfoMap.put(gfsh, sysEnterpriseConfigEntity);
                }
            }
            //筛选税号和是否当前属期 未统计。
            Map<String, List<BaseTDxDkCount>> wtjList = dkCountList.stream().filter(e -> "0".equals(e.getTjStatus())).collect(Collectors.groupingBy(BaseTDxDkCount::getTaxno));

            DynamicContextHolder.push("business" + DbConstant.BUSINESS_READ);
            PageHelper.startPage(curr, size);
            List<TdxZzsDkdjwspzEntity> pageList = super.baseMapper.selectDkdjAuthPageList(pramsMap);
            PageInfo<TdxZzsDkdjwspzEntity> pageInfo = new PageInfo<>(pageList);
            List<TdxZzsDkdjwspzEntity> resultList = pageInfo.getList();
            String searchPageType = pramsMap.get("searchPageType").toString();
            List<TdxZzsDkdjwspzVo> resultShowList = new LinkedList();
            // 用于页面返回list对象
            if (resultList.size() > 0) {
                int start = (int)pageInfo.getStartRow();
                if("0".equals(searchPageType)){
                    log.info("可勾选条件：1.税号当前属期为未统计，2.代扣代缴完税凭证的填发日期小于等于当前属期的最后一天，3.如果是乐企，填发日期大于等于成为试点企业下月1号");
                }else{
                    log.info("可勾选条件：1.税号对应的明细属期为未统计，2.认证状态=已认证抵扣、已认证不抵扣且处理状态= 申请成功");
                }

                for (int i = 0; i < resultList.size(); i++) {
                    TdxZzsDkdjwspzVo item = new TdxZzsDkdjwspzVo();
                    item.setXh(String.valueOf(i + start));
                    BeanUtils.copyProperties(resultList.get(i),item);
                    item.setSelect(false);
                    //可勾选判断
                    if("0".equals(searchPageType)){
                        //log.info("可勾选条件：1.税号当前属期为未统计，2.代扣代缴完税凭证的填发日期小于等于当前属期的最后一天");
                        //1.税号当前属期为未统计
                        if(ObjectUtil.isNotEmpty(wtjList.get(item.getKjywrsbh()))&&wtjList.get(item.getKjywrsbh()).size()>0){
                            //查到属期，判断
                            if(ObjectUtil.isNotEmpty(taxCurrentMap.get(item.getKjywrsbh()))){
                                //2.代扣代缴完税凭证的填发日期小于等于当前属期的最后一天
                                BaseTDxTaxCurrent current = taxCurrentMap.get(item.getKjywrsbh());

                                if (item.getTfrq()
                                        .compareTo(DateUtils.strToDatePeriodFormate(current.getSelectEndDate()+"235959","yyyyMMddHHmmss")) <= 0) {
                                    item.setSelect(true);
                                    //2.如果是乐企的话，判断成为试点企业日期
                                    //如果是乐企，判断  是否大于等于为成为试点企业的下一个月1日的票据
                                    SysEnterpriseConfigEntity sysEnterpriseConfigEntity = gfInfoMap.get(item.getKjywrsbh());
                                    if(ObjectUtil.isNotEmpty(sysEnterpriseConfigEntity)){
                                        if("1".equals(sysEnterpriseConfigEntity.getJrfs())){
                                            if(StringUtils.isNotEmpty(sysEnterpriseConfigEntity.getNcpgnqyrq())){
                                                //试点企业日期
                                                String sdqyrq = sysEnterpriseConfigEntity.getNcpgnqyrq() + "-01";
                                                //称为企业试点日期的下月1号
                                                String nextMonthDay = DateUtils.getNextMonthDay(sdqyrq, 1);
                                                if(
                                                        item.getTfrq()
                                                                .compareTo(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(nextMonthDay+" 00:00:00")) < 0){
                                                    item.setSelect(false);
                                                }
                                            }
                                        }
                                    }

                                }
                            }
                        }


                    }else{
                        //log.info("可勾选条件：1.税号对应的明细属期为未统计，2.认证状态=已认证抵扣、已认证不抵扣且处理状态= 申请成功");
                        //1.税号当前属期为未统计
                        if(ObjectUtil.isNotEmpty(wtjList.get(item.getKjywrsbh()))&&wtjList.get(item.getKjywrsbh()).size()>0){
                            //查到属期，判断
                            if(ObjectUtil.isNotEmpty(taxCurrentMap.get(item.getKjywrsbh()))){
                                //2.认证状态=已认证抵扣、已认证不抵扣且处理状态= 申请成功
                                if ( ConfigureConstant.STRING_4.equals(item.getRzclzt())&&
                                        (ConfigureConstant.STRING_1.equals(item.getRzzt())||ConfigureConstant.STRING_2.equals(item.getRzzt()))
                                       ) {
                                    item.setSelect(true);
                                }
                            }
                        }
                    }

                    if(StringUtils.isNotEmpty(item.getJsje())){
                        item.setJsje(AmountFormatUtil.fmtMicrometer2(item.getJsje()));
                    }
                    if(StringUtils.isNotEmpty(item.getSjje())){
                        item.setSjje(AmountFormatUtil.fmtMicrometer2(item.getSjje()));
                    }
                    if(StringUtils.isNotEmpty(item.getYxse())){
                        item.setYxse(AmountFormatUtil.fmtMicrometer2(item.getYxse()));
                    }

                    if(ObjectUtil.isNotEmpty(item.getTfrq())){
                        item.setTfrqShow(DateUtils.dateToStr(item.getTfrq(), "yyyy-MM-dd"));
                    }
                    if(ObjectUtil.isNotEmpty(item.getRzsj())&&item.getRzsj().length()>=10){
                        item.setRzsjShow(item.getRzsj().substring(0,10));
                    }
                    //处理状态
                    if(StringUtils.isNotEmpty(item.getRzclzt())){
                        item.setRzclzt(dictdetaServcice.queryDictName(DictConstant.NCPJJKC_JJCLZT, item.getRzclzt()));
                    }
                    //认证类型
                    if(StringUtils.isNotEmpty(item.getRzlx())){
                        item.setRzlx(dictdetaServcice.queryDictName(DictConstant.DKDJ_RZLX, item.getRzlx()));
                    }
                    //认证状态
                    if(StringUtils.isNotEmpty(item.getRzzt())){
                        item.setRzzt(dictdetaServcice.queryDictName(DictConstant.DEDU_STATUS, item.getRzzt()));
                    }

                    //不抵扣类型
                    if(StringUtils.isNotEmpty( item.getBdklx())){
                        item.setBdklx(dictdetaServcice.queryDictName(DictConstant.bdkMessage, item.getBdklx()));
                    }

                    resultShowList.add(item);
                }
            }

            // 设置记录总数
            json.put("total", pageInfo.getTotal());
            json.put("datalist", resultShowList);
        } catch (Exception e) {
            // 统一设置操作异常标识
            json = super.errorResult(e);
        }

        return super.responseResult(json);
    }

    /**
     * @Description 代扣代缴认证/认证不抵扣
     * @Return java.lang.Object
     * @Author wangruwei
     * @Date 2023/11/28 11:38
     **/
    @Override
    public Object dkdjAuth(DkdjAuthReq dkdjAuthReq, UserInfo userInfo) {
        JSONObject json = new JSONObject();
        DynamicContextHolder.push("business" + DbConstant.BUSINESS_READ);
        String hjje = "0.00";
        String sjje = "0.00";
        String hjyxse = "0";

        if(ConfigureConstant.STRING_1.equals(dkdjAuthReq.getRzType())){
            log.info("认证抵扣");
        }else if(ConfigureConstant.STRING_2.equals(dkdjAuthReq.getRzType())){
            log.info("认证不抵扣");
        }else if(ConfigureConstant.STRING_3.equals(dkdjAuthReq.getRzType())){
            log.info("撤销认证");
        }else{
            log.info("没有此认证类型");
        }

        List<TdxZzsDkdjwspzEntity> tdxZzsDkdjwspzEntities = this.baseMapper.selectList(new LambdaQueryWrapper<TdxZzsDkdjwspzEntity>().in(TdxZzsDkdjwspzEntity::getDkdjwspzh, dkdjAuthReq.getDkdjwspzhs()));

        for (int i = 0; i < tdxZzsDkdjwspzEntities.size(); i++) {
            TdxZzsDkdjwspzEntity tdxZzsDkdjwspzEntity = tdxZzsDkdjwspzEntities.get(i);
            BaseTDxTaxCurrent tdxTaxCurrent = baseTDxTaxCurrentDao.selectOne(
                    new QueryWrapper<BaseTDxTaxCurrent>().eq("taxno", tdxZzsDkdjwspzEntity.getKjywrsbh()));
            //当前税款所属期
            String currentTaxPeriod = "";
            if(ObjectUtil.isNotEmpty(tdxTaxCurrent)){
                currentTaxPeriod = tdxTaxCurrent.getCurrentTaxPeriod();
            }
            if(ConfigureConstant.STRING_1.equals(dkdjAuthReq.getRzType())){
                //log.info("认证抵扣");
                tdxZzsDkdjwspzEntity.setRzlx("01");
                tdxZzsDkdjwspzEntity.setRzclzt("1");
                tdxZzsDkdjwspzEntity.setRzssq(currentTaxPeriod);
            }else if(ConfigureConstant.STRING_2.equals(dkdjAuthReq.getRzType())){
                //log.info("认证不抵扣");
                tdxZzsDkdjwspzEntity.setRzlx("03");
                tdxZzsDkdjwspzEntity.setRzclzt("1");
                tdxZzsDkdjwspzEntity.setRzssq(currentTaxPeriod);
                tdxZzsDkdjwspzEntity.setBdklx(dkdjAuthReq.getBdklx());
                tdxZzsDkdjwspzEntity.setBdkyy(dkdjAuthReq.getBdkyy());
            }else if(ConfigureConstant.STRING_3.equals(dkdjAuthReq.getRzType())){
                //log.info("撤销认证");
                //tdxZzsDkdjwspzEntity.setRzlx("04");
                //认证类型：01申请抵扣，02撤销抵扣，03申请不抵扣，04撤销不抵扣
                //如果认证类型是01申请抵扣，变02  。03变04
                if("01".equals(tdxZzsDkdjwspzEntity.getRzlx())){
                    tdxZzsDkdjwspzEntity.setRzlx("02");
                }
                if("03".equals(tdxZzsDkdjwspzEntity.getRzlx())){
                    tdxZzsDkdjwspzEntity.setRzlx("04");
                }
                tdxZzsDkdjwspzEntity.setRzclzt("5");
            }
            if(StringUtils.isNotEmpty(tdxZzsDkdjwspzEntity.getJsje())){
                hjje = MathUtil.add(hjje, tdxZzsDkdjwspzEntity.getJsje());
            }
            if(StringUtils.isNotEmpty(tdxZzsDkdjwspzEntity.getSjje())){
                sjje = MathUtil.add(sjje, tdxZzsDkdjwspzEntity.getSjje());
            }
            if(StringUtils.isNotEmpty(tdxZzsDkdjwspzEntity.getYxse())){
                hjyxse = MathUtil.add(hjyxse, tdxZzsDkdjwspzEntity.getYxse());
            }

            tdxZzsDkdjwspzEntity.setCzr(userInfo.getUsername());
            tdxZzsDkdjwspzEntity.setCzsj(new Date());
            tdxZzsDkdjwspzEntity.setUpdateTime(new Date());
            this.baseMapper.updateById(tdxZzsDkdjwspzEntity);
        }
        json.put("code", "0000");
        json.put("msg", "处理成功");
        json.put("hjje", hjje);
        json.put("sjje", sjje);
        json.put("hjyxse", hjyxse);
        json.put("total", tdxZzsDkdjwspzEntities.size());
        return super.responseResult(json);
    }


    /**
     * @Description 代扣代缴导入，返回前端展示
     * @param dkdjAuthExcels
     * @param userInfo
     * @Return java.lang.Object
     * @Author wangruwei
     * @Date 2023/11/29 16:04
     **/
    @Override
    public Object dkdjExcelShow(List<DkdjAuthExcel> dkdjAuthExcels, UserInfo userInfo) {
        for (int i = 0; i < dkdjAuthExcels.size(); i++) {
            dkdjAuthExcels.get(i).setRowNum(i+1);
        }
        JSONObject json = new JSONObject();
        //验证excel数据是否合规
        CheckExcelDataRecord checkExcelDataRecord = checkDkdjExcel(dkdjAuthExcels,userInfo);
        if(checkExcelDataRecord.getErrList().size()>0){
            json.put("code", "9999");
            json.put("msg", "保存数据不符合规范");
            json.put("errList", new TreeMap<>(checkExcelDataRecord.getErrList()));
            return super.responseResult(json);
        }
        //检测成功，返回给前端展示
        List<TdxZzsDkdjwspzVo> recordIncoceList = checkExcelDataRecord.getExcelList();
        for (int i = 0; i < recordIncoceList.size() ; i++) {
            TdxZzsDkdjwspzVo item = recordIncoceList.get(i);
            //BeanUtils.copyProperties(recordIncoceList.get(i),item);
            item.setXh((i+1)+"");
            item.setTfrqShow(DateUtils.dateToStr(item.getTfrq(), "yyyy-MM-dd"));
            if(StringUtils.isNotEmpty(item.getJsje())){
                item.setJsje(AmountFormatUtil.fmtMicrometer2(item.getJsje()));
            }
            if(StringUtils.isNotEmpty(item.getSjje())){
                item.setSjje(AmountFormatUtil.fmtMicrometer2(item.getSjje()));
            }
            if(StringUtils.isNotEmpty(item.getYxse())){
                item.setYxse(AmountFormatUtil.fmtMicrometer2(item.getYxse()));
            }
            if(ObjectUtil.isNotEmpty(item.getTfrq())){
                item.setTfrqShow(DateUtils.dateToStr(item.getTfrq(), "yyyy-MM-dd"));
            }
        }
        json.put("code", "0000");
        json.put("msg", "读取成功");
        json.put("data", recordIncoceList);
        return super.responseResult(json);
    }

    /**
     * @Description 代扣代缴导入的保存，入库
     * @param dkdjAuthExcels
     * @Return java.lang.Object
     * @Author wangruwei
     * @Date 2023/11/29 16:04
     **/
    @Override
    public Object dkdjExcelSave(List<DkdjAuthExcel> dkdjAuthExcels, UserInfo userInfo) {
        JSONObject json = new JSONObject();
        //筛选出认证的
        List<DkdjAuthExcel> rzdkList = dkdjAuthExcels.stream().filter(e -> BdkStatusEnum.RZDK.getValue().equals(e.getRzType())).collect(Collectors.toList());

        if(rzdkList.size()>0){
            log.info("筛选出认证的数据调认证方法");
            DkdjAuthReq rzdkAuthReq = new DkdjAuthReq();
            rzdkAuthReq.setRzType(BdkStatusEnum.RZDK.getKey());
            rzdkAuthReq.setDkdjwspzhs(rzdkList.stream().map(e->e.getDkdjwspzh()).collect(Collectors.toList()));
            dkdjAuth(rzdkAuthReq, userInfo);
        }

        List<DkdjAuthExcel> rzbdkList = dkdjAuthExcels.stream().filter(e -> BdkStatusEnum.RZBDK.getValue().equals(e.getRzType())).collect(Collectors.toList());

        if(rzbdkList.size()>0){
            log.info("筛选出认证不抵扣的数据调认证方法");
            //按类型和原因一样的分组，再分批调
            Map<String, List<DkdjAuthExcel>> groupByBdkLx = rzbdkList.stream().collect(Collectors.groupingBy(e -> e.getBdklx()+"@"+e.getBdkyy()));
            groupByBdkLx.keySet().forEach(key -> {
                List<DkdjAuthExcel> bdkList = groupByBdkLx.get(key);
                DkdjAuthReq rzdkAuthReq = new DkdjAuthReq();
                rzdkAuthReq.setRzType(BdkStatusEnum.RZBDK.getKey());
                rzdkAuthReq.setDkdjwspzhs(bdkList.stream().map(e->e.getDkdjwspzh()).collect(Collectors.toList()));
                String bdklx = getBdklxKey(key.split("@")[0]);
                String bdkyy = "";
                if(key.split("@").length>1){
                    bdkyy = key.split("@")[1];
                }
                rzdkAuthReq.setBdklx(bdklx);
                rzdkAuthReq.setBdkyy(bdkyy);
                dkdjAuth(rzdkAuthReq, userInfo);
            });
        }
        json.put("code", "0000");
        json.put("msg", "导入认证成功");
        return super.responseResult(json);
    }

    private static String getBdklxKey(String bdklxShow){
        String bdklxKey = "";
        switch (bdklxShow){
            case "用于非应税项目":
                bdklxKey = "1";
                break;
            case "用于免税项目":
                bdklxKey = "2";
                break;
            case "用于集体福利或者个人消费":
                bdklxKey = "3";
                break;
            case "遭受非正常损失":
                bdklxKey = "4";
                break;
            case "其他":
                bdklxKey = "5";
                break;
        }
        return bdklxKey;
    }

    /**
     * 校验导入数据
     **/
    private CheckExcelDataRecord checkDkdjExcel(List<DkdjAuthExcel> dkdjAuthExcels, UserInfo userInfo) {
        CheckExcelDataRecord checkExcelDataRecord = new CheckExcelDataRecord();
        List<String> bdklxList = new LinkedList();
        bdklxList.add("用于非应税项目");
        bdklxList.add("用于免税项目");
        bdklxList.add("用于集体福利或者个人消费");
        bdklxList.add("遭受非正常损失");
        bdklxList.add("其他");
        //定义触发规则的数据
        Map<Integer, String> errMap = new HashMap<>();
        log.info("1校验必填项是否填写数据“代扣代缴完税凭证号”、“认证类型”  如果未填写则返回错误信息“必填项未录入”");
        List<DkdjAuthExcel> btx = dkdjAuthExcels.stream().filter(e -> StringUtils.isEmpty(e.getDkdjwspzh()) || StringUtils.isEmpty(e.getRzType())).collect(Collectors.toList());
        if(btx.size()>0){
            log.info("校验必填项是否填写数据“代扣代缴完税凭证号”、“认证类型”未填写的数据:{}", JSON.toJSONString(btx));
            for (DkdjAuthExcel item: btx){
                createErrMsg(errMap,item.getRowNum(),"必填项未录入");
            }
            checkExcelDataRecord.setErrList(errMap);
            return checkExcelDataRecord;
        }

        log.info("2.校验认证类型中的填写的内容是否为“认证抵扣” 、“认证不抵扣” 如果不满足 则返回错误信息“认证类型错误”");
        List<DkdjAuthExcel> rxlxErr = dkdjAuthExcels.stream().filter(e -> !BdkStatusEnum.RZDK.getValue().equals(e.getRzType())&&!BdkStatusEnum.RZBDK.getValue().equals(e.getRzType())).collect(Collectors.toList());
        if(rxlxErr.size()>0){
            log.info("校验认证类型中的填写的内容是否为“认证抵扣” 、“认证不抵扣” 如果不满足 则返回错误信息“认证类型错误”:{}", JSON.toJSONString(rxlxErr));
            for (DkdjAuthExcel item: rxlxErr){
                createErrMsg(errMap,item.getRowNum(),"认证类型错误");
            }
        }

        log.info("3.认证类型=认证不抵扣校验不抵扣类型是否填写，如果未填写则默认为补齐“不抵扣类型=其他”“不抵扣原因=其他”");
        log.info("3.1.如果不抵扣类型有值则校验不抵扣类型值是否为“用于非应税项目”、“用于免税项目”“用于集体福利或者个人消费”、“遭受非正常损失”、“其他” 如果不满足则返回错误信息“认证类型错误”；");
        log.info("3.2.如果认证类型=其他，校验“不抵扣原因”是否有值，如果有值则存储录入值，校验“不抵扣原因”字段中长度30字符，如果为空则补齐字段“其他”");
        List<DkdjAuthExcel> bdkYy = dkdjAuthExcels.stream().filter(e -> BdkStatusEnum.RZBDK.getValue().equals(e.getRzType())).collect(Collectors.toList());
        if(bdkYy.size()>0){
            for (DkdjAuthExcel item: bdkYy){
                if(StringUtils.isEmpty(item.getBdklx())){
                    item.setBdklx("其他");
                }else{
                    //校验是否属于正确的不抵扣类型
                    if(!bdklxList.contains(item.getBdklx())){
                        createErrMsg(errMap,item.getRowNum(),"认证类型错误");
                    }
                }
                if(StringUtils.isEmpty(item.getBdkyy())){
                    item.setBdkyy("其他");
                }else{
                    if(item.getBdkyy().length()>30){
                        createErrMsg(errMap,item.getRowNum(),"不抵扣原因最多只能填写30个字");
                    }
                }
                if(!"其他".equals(item.getBdklx())){
                    item.setBdkyy("");
                }
            }
        }

        DynamicContextHolder.push("business" + DbConstant.BUSINESS_READ);
        List<BaseTDxDkCount> dkCountList = new LinkedList();
        Map<String, BaseTDxTaxCurrent> taxCurrentMap = new HashMap<>();
        List<String> gfshAll = UserInfoUtil.getGfshAll(userInfo.getOrg());
        Map<String, SysEnterpriseConfigEntity> gfInfoMap = new HashMap();
        for (String gfsh:gfshAll) {
            DynamicContextHolder.push("business" + DbConstant.BUSINESS_READ);
            BaseTDxTaxCurrent tdxTaxCurrent = baseTDxTaxCurrentDao.selectOne(
                    new QueryWrapper<BaseTDxTaxCurrent>().eq("taxno", gfsh));
            if(ObjectUtil.isNotEmpty(tdxTaxCurrent)){
                taxCurrentMap.put(gfsh, tdxTaxCurrent);
                //当前税款所属期
                String currentTaxPeriod = tdxTaxCurrent.getCurrentTaxPeriod();

                log.info("查询所传税号是否已统计成功，用作限制是否可勾选。");
                BaseTDxDkCount tdxDkCountEntity = basetdxDkCountDao.selectOne(new LambdaQueryWrapper<BaseTDxDkCount>()
                        .eq(BaseTDxDkCount::getTaxno,gfsh)
                        .eq(BaseTDxDkCount::getSkssq, currentTaxPeriod));
                if (ObjectUtil.isNotEmpty(tdxDkCountEntity)) {
                    dkCountList.add(tdxDkCountEntity);
                }
                DynamicContextHolder.push(DbConstant.BASICS_READ);
                SysEnterpriseConfigEntity sysEnterpriseConfigEntity = baseSysEnterpriseConfigDao.selectOne(new LambdaQueryWrapper<SysEnterpriseConfigEntity>().eq(SysEnterpriseConfigEntity::getNsrsbh, gfsh));
                gfInfoMap.put(gfsh, sysEnterpriseConfigEntity);
            }
        }
        //筛选税号是否当前属期 未统计。
        Map<String, List<BaseTDxDkCount>> wtjList = dkCountList.stream().filter(e -> "0".equals(e.getTjStatus())).collect(Collectors.groupingBy(BaseTDxDkCount::getTaxno));

        DynamicContextHolder.push("business" + DbConstant.BUSINESS_READ);
        log.info("4.校验代扣代缴完税凭证号是否存在，如果不存在则返回错误信息“代扣代缴完税凭证号不存在”");
        log.info("5.校验代扣代缴完税凭证号对应扣缴义务人的是否为当前用户所属权限，如果不满足则返回错误信息“无完税凭证所属扣缴义务人操作权限”");
        log.info("6.校验代扣代缴完税凭证好对应扣缴义务人所对应的税号当前属期统计状态是否为“未统计”，需要判断是否为未申请、申请失败、撤销成功，如果不为未统计则返回错误信息“税号对应属期在统计中或已统计不允许认证“");
        log.info("7.(乐企)校验代扣代缴完税凭证对应的日期是否为可勾选（是否大于等于为成为试点企业的下一个月1日的票据，小于等于当前属期最后一天），如果不满足则返回错误”完税凭证在当前属期不允许认证“");
        //导入抵扣
        List<TdxZzsDkdjwspzVo> excellist = new LinkedList();
        for (int i = 0; i < dkdjAuthExcels.size(); i++) {
            TdxZzsDkdjwspzEntity tdxZzsDkdjwspzEntity = this.baseMapper.selectOne(new LambdaQueryWrapper<TdxZzsDkdjwspzEntity>().eq(TdxZzsDkdjwspzEntity::getDkdjwspzh, dkdjAuthExcels.get(i).getDkdjwspzh()));
            if(ObjectUtil.isEmpty(tdxZzsDkdjwspzEntity)){
                createErrMsg(errMap,dkdjAuthExcels.get(i).getRowNum(),"代扣代缴完税凭证号不存在");
                continue;
            }
            TdxZzsDkdjwspzVo dkdjwspzVo = new TdxZzsDkdjwspzVo();
            BeanUtils.copyProperties(tdxZzsDkdjwspzEntity, dkdjwspzVo);
            dkdjwspzVo.setRzlx(dkdjAuthExcels.get(i).getRzType());
            dkdjwspzVo.setBdklx(dkdjAuthExcels.get(i).getBdklx());
            dkdjwspzVo.setBdkyy(dkdjAuthExcels.get(i).getBdkyy());

            excellist.add(dkdjwspzVo);
            if(!gfshAll.contains(tdxZzsDkdjwspzEntity.getKjywrsbh())){
                createErrMsg(errMap,dkdjAuthExcels.get(i).getRowNum(),"无完税凭证所属扣缴义务人操作权限");
            }
            //如果未统计信息是空，以失败处理
            if(CollectionUtils.isEmpty(wtjList.get(tdxZzsDkdjwspzEntity.getKjywrsbh()))){
                createErrMsg(errMap,dkdjAuthExcels.get(i).getRowNum(),"税号对应属期在统计中或已统计不允许认证");
            }
            //如果状态不是  未申请、申请失败、撤销成功 ，以失败处理
            if(!ConfigureConstant.STRING_0.equals(tdxZzsDkdjwspzEntity.getRzclzt())&&
                    !ConfigureConstant.STRING_3.equals(tdxZzsDkdjwspzEntity.getRzclzt())&&
                    !ConfigureConstant.STRING_8.equals(tdxZzsDkdjwspzEntity.getRzclzt())
            ){
                createErrMsg(errMap,dkdjAuthExcels.get(i).getRowNum(),"完税凭证已在处理中不允许认证");
            }

            BaseTDxTaxCurrent current = taxCurrentMap.get(tdxZzsDkdjwspzEntity.getKjywrsbh());

            //0大企业  1乐企
            String kjfs = "";
            SysEnterpriseConfigEntity mapGetQyxx = gfInfoMap.get(tdxZzsDkdjwspzEntity.getKjywrsbh());
            if(ObjectUtil.isNotEmpty(mapGetQyxx)){
                kjfs = gfInfoMap.get(tdxZzsDkdjwspzEntity.getKjywrsbh()).getJrfs();
            }
            try {
                if(ObjectUtil.isEmpty(current)){
                    createErrMsg(errMap,dkdjAuthExcels.get(i).getRowNum(),"完税凭证在当前属期不允许认证");
                    continue;
                }
                //代扣代缴完税凭证的填发日期小于等于当前属期的最后一天
                if (tdxZzsDkdjwspzEntity.getTfrq()
                        .compareTo(DateUtils.strToDatePeriodFormate(current.getSelectEndDate()+"235959","yyyyMMddHHmmss")) > 0
                ) {
                    createErrMsg(errMap,dkdjAuthExcels.get(i).getRowNum(),"完税凭证在当前属期不允许认证");
                }else{
                    //如果是乐企，判断  是否大于等于为成为试点企业的下一个月1日的票据
                    if("1".equals(kjfs)){
                        if(StringUtils.isNotEmpty(mapGetQyxx.getNcpgnqyrq())){
                            //试点企业日期
                            String sdqyrq = mapGetQyxx.getNcpgnqyrq() + "-01";
                            //称为企业试点日期的下月1号
                            String nextMonthDay = DateUtils.getNextMonthDay(sdqyrq, 1);
                            if(
                                    tdxZzsDkdjwspzEntity.getTfrq()
                                            .compareTo(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(nextMonthDay+" 23:59:59")) < 0){

                                createErrMsg(errMap,dkdjAuthExcels.get(i).getRowNum(),"完税凭证在当前属期不允许认证");
                                continue;
                            }
                        }
                    }
                }
            } catch (ParseException e) {
               log.info("业务处理异常：{}", e);
            }


        }

        checkExcelDataRecord.setErrList(errMap);
        checkExcelDataRecord.setExcelList(excellist);
        return checkExcelDataRecord;
    }

    /**
     * @Description 返回带有底账表数据，代开导入，ncp表还没数据
     * @Return
     * @Author wangruwei
     * @Date 2023/10/17 9:43
     **/
    @Data
    public class CheckExcelDataRecord{
        /**
         * 给前端返回的验证住的信息
         **/
        private Map<Integer, String> errList;
        /**
         * 校验成功后，excel转化为代扣代缴表具体信息
         * 认证抵扣
         **/
        private List<TdxZzsDkdjwspzVo> excelList;
    }

    public static boolean isGreaterThan30(String str) {
        if (str == null || str.isEmpty()) {
            return false;
        }
        int length = 0;
        for (int i = 0; i < str.length(); i++) {
            length += (str.charAt(i) >= 0x4E00 && str.charAt(i) <= 0x9FA5) ? 2 : 1;
            if (length > 30) {
                return true;
            }
        }
        return false;
    }

    public static void createErrMsg(Map errMap,int rowNum,String msg){
        if(errMap.containsKey(rowNum)){
            errMap.put(rowNum, errMap.get(rowNum)+msg+"。");
        }else{
            errMap.put(rowNum, msg+"。");
        }
    }

    public static void main(String[] args) {
        String abc = "123@";
        System.out.println(abc.split("@").length);
        System.out.println(abc.split("@")[0]);
        System.out.println(abc.split("@")[1]);


        String a = "1234567890123456789012345678901";
        System.out.println(a.length());
        System.out.println(isGreaterThan30(a));

        a = "123456789012345678901234567890";
        System.out.println(a.length());
        System.out.println(isGreaterThan30(a));

        a = "一二三四五六七八九十一二三四五六七八九十一二三四五六七八九十";
        System.out.println(a.length());
        System.out.println(isGreaterThan30(a));

        a = "一二三四五六七八九十一二三四五六七八九十一二三四五六七八九十一";
        System.out.println(a.length());
        System.out.println(isGreaterThan30(a));

        a = "一二三四五六七八九十一二三四五六七八九十一二三四五六七八九1";
        System.out.println(a.length());
        System.out.println(isGreaterThan30(a));

        a = "一二三四五六七八九十一二三四五六七八九十一二三四五六七八九22";
        System.out.println(a.length());
        System.out.println(isGreaterThan30(a));
    }

}
