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

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dxhy.api.model.bigB.enterpriseInterface.ZldwInfo;
import com.dxhy.api.model.config.UserInfo;
import com.dxhy.api.model.config.sys.ImportEnterpriseDqyEntity;
import com.dxhy.api.model.config.sys.ImportEnterpriseLqEntity;
import com.dxhy.api.model.config.sys.SysEnterpriseConfigEntity;
import com.dxhy.api.model.config.sys.SysGroupConfigEntity;
import com.dxhy.api.model.db.SysLqZldwConfigEntity;
import com.dxhy.common.constant.DbConstant;
import com.dxhy.common.constant.RedisConstant;
import com.dxhy.common.datasource.config.DynamicContextHolder;
import com.dxhy.common.rabbitmq.RabbitMqSender;
import com.dxhy.common.util.JsonUtils;
import com.dxhy.common.util.UserInfoUtil;
import com.dxhy.common.util.redis.RedisUtils;
import com.dxhy.common.utils.DateUtils;
import com.dxhy.common.utils.PageUtils;
import com.dxhy.common.utils.Query;
import com.dxhy.jxpt.baseService.config.dao.SysEnterpriseConfigDao;
import com.dxhy.jxpt.baseService.config.dao.SysGroupConfigDao;
import com.dxhy.jxpt.baseService.config.dao.SysLqZldwConfigDao;
import com.dxhy.jxpt.baseService.config.service.LqInitService;
import com.dxhy.jxpt.baseService.config.service.SysEnterpriseConfigService;
import com.dxhy.jxpt.baseService.constants.LqConfigurerInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
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.ParseException;
import java.util.*;
import java.util.stream.Collectors;


@Service("sysEnterpriseConfigFacade")
@Slf4j
public class SysEnterpriseConfigServiceImpl
		extends ServiceImpl<SysEnterpriseConfigDao, SysEnterpriseConfigEntity>
		implements SysEnterpriseConfigService {
    @Resource
    private SysGroupConfigDao sysGroupConfigDao;

    @Resource
    private SysLqZldwConfigDao sysLqZldwConfigDao;

    @Resource
    private RedisUtils redisUtils;

    @Resource
    private SysEnterpriseConfigDao sysEnterpriseConfigDao;

    @Resource
    private LqInitService lqInitService;

    @Resource
    private RabbitMqSender rabbitLogsSender;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        DynamicContextHolder.push(DbConstant.BASICS_READ);
        String company = (String)params.get("company");
        String nsrsbh = (String)params.get("nsrsbh");
        String nsrmc = (String)params.get("nsrmc");
        String jrfs = (String)params.get("jrfs");
        if(StringUtils.isNotEmpty(jrfs)&&"99".equals(jrfs)){
            jrfs = "";
        }

        IPage<SysEnterpriseConfigEntity> page = this.page(new Query<SysEnterpriseConfigEntity>().getPage(params),
                new QueryWrapper<SysEnterpriseConfigEntity>()
                        .eq(StringUtils.isNotBlank(company), "company", company)
                        .like(StringUtils.isNotBlank(nsrsbh), "nsrsbh", nsrsbh)
                        .like(StringUtils.isNotBlank(nsrmc), "nsrmc", nsrmc)
                        .eq(StringUtils.isNotBlank(jrfs), "jrfs", jrfs)
                );
        /*List<SysEnterpriseConfigEntity> resultList = page.getRecords();
        // 用于页面返回list对象
        if (resultList.size() > 0) {
            for (int i = 0; i < resultList.size(); i++) {
                String sfqyncpdk = resultList.get(i).getSfqyncpdk();
                resultList.get(i).setSfqyncpdk(dictdetaServcice.queryDictName(DictConstant.NCP_KTZT,sfqyncpdk));

                String sfqyncpjjkc = resultList.get(i).getSfqyncpjjkc();
                resultList.get(i).setSfqyncpjjkc(dictdetaServcice.queryDictName(DictConstant.NCP_KTZT,sfqyncpjjkc));
            }
        }*/
        return new PageUtils(page);
    }

    @Override
    public SysEnterpriseConfigEntity selectEnterpriseInfo(String id) {
        DynamicContextHolder.push(DbConstant.BASICS_WRITE);
        return baseMapper.selectById(id);
    }

    @Override
    public Long checkEnterpriseDqy(String company) {
        DynamicContextHolder.push(DbConstant.BASICS_WRITE);
        Long size = baseMapper.selectCount(
                new LambdaQueryWrapper<SysEnterpriseConfigEntity>()
                        .eq(SysEnterpriseConfigEntity::getCompany, company)
                        .eq(SysEnterpriseConfigEntity::getJrfs, "0")
        );
        return size;
    }

    @Override
    public int delEnterprise(String id) {
        DynamicContextHolder.push(DbConstant.BASICS_WRITE);
        SysEnterpriseConfigEntity sysEnterpriseConfigEntity = baseMapper.selectById(id);
        if(ObjectUtils.isNotEmpty(sysEnterpriseConfigEntity)&&StringUtils.isNotBlank(sysEnterpriseConfigEntity.getSydwptbm())){
            redisUtils.delete(RedisConstant.LQ_SYDWPTBH+sysEnterpriseConfigEntity.getSydwptbm());
        }
        return baseMapper.deleteById(id);
    }

    /**
    * @Description 新增或更新企业信息
    * @param sysEnterpriseConfig
    * @param userInfo
     * @Return void
    * @Author wangruwei
    * @Date 2023/6/27 16:36
    **/
    @Override
    public String updateEnterpriseInfo(SysEnterpriseConfigEntity sysEnterpriseConfig, UserInfo userInfo) throws ParseException {
        Map<String, String> mqMqp = new HashMap<>();
        String msg = "";
        DynamicContextHolder.push(DbConstant.BASICS_WRITE);
        if(ObjectUtil.isEmpty(sysEnterpriseConfig.getId())){
            log.info("新增企业业务开始");
            log.info("查询是否已存在此税号");
            Long shNum = baseMapper.selectCount(new LambdaQueryWrapper<SysEnterpriseConfigEntity>()
                    .eq(StringUtils.isNotBlank(sysEnterpriseConfig.getCompany()), SysEnterpriseConfigEntity::getCompany, sysEnterpriseConfig.getCompany())
                    .eq(StringUtils.isNotBlank(sysEnterpriseConfig.getNsrsbh()), SysEnterpriseConfigEntity::getNsrsbh, sysEnterpriseConfig.getNsrsbh())
            );
            if(shNum>0){
                return "当前税号已配置接入信息";
            }

            if("1".equals(sysEnterpriseConfig.getJrfs())){
                //验证开通月份是否符合yyyy-MM
                boolean b = DateUtils.checkStrFormat(sysEnterpriseConfig.getNcpgnqyrq(), "yyyy-MM");
                if(!b){
                    return "企业试点开通月份格式必须满足yyyy-MM。例:2023-08";
                }

                log.info("乐企票种处理");
                SysGroupConfigEntity sysGroupConfig = sysGroupConfigDao.selectOne(new QueryWrapper<SysGroupConfigEntity>().eq("company", sysEnterpriseConfig.getCompany()));
                ResponseEntity<?> responseEntity = lqInitService.saveUpdateLqFpzlDm(Arrays.asList(sysEnterpriseConfig), Arrays.asList(sysGroupConfig.getPzxz().split(",")));
                log.info("处理票种全量采集初始化返回结果:{}", JSON.toJSONString(responseEntity));
                if(StringUtils.isNotEmpty(sysEnterpriseConfig.getTspzxz())){
                    log.info("处理特殊票种开始");
                    String tspzxz = sysEnterpriseConfig.getTspzxz();
                    ResponseEntity<?> lqTspzXzResponse = lqInitService.saveUpdateLqTspzXz(Arrays.asList(sysEnterpriseConfig), Arrays.asList(tspzxz.split(",")));
                    log.info("处理特殊票种全量采集初始化返回结果:{}", JSON.toJSONString(lqTspzXzResponse));
                    if(sysEnterpriseConfig.getTspzxz().contains("ZZSDKDJWSPZ")){
                        //代扣代缴完税凭证
                        mqMqp.put("dkdjwspzcsh", "1");
                    }
                    if(sysEnterpriseConfig.getTspzxz().contains("CKZNXFP")){
                        //出口转内销发票
                        mqMqp.put("ckznxfpcsh", "1");
                    }
                    if(sysEnterpriseConfig.getTspzxz().contains("CKZNXJKS")){
                        //出口转内销缴款书
                        mqMqp.put("ckznxjkscsh", "1");
                    }
                }
                //乐企未勾选数据初始化采集
                mqMqp.put("wrzcsh", "1");

                //乐企未勾选退税数据初始化采集
                mqMqp.put("wgxtscsh", "1");

                //乐企未勾选成品油经销企业未勾选库存数据初始化采集
                mqMqp.put("cpyjxqykcgxcsh", "1");

                //乐企未勾选
                if ("1".equals(sysEnterpriseConfig.getSfqyncpdk())) {
                    //乐企农产品待确认数据初始化
                    mqMqp.put("ncpdqrcsh", "1");
                    //乐企农产品税编初始化
                    mqMqp.put("ncpsbcsh", "1");
                    sysEnterpriseConfig.setLqncpywbgsj(new Date());
                }
                if ("1".equals(sysEnterpriseConfig.getSfqyncpjjkc())) {
                    //乐企农产品加计扣除数据初始化
                    mqMqp.put("ncpjjkccsh", "1");
                    sysEnterpriseConfig.setLqncpjjkcqysj(new Date());
                }
            }
            sysEnterpriseConfig.setCzrId(userInfo.getId());
            sysEnterpriseConfig.setCzrMc(userInfo.getUsername());
            sysEnterpriseConfig.setCreateTime(new Date());
            DynamicContextHolder.push(DbConstant.BASICS_WRITE);
            baseMapper.insert(sysEnterpriseConfig);
        }else{
            log.info("修改");

            log.info("查询此税号配置信息");
            SysEnterpriseConfigEntity sec = baseMapper.selectOne(new LambdaQueryWrapper<SysEnterpriseConfigEntity>()
                    .eq(StringUtils.isNotBlank(sysEnterpriseConfig.getCompany()), SysEnterpriseConfigEntity::getCompany, sysEnterpriseConfig.getCompany())
                    .eq(StringUtils.isNotBlank(sysEnterpriseConfig.getNsrsbh()), SysEnterpriseConfigEntity::getNsrsbh, sysEnterpriseConfig.getNsrsbh()));

            if("1".equals(sysEnterpriseConfig.getJrfs())){
                //验证开通月份是否符合yyyy-MM
                boolean b = DateUtils.checkStrFormat(sysEnterpriseConfig.getNcpgnqyrq(), "yyyy-MM");
                if(!b){
                    return "企业试点开通月份格式必须满足yyyy-MM。例:2023-08";
                }
                if(!sec.getJrfs().equals(sysEnterpriseConfig.getJrfs())){
                    log.info("企业从大企业切换到乐企");
                    log.info("乐企票种处理");
                    SysGroupConfigEntity sysGroupConfig = sysGroupConfigDao.selectOne(new QueryWrapper<SysGroupConfigEntity>().eq("company", sysEnterpriseConfig.getCompany()));
                    ResponseEntity<?> responseEntity = lqInitService.saveUpdateLqFpzlDm(Arrays.asList(sysEnterpriseConfig), Arrays.asList(sysGroupConfig.getPzxz().split(",")));
                    log.info("处理票种全量采集初始化返回结果:{}", JSON.toJSONString(responseEntity));

                    log.info("乐企未勾选数据初始化采集");
                    DynamicContextHolder.push(DbConstant.BASICS_WRITE);
                    mqMqp.put("wrzcsh", "1");
                    log.info("乐企未勾选退税数据初始化采集");
                    mqMqp.put("wgxtscsh", "1");
                    //乐企未勾选成品油经销企业未勾选库存数据初始化采集
                    mqMqp.put("cpyjxqykcgxcsh", "1");
                }

                //判断，只要特殊票种有变化(就属于新增)，则放mq
                setMq(sec,sysEnterpriseConfig.getTspzxz(),mqMqp);
                DynamicContextHolder.push(DbConstant.BASICS_WRITE);

                if ("1".equals(sysEnterpriseConfig.getSfqyncpdk())) {
                    if (sec.getLqncpywbgsj() != null) {
                        if (!sysEnterpriseConfig.getSfqyncpdk().equals(sec.getSfqyncpdk()) && DateUtils.isThisTime(sec.getLqncpywbgsj())) {
                            return "当月不允许重复启用农产品功能";
                        }
                        if (!sysEnterpriseConfig.getSfqyncpdk().equals(sec.getSfqyncpdk())) {
                            //启用农产品功能  初始化待处理数据
                            //乐企农产品待确认数据初始化
                            mqMqp.put("ncpdqrcsh", "1");
                            //乐企农产品税编初始化
                            mqMqp.put("ncpsbcsh", "1");
                            sysEnterpriseConfig.setLqncpywbgsj(new Date());
                        }
                    } else {
                        //首次启用农产品功能  初始化待处理数据
                        //乐企农产品待确认数据初始化
                        mqMqp.put("ncpdqrcsh", "1");
                        //乐企农产品税编初始化
                        mqMqp.put("ncpsbcsh", "1");
                        sysEnterpriseConfig.setLqncpywbgsj(new Date());
                    }
                }

                if ("1".equals(sysEnterpriseConfig.getSfqyncpjjkc())) {
                    if (sec.getLqncpjjkcqysj() != null) {
                        if (!sysEnterpriseConfig.getSfqyncpjjkc().equals(sec.getSfqyncpjjkc()) && DateUtils.isThisTime(sec.getLqncpjjkcqysj())) {
                            return "当月不允许重复启用农产品加计扣除功能";
                        }
                        if (!sysEnterpriseConfig.getSfqyncpjjkc().equals(sec.getSfqyncpjjkc())) {
                            //启用农产品加计扣除功能  初始化待处理数据
                            //乐企农产品加计扣除数据初始化
                            mqMqp.put("ncpjjkccsh", "1");
                            sysEnterpriseConfig.setLqncpjjkcqysj(new Date());
                        }
                    } else {
                        //首次启用农产品加计扣除功能  初始化待处理数据
                        //乐企农产品加计扣除数据初始化
                        mqMqp.put("ncpjjkccsh", "1");
                        sysEnterpriseConfig.setLqncpjjkcqysj(new Date());
                    }
                }
                //刷新使用平台编码  对应 直连单位信息 redis缓存
                refreshSyptbmZldw(sysEnterpriseConfig.getSydwptbm(), sysEnterpriseConfig.getZldwqyid());
            }

            //修改
            sysEnterpriseConfig.setCzrId(userInfo.getId());
            sysEnterpriseConfig.setCzrMc(userInfo.getUsername());
            sysEnterpriseConfig.setUpdateTime(new Date());
            baseMapper.updateById(sysEnterpriseConfig);
        }
        mqMqp.put("nsrsbh", sysEnterpriseConfig.getNsrsbh());
        //发送乐企初始化数据下载队列
        rabbitLogsSender.lqcshsjxzSend(JsonUtils.getInstance().toJsonString(mqMqp));
        return msg;
    }

    /**
    * @Description 刷新使用平台编码  对应 直连单位信息 redis缓存
    * @param sydwptbm
    * @param zldwqyid
    * @Return void
    * @Author wangruwei
    * @Date 2024/12/11 16:22
    **/
    @Override
    public void refreshSyptbmZldw(String sydwptbm,String zldwqyid){
        SysLqZldwConfigEntity dbZldw = sysLqZldwConfigDao.selectOne(new LambdaQueryWrapper<SysLqZldwConfigEntity>().eq(SysLqZldwConfigEntity::getZldwqyid, zldwqyid));
        if(ObjectUtils.isNotEmpty(dbZldw)){
            log.info("刷新syptbm对应直连单位的redis");
            ZldwInfo zldwInfo = new ZldwInfo();
            zldwInfo.setJrdwptbm(dbZldw.getJrdwptbm());
            zldwInfo.setLqKey(dbZldw.getLqKey());
            zldwInfo.setApiUrl(dbZldw.getApiUrl());
            redisUtils.set(RedisConstant.LQ_SYDWPTBH+sydwptbm, JSON.toJSONString(zldwInfo),3600);
        }
    }

    /*
    * @Description 原先的企业信息，传入的特殊票种
    * @Return void
    * @Author wangruwei
    * @Date 2023/12/12 15:40
    **/
    private void setMq(SysEnterpriseConfigEntity sysEnterpriseConfig, String tspzxz, Map<String, String> mqMqp) {
        if(StringUtils.isNotEmpty(tspzxz)){
            log.info("处理特殊票种开始");
            //用企业本身的，排除这次修改的，有新增，则走下面的逻辑
            String sysTepzxz = StringUtils.isBlank(sysEnterpriseConfig.getTspzxz())?"":sysEnterpriseConfig.getTspzxz();
            List<String> sysTspz = new ArrayList<>(Arrays.asList(sysTepzxz.split(",")));
            List<String> prarmTspz = new ArrayList<>(Arrays.asList(tspzxz.split(",")));
            prarmTspz.removeAll(sysTspz);
            //如果传入的(123) 大于 现有的(12)，则去除现有的(剩下3)，判断新增的(3)
            if(prarmTspz.size()>0){
                ResponseEntity<?> lqTspzXzResponse = lqInitService.saveUpdateLqTspzXz(Arrays.asList(sysEnterpriseConfig), prarmTspz);
                log.info("处理特殊票种全量采集初始化返回结果:{}", JSON.toJSONString(lqTspzXzResponse));
                if(prarmTspz.contains("ZZSDKDJWSPZ")){
                    //代扣代缴完税凭证
                    mqMqp.put("dkdjwspzcsh", "1");
                }
                if(prarmTspz.contains("CKZNXFP")){
                    //出口转内销发票
                    mqMqp.put("ckznxfpcsh", "1");
                }
                if(prarmTspz.contains("CKZNXJKS")){
                    //出口转内销缴款书
                    mqMqp.put("ckznxjkscsh", "1");
                }
            }
        }
    }

    /**
     * @Description 导入乐企或大企业的数据验证
     * @param company
     * @param jrfs
     * @param detailArray
     * @param userInfo
     * @Return java.lang.String
     * @Author wangruwei
     * @Date 2023/6/28 14:44
     **/
    @Override
    public List<String> importEnterprise(String company, String jrfs, JSONArray detailArray, UserInfo userInfo) throws ParseException {
        DynamicContextHolder.push(DbConstant.BASICS_WRITE);
        List<String> errMsg = new LinkedList<>();
        String msg = "";
        if(LqConfigurerInfo.JRFS_DQY.equals(jrfs)){
            log.info("1,大企业  判断id key是否有值");
            SysGroupConfigEntity sysGroupConfig = sysGroupConfigDao.selectOne(new QueryWrapper<SysGroupConfigEntity>().eq("company", company));
            if(StringUtils.isEmpty(sysGroupConfig.getAceId())||StringUtils.isEmpty(sysGroupConfig.getAceKey())){
                errMsg.add("请到基础配置中录入企业平台接入信息");
                return errMsg;
            }
            //定义传入进来的数据结构
            List<ImportEnterpriseDqyEntity> importEnterpriseDqyList = JSONArray.parseArray(detailArray.toJSONString(), ImportEnterpriseDqyEntity.class);
            log.info("2,判断税号不能为空");
            List<ImportEnterpriseDqyEntity> allEnterprise = importEnterpriseDqyList.stream().filter(e -> StringUtils.isEmpty(e.getNsrsbh())).collect(Collectors.toList());
            if(allEnterprise.size()>0){
                errMsg.add("税号不能为空");
                return errMsg;
            }
            log.info("3,验证本身税号是否重复");
            Map<String, List<ImportEnterpriseDqyEntity>> repeatNsrsbh = importEnterpriseDqyList.stream().collect(Collectors.groupingBy(e -> e.getNsrsbh()));
            Set set = repeatNsrsbh.keySet();
            for (Object key : set) {
                if(repeatNsrsbh.get(key).size()>1){
                    //msg = "税号"+key+",";
                    errMsg.add("税号"+key+"存在重复");
                }
            }
            if(errMsg.size()>0){
                return errMsg;
            }
            log.info("4,校验税号是否为权限内税号");
            List<String> gfshAll = UserInfoUtil.getGfshAll(userInfo.getOrg());
            List<String> allNsrsbh = importEnterpriseDqyList.stream().map(ImportEnterpriseDqyEntity::getNsrsbh).collect(Collectors.toList());
            List<String> importAllSh = new LinkedList(allNsrsbh);
            allNsrsbh.removeAll(gfshAll);
            if(allNsrsbh.size()>0){
                for (String nsrsbh:allNsrsbh) {
                    msg = "税号"+nsrsbh+"不在用户拥有的权限内，";
                    errMsg.add("税号"+nsrsbh+"不在用户拥有的权限内");
                }
                return errMsg;
            }

            if(errMsg.size()>0){
                return errMsg;
            }
            /**
             * @Description 如果库里有，则删除，以导入的数据重新走入库
             * @Author wangruwei
             * @Date 2024/7/25 17:15
             **/
            //修改时间
            Date updateDate = null;
            log.info("5,校验税号是否存在（如果库里有，则删除，以导入的数据重新走入库）");
            for(String nsrsbh : importAllSh){
                Long qySize = sysEnterpriseConfigDao.selectCount(new QueryWrapper<SysEnterpriseConfigEntity>()
                        .eq("company", company)
                        .eq("nsrsbh", nsrsbh)
                );
                if(qySize>0){
                    updateDate = new Date();
                    sysEnterpriseConfigDao.delete(new LambdaQueryWrapper<SysEnterpriseConfigEntity>().eq(SysEnterpriseConfigEntity::getCompany, company)
                            .eq(SysEnterpriseConfigEntity::getNsrsbh, nsrsbh));
                }
            }

            log.info("6,入库");
            for (ImportEnterpriseDqyEntity importDqy:importEnterpriseDqyList) {
                SysEnterpriseConfigEntity insert = new SysEnterpriseConfigEntity();
                insert.setCompany(company);
                insert.setNsrsbh(importDqy.getNsrsbh());
                insert.setNsrmc(userInfo.getOrg().stream().filter(e->importDqy.getNsrsbh().equals(e.getTaxno())).findFirst().get().getTaxname());
                insert.setJrfs("0");
                insert.setSfcy(StringUtils.isBlank(importDqy.getSfcy())?"1":("查验".equals(importDqy.getSfcy())?"1":"0"));
                insert.setSfcj(StringUtils.isBlank(importDqy.getSfcj())?"1":("采集".equals(importDqy.getSfcj())?"1":"0"));
                insert.setCzrMc(userInfo.getUsername());
                insert.setCzrId(userInfo.getId());
                if(updateDate==null){
                    insert.setCreateTime(new Date());
                }else{
                    insert.setCreateTime(updateDate);
                }
                insert.setUpdateTime(updateDate);
                updateEnterpriseInfo(insert, userInfo);
                //baseMapper.insert(insert);
            }
        }else{
            //乐企

            //定义传入进来的数据结构
            List<ImportEnterpriseLqEntity> importEnterpriseLqList = JSONArray.parseArray(detailArray.toJSONString(), ImportEnterpriseLqEntity.class);
            log.info("1,判断税号和使用平台编码等必填项都不能为空");
            List<ImportEnterpriseLqEntity> allEnterprise = importEnterpriseLqList.stream().filter(e -> StringUtils.isEmpty(e.getZlNsrsbh())||StringUtils.isEmpty(e.getNsrsbh())||StringUtils.isEmpty(e.getSydwptbm())
                   ).collect(Collectors.toList());
            if(allEnterprise.size()>0){
                errMsg.add("直连单位税号、接入单位税号、接入单位乐企ID必填");
                return errMsg;
            }
            importEnterpriseLqList.stream().forEach(e->{
                if(StringUtils.isEmpty(e.getNcpgnqyrq())){
                    e.setNcpgnqyrq(DateUtils.getMonthByMonth(-6));
                }
                if(StringUtils.isEmpty(e.getSfqyncpdk())){
                    e.setSfqyncpdk("含农产品业务");
                }
            });
            log.info("2,月份格式必须正确");
            List<ImportEnterpriseLqEntity> rqFormat = importEnterpriseLqList.stream().filter(e -> !DateUtils.checkStrFormat(e.getNcpgnqyrq(), "yyyy-MM")).collect(Collectors.toList());
            if(rqFormat.size()>0){
                errMsg.add("月份格式必须为yyyy-MM，例:2023-02");
                return errMsg;
            }

            log.info("3,验证本身税号是否重复");
            Map<String, List<ImportEnterpriseLqEntity>> repeatNsrsbh = importEnterpriseLqList.stream().collect(Collectors.groupingBy(e -> e.getNsrsbh()));
            Set set = repeatNsrsbh.keySet();
            for (Object key : set) {
                if(repeatNsrsbh.get(key).size()>1){
                    msg = "税号"+key+",";
                    errMsg.add("税号"+key+"存在重复");
                }
            }
            if(errMsg.size()>0){
                return errMsg;
            }
            log.info("4,校验税号是否为权限内税号");
            List<String> gfshAll = UserInfoUtil.getGfshAll(userInfo.getOrg());

            List<String> allNsrsbh = importEnterpriseLqList.stream().map(ImportEnterpriseLqEntity::getNsrsbh).collect(Collectors.toList());
            List<String> importAllSh = new ArrayList<>(allNsrsbh);
            allNsrsbh.removeAll(gfshAll);
            if(allNsrsbh.size()>0){
                for (String nsrsbh:allNsrsbh) {
                    msg = "税号"+nsrsbh+"不在用户拥有的权限内，";
                    errMsg.add("税号"+nsrsbh+"不在用户拥有的权限内");
                }
                if(errMsg.size()>0){
                    return errMsg;
                }
            }

            if(errMsg.size()>0){
                return errMsg;
            }

            /**
            * @Description 如果库里有，则删除，以导入的数据重新走入库
            * @Author wangruwei
            * @Date 2024/7/25 17:15
            **/
            //修改时间
            Date updateDate = null;
            log.info("5,直连单位是否存在。再校验税号是否存在（如果库里有，则删除，以导入的数据重新走入库）。");
            List<String> zldwList = importEnterpriseLqList.stream().map(ImportEnterpriseLqEntity::getZlNsrsbh).distinct().collect(Collectors.toList());
            for(String nsrsbh : zldwList){
                Long zlSize = sysLqZldwConfigDao.selectCount(new LambdaQueryWrapper<SysLqZldwConfigEntity>()
                        .eq(SysLqZldwConfigEntity::getNsrsbh, nsrsbh)
                );
                if(zlSize==0){
                    errMsg.add("直连单位税号"+nsrsbh+"不存在");
                }
            }
            if(errMsg.size()>0){
                return errMsg;
            }
            for(String nsrsbh : importAllSh){
                Long qySize = sysEnterpriseConfigDao.selectCount(new QueryWrapper<SysEnterpriseConfigEntity>()
                        .eq("company", company)
                        .eq("nsrsbh", nsrsbh)
                );
                if(qySize>0){
                    updateDate = new Date();
                    sysEnterpriseConfigDao.delete(new LambdaQueryWrapper<SysEnterpriseConfigEntity>().eq(SysEnterpriseConfigEntity::getCompany, company)
                            .eq(SysEnterpriseConfigEntity::getNsrsbh, nsrsbh));
                }
            }

            //农产品业务逻辑校验
            int hh = 0;
            for (ImportEnterpriseLqEntity iele : importEnterpriseLqList) {
                hh++;
                /*if ("含农产品业务".equals(iele.getSfqyncpdk())) {
                    if (StringUtils.isBlank(iele.getJdncpgnqysj())) {
                        errMsg.add("第" + hh + "行，当开启农产品功能时，成为农产品试点企业月份必填");
                    }else{
                        //验证日期是否yyyy-MM格式
                        boolean checkDate = DateUtils.checkStrFormat(iele.getJdncpgnqysj(), "yyyy-MM");
                        if(!checkDate){
                            errMsg.add("第" + hh + "行，成为农产品试点企业月份格式不正确，应符合yyyy-MM格式，例:2023-02");
                        }
                    }
                }*/
                if ("无农产品业务".equals(iele.getSfqyncpdk())) {
                    if (StringUtils.isNotBlank(iele.getSfqyncpjjkc())&&"启用".equals(iele.getSfqyncpjjkc())) {
                        errMsg.add("第" + hh + "行，当不开启农产品功能时，农产品加计扣除功能必须为空或者不启用");
                    }
                }
            }
            if(errMsg.size()>0){
                return errMsg;
            }

            log.info("6,入库");
            for (ImportEnterpriseLqEntity importLq:importEnterpriseLqList) {
                SysEnterpriseConfigEntity insert = new SysEnterpriseConfigEntity();
                SysLqZldwConfigEntity dbzldw = sysLqZldwConfigDao.selectOne(new LambdaQueryWrapper<SysLqZldwConfigEntity>().eq(SysLqZldwConfigEntity::getNsrsbh, importLq.getZlNsrsbh()));
                insert.setCompany(company);
                insert.setNsrsbh(importLq.getNsrsbh());
                insert.setNsrmc(userInfo.getOrg().stream().filter(e->importLq.getNsrsbh().equals(e.getTaxno())).findFirst().get().getTaxname());
                insert.setJrfs("1");
                insert.setSydwptbm(importLq.getSydwptbm());
                if ("含农产品业务".equals(importLq.getSfqyncpdk())) {
                    insert.setSfqyncpdk("1");
                }
                if ("无农产品业务".equals(importLq.getSfqyncpdk())) {
                    insert.setSfqyncpdk("0");
                }
                if (StringUtils.isNotBlank(importLq.getNcpgnqyrq())) {
                    insert.setNcpgnqyrq(importLq.getNcpgnqyrq());
                }
                if (StringUtils.isNotBlank(importLq.getSfqyncpjjkc())) {
                    if ("启用".equals(importLq.getSfqyncpjjkc())) {
                        insert.setSfqyncpjjkc("1");
                    }
                    if ("不启用".equals(importLq.getSfqyncpjjkc())) {
                        insert.setSfqyncpjjkc("0");
                    }
                }
                String tspzxz = dealTspzxz(importLq);
                insert.setTspzxz(tspzxz);
                insert.setCzrMc(userInfo.getUsername());
                insert.setCzrId(userInfo.getId());
                insert.setSydwqyid(importLq.getNsrsbh());
                insert.setZldwqyid(dbzldw.getZldwqyid());
                if(updateDate==null){
                    insert.setCreateTime(new Date());
                }else{
                    insert.setCreateTime(updateDate);
                }
                insert.setUpdateTime(updateDate);
                updateEnterpriseInfo(insert, userInfo);
                //baseMapper.insert(insert);
            }
        }
        return errMsg;
    }

    private String dealTspzxz(ImportEnterpriseLqEntity importLq) {
        String tspzxz = "";
        if(StringUtils.isNotEmpty(importLq.getZzsdkdjwspz())&&"启用".equals(importLq.getZzsdkdjwspz())){
            tspzxz += "ZZSDKDJWSPZ,";
        }
        if(StringUtils.isNotEmpty(importLq.getCkznxfp())&&"启用".equals(importLq.getCkznxfp())){
            tspzxz += "CKZNXFP,";
        }
        if(StringUtils.isNotEmpty(importLq.getCkznxjks())&&"启用".equals(importLq.getCkznxjks())){
            tspzxz += "CKZNXJKS,";
        }
        if(StringUtils.isNotBlank(tspzxz)){
            tspzxz = tspzxz.substring(0, tspzxz.length()-1);
        }
        return tspzxz;
    }

    @Override
    public SysEnterpriseConfigEntity getEnterpriseInfoByNsrsbh(Map<String, String> params) {
        String company = params.get("company");
        String nsrsbh = params.get("nsrsbh");
        SysEnterpriseConfigEntity sysEnterpriseConfigEntity = baseMapper.selectOne(new LambdaQueryWrapper<SysEnterpriseConfigEntity>()
                .eq(StringUtils.isNotBlank(company), SysEnterpriseConfigEntity::getCompany, company)
                .eq(StringUtils.isNotBlank(nsrsbh), SysEnterpriseConfigEntity::getNsrsbh, nsrsbh)
        );
        return sysEnterpriseConfigEntity;
    }

    /**
     * @Description 筛选企业信息
     * @param gfshList
     * @param jrfs 0大企业  1乐企
     * @Return java.util.List<com.dxhy.api.model.config.sys.SysEnterpriseConfigEntity>
     * @Author wangruwei
     * @Date 2024/3/25 16:30
     **/
    @Override
    public List<SysEnterpriseConfigEntity> selectEnterpriseList(List<String> gfshList, String jrfs) {
        return baseMapper.selectList(new LambdaQueryWrapper<SysEnterpriseConfigEntity>()
                .in(!CollectionUtils.isEmpty(gfshList), SysEnterpriseConfigEntity::getNsrsbh,gfshList)
                .eq(StringUtils.isNotBlank(jrfs),SysEnterpriseConfigEntity::getJrfs, jrfs)
        );
    }

    /**
     * @Description 根据纳税人识别号判断接入方式。 空则没有税号，0大企业   1乐企
     * @param nsrsbh
     * @Return java.lang.String
     * @Author wangruwei
     * @Date 2025/1/2 10:28
     **/
    @Override
    public String getEnterpriseJrfs(String nsrsbh) {
        String jrfs = "";
        SysEnterpriseConfigEntity sysEnterpriseConfigEntity = baseMapper.selectOne(new LambdaQueryWrapper<SysEnterpriseConfigEntity>().eq(SysEnterpriseConfigEntity::getNsrsbh, nsrsbh).select(SysEnterpriseConfigEntity::getJrfs));
        if(ObjectUtils.isNotEmpty(sysEnterpriseConfigEntity)){
            jrfs = sysEnterpriseConfigEntity.getJrfs();
        }
        return jrfs;
    }
}
