package cn.cecep.talroad.service.impl;

import cn.cecep.talroad.common.core.constant.TokenConstants;
import cn.cecep.talroad.common.core.utils.DateUtils;
import cn.cecep.talroad.common.security.utils.SecurityUtils;
import cn.cecep.talroad.domain.AmProblemFi;
import cn.cecep.talroad.domain.BEnterpriseRiskAssessmentLast;
import cn.cecep.talroad.domain.BMainThreeSupervisionEnforc;
import cn.cecep.talroad.domain.PcFactory;
import cn.cecep.talroad.domain.analysis.SRaFactoryTransferRateAnalysis;
import cn.cecep.talroad.domain.analysis.SRaRealTimeAnalysisRun;
import cn.cecep.talroad.domain.analysis.SRaSelfMonitoringData;
import cn.cecep.talroad.enums.EnvironmentalCodingGradeEnum;
import cn.cecep.talroad.mapper.BEnterpriseRiskAssessmentLastMapper;
import cn.cecep.talroad.mapper.EnvironmentalCodingMapper;
import cn.cecep.talroad.mapper.PcFactoryMapper;
import cn.cecep.talroad.service.EnvironmentalCodingService;
import cn.cecep.talroad.service.IBMainThreeSupervisionEnforcService;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.sql.Timestamp;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @className: EnvironmentalCodingServiceImpl
 * @description: TODO 类描述
 * @author: Mr.Yanghongtao
 * @date: 2023/04/08 1:16 PM
 * @Company: Copyright© [2023/04/08 1:16 PM] by [Mr.Yanghongtao]
 **/
@Service
public class EnvironmentalCodingServiceImpl implements EnvironmentalCodingService {


    @Autowired
    private EnvironmentalCodingMapper environmentalCodingMapper;

    @Autowired
    private BEnterpriseRiskAssessmentLastMapper bEnterpriseRiskAssessmentLastMapper;

    @Autowired
    private PcFactoryMapper pcFactoryMapper;

    @Autowired
    private IBMainThreeSupervisionEnforcService ibMainThreeSupervisionEnforcServiceImpl;

    /**
     * @Author: Mr.Yanghongtao
     * @data: 2023/4/8 1:43 PM
     * @Deseription:
     * @Params: dateTime yyyy-MM-dd
     * @Return: void
     * @Throws:
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void scanYesterdayDeductionPoints(String dateTime) {
        Date nowTime = DateUtils.parseDate(DateUtils.parseDateToStr("yyyy-MM-dd HH:mm:00", new Date()));
        String startTime = DateUtils.parseDateToStr("yyyy-MM-dd 00:00:00", nowTime);
        String endTime = DateUtils.parseDateToStr("yyyy-MM-dd 23:59:59", nowTime);
        String time = DateUtils.parseDateToStr("yyyy-MM-dd", nowTime);
        // 取出昨日日期
        if (StringUtils.isNotEmpty(dateTime)) {
            startTime = dateTime + " 00:00:00";
            endTime = dateTime + " 23:59:59";
            time = dateTime;
        }

        List<BEnterpriseRiskAssessmentLast> toDaylist = new ArrayList<>();
        List<SRaFactoryTransferRateAnalysis> tmpAnalysis = new ArrayList<>();
        // 查询"三级联动"不多次扣分的
        List<BMainThreeSupervisionEnforc> sjldIsGradeFalse = environmentalCodingMapper.selectListByTime(Timestamp.valueOf(startTime), Timestamp.valueOf(endTime), EnvironmentalCodingGradeEnum.getNameListByType("SJLD", false));
        sjldIsGradeFalse.forEach(x -> {
            BEnterpriseRiskAssessmentLast last = new BEnterpriseRiskAssessmentLast();
            last.setFactoryId(x.getFactoryId());
            // 类型
            last.setProblemExist(x.getTaskName());
            // 是否多次扣分,0-不多次扣分，1-多次扣分
            last.setIsRepeatedGrade(0);
            // 存业务ID
            last.setBusinessId(x.getTaskId());
            // 扣分
            last.setScore(EnvironmentalCodingGradeEnum.getGradeByName(x.getTaskName()));
            last.setCreateTime(nowTime);
            toDaylist.add(last);
        });

        // 查询"三级联动"多次扣分的
        List<BMainThreeSupervisionEnforc> sjldIsGradeTrue = environmentalCodingMapper.selectListByTime(Timestamp.valueOf(startTime), Timestamp.valueOf(endTime), EnvironmentalCodingGradeEnum.getNameListByType("SJLD", true));
        sjldIsGradeTrue.forEach(x -> {
            BEnterpriseRiskAssessmentLast last = new BEnterpriseRiskAssessmentLast();
            last.setFactoryId(x.getFactoryId());
            // 类型
            last.setProblemExist(x.getTaskName());
            // 是否多次扣分,0-不多次扣分，1-多次扣分
            last.setIsRepeatedGrade(1);
            // 存业务ID
            last.setBusinessId(x.getTaskId());
            // 扣分
            last.setScore(EnvironmentalCodingGradeEnum.getGradeByName(x.getTaskName()));
            last.setCreateTime(nowTime);
            toDaylist.add(last);
        });

        // 查询"关联分析系统" 不多次扣分的
        List<EnvironmentalCodingGradeEnum> glfxList = EnvironmentalCodingGradeEnum.getListByCode("GLFXXT", null);
        String finalStartTime = startTime;
        String finalEndTime = endTime;
        String finalTime = time;
        glfxList.forEach(x -> {
            if ("GLFXXT_01".equals(x.getCode())) {
                // 查询 排污单位自行监测数据超标
                List<SRaSelfMonitoringData> amProblemFisSjzl = environmentalCodingMapper.selectSRaSelfMonitoringDataList(Timestamp.valueOf(finalStartTime), Timestamp.valueOf(finalEndTime));
                amProblemFisSjzl.forEach(y -> {
                    BEnterpriseRiskAssessmentLast last = new BEnterpriseRiskAssessmentLast();
                    last.setFactoryId(y.getFactoryId());
                    // 类型
                    last.setProblemExist(x.getName());
                    // 是否多次扣分
                    last.setIsRepeatedGrade(x.getIsGrade() ? 1 : 0);
                    // 存业务ID
                    last.setBusinessId(y.getDataId() + "," + y.getFactoryId() + "," + y.getMonitorId());
                    // 存扣分项
                    last.setRemark(y.getPollutantsCode());
                    // 扣分
                    last.setScore(EnvironmentalCodingGradeEnum.getGradeByName(x.getName()));
                    last.setCreateTime(nowTime);
                    toDaylist.add(last);
                });
            } else if ("GLFXXT_02".equals(x.getCode())) {
                // 查询数据质量异常
                List<AmProblemFi> amProblemFisSjzl = environmentalCodingMapper.selectMamProblemFiListNew(Timestamp.valueOf(finalStartTime), Timestamp.valueOf(finalEndTime), Arrays.asList(new String[]{"006001", "006002", "006003", "006004"}), "1");
                amProblemFisSjzl.forEach(y -> {
                    BEnterpriseRiskAssessmentLast last = new BEnterpriseRiskAssessmentLast();
                    last.setFactoryId(y.getFactoryId());
                    // 类型
                    last.setProblemExist(x.getName());
                    // 是否多次扣分
                    last.setIsRepeatedGrade(x.getIsGrade() ? 1 : 0);
                    // 存业务ID
                    last.setBusinessId(y.getId());
                    // 扣分
                    last.setScore(EnvironmentalCodingGradeEnum.getGradeByName(x.getName()));
                    last.setCreateTime(nowTime);
                    toDaylist.add(last);
                });
            } else if ("GLFXXT_03".equals(x.getCode())) {
                // 查询每日数据传输率低于75%的问题
                List<SRaFactoryTransferRateAnalysis> sRaFactoryTransferRateAnalyses = environmentalCodingMapper.selectSRaFactoryTransferRateAnalysisList(finalTime);
                sRaFactoryTransferRateAnalyses.forEach(y -> {
                    // 判断 分表计电-传输率
                    if (y.getElecTransmissionRate().compareTo(new BigDecimal(75)) == -1) {
                        processSRaFactoryTransferRateAnalysis(x, y, nowTime, "分表计电", toDaylist);
                    }
                    // 判断 无组织管控-分钟数据-传输率
                    if (y.getUnorganizedTransmissionMinuteRate().compareTo(new BigDecimal(75)) == -1) {
                        processSRaFactoryTransferRateAnalysis(x, y, nowTime, "无组织管控-分钟数据", toDaylist);
                    }
                    // 判断 无组织管控-小时数据-传输率
                    if (y.getUnorganizedTransmissionHourRate().compareTo(new BigDecimal(75)) == -1) {
                        processSRaFactoryTransferRateAnalysis(x, y, nowTime, "无组织管控-小时数据", toDaylist);
                    }
                    // 判断 无组织管控-日数据-传输率
                    if (y.getUnorganizedTransmissionDayRate().compareTo(new BigDecimal(75)) == -1) {
                        processSRaFactoryTransferRateAnalysis(x, y, nowTime, "无组织管控-日数据", toDaylist);
                    }
                    // 判断 dcs监控数据-传输率
                    if (y.getDcsTransmissionRate().compareTo(new BigDecimal(75)) == -1) {
                        processSRaFactoryTransferRateAnalysis(x, y, nowTime, "dcs监控数据-传输率", toDaylist);
                    }
                    // 判断 网格化数据-分钟数据-传输率
                    if (y.getGriddedTransmissionMinuteRate().compareTo(new BigDecimal(75)) == -1) {
                        processSRaFactoryTransferRateAnalysis(x, y, nowTime, "网格化数据-分钟数据", toDaylist);
                    }
                    // 判断 网格化数据-小时数据-传输率
                    if (y.getGriddedTransmissionHourRate().compareTo(new BigDecimal(75)) == -1) {
                        processSRaFactoryTransferRateAnalysis(x, y, nowTime, "网格化数据-小时数据", toDaylist);
                    }
                    // 判断 网格化数据-日数据-传输率
                    if (y.getGriddedTransmissionDayRate().compareTo(new BigDecimal(75)) == -1) {
                        processSRaFactoryTransferRateAnalysis(x, y, nowTime, "网格化数据-日数据", toDaylist);
                    }
                    // 判断 在线监测-分钟数据-传输率
                    if (y.getOnlineMonitoringMinuteRate().compareTo(new BigDecimal(75)) == -1) {
                        processSRaFactoryTransferRateAnalysis(x, y, nowTime, "在线监测-分钟数据", toDaylist);
                    }
                    // 判断 在线监测-小时数据-传输率
                    if (y.getOnlineMonitoringHourRate().compareTo(new BigDecimal(75)) == -1) {
                        processSRaFactoryTransferRateAnalysis(x, y, nowTime, "在线监测-小时数据", toDaylist);
                    }
                    // 判断 在线监测-日数据-传输率
                    if (y.getOnlineMonitoringDayRate().compareTo(new BigDecimal(75)) == -1) {
                        processSRaFactoryTransferRateAnalysis(x, y, nowTime, "在线监测-日数据", toDaylist);
                    }
                });
                tmpAnalysis.addAll(sRaFactoryTransferRateAnalyses);
            } else if ("GLFXXT_04".equals(x.getCode())) {
                // 查询启停问题
                List<AmProblemFi> amProblemFis = environmentalCodingMapper.selectMamProblemFiList(Timestamp.valueOf(finalStartTime), Timestamp.valueOf(finalEndTime), "002002", "1");
                amProblemFis.forEach(y -> {
                    BEnterpriseRiskAssessmentLast last = new BEnterpriseRiskAssessmentLast();
                    last.setFactoryId(y.getFactoryId());
                    // 类型
                    last.setProblemExist(x.getName());
                    // 是否多次扣分
                    last.setIsRepeatedGrade(x.getIsGrade() ? 1 : 0);
                    // 存业务ID
                    last.setBusinessId(y.getId());
                    // 扣分
                    last.setScore(EnvironmentalCodingGradeEnum.getGradeByName(x.getName()));
                    last.setCreateTime(nowTime);
                    toDaylist.add(last);
                });
            }


        });


        // 查询"在线监测系统"
        List<AmProblemFi> amProblemFisWry = environmentalCodingMapper.selectMamProblemFiList(Timestamp.valueOf(startTime), Timestamp.valueOf(endTime), "003003", "3");
        amProblemFisWry.forEach(x -> {
            BEnterpriseRiskAssessmentLast last = new BEnterpriseRiskAssessmentLast();
            last.setFactoryId(x.getFactoryId());
            // 类型
            last.setProblemExist(EnvironmentalCodingGradeEnum.ZXJCXT_01.getName());
            // 是否多次扣分,0-不多次扣分，1-多次扣分
            last.setIsRepeatedGrade(0);
            // 存业务ID
            last.setRemark(x.getId());
            // 扣分
            last.setScore(EnvironmentalCodingGradeEnum.ZXJCXT_01.getGrade());
            last.setCreateTime(nowTime);
            toDaylist.add(last);
        });

        // 查询"分表计电系统" 分表计电发生预警问题 治理设施停运 problemType =  004001001 ， problemSources = 1
        List<AmProblemFi> amProblemFisElec = environmentalCodingMapper.selectMamProblemFiList(Timestamp.valueOf(startTime), Timestamp.valueOf(endTime), "004001001", "1");
        amProblemFisElec.forEach(x -> {
            BEnterpriseRiskAssessmentLast last = new BEnterpriseRiskAssessmentLast();
            last.setFactoryId(x.getFactoryId());
            // 类型
            last.setProblemExist(EnvironmentalCodingGradeEnum.FBJDXT_01.getName());
            // 是否多次扣分
            last.setIsRepeatedGrade(1);
            // 存业务ID
            last.setBusinessId(x.getId());
            // 扣分
            last.setScore(EnvironmentalCodingGradeEnum.FBJDXT_01.getGrade());
            last.setCreateTime(nowTime);
            toDaylist.add(last);
        });


        // 处理之前已分析的数据
        List<BEnterpriseRiskAssessmentLast> bEnterpriseRiskAssessmentLasts = processYesterdayGrade(tmpAnalysis, startTime, endTime);
        // 查询 执法系统
//        getXianheGetTaskAccount(bEnterpriseRiskAssessmentLasts,nowTime);
        // 计算今日的分数 加上昨日未处理的问题
        toDaylist.addAll(bEnterpriseRiskAssessmentLasts);
        // 根据企业进行分组 k为企业ID
        Map<String, List<BEnterpriseRiskAssessmentLast>> collect = toDaylist.stream().collect(Collectors.groupingBy(BEnterpriseRiskAssessmentLast::getFactoryId));
        // 查询所有企业
        List<PcFactory> pcFactories = pcFactoryMapper.selectList(new LambdaQueryWrapper<PcFactory>());
        pcFactories.forEach(x -> {
            // 要计算分数的企业里，可能不全，所以要查出所有企业惯里
            if (!collect.containsKey(x.getId())) {
                collect.put(x.getId(), new ArrayList<>());
            }
        });
        List<PcFactory> updatePcFactory = new ArrayList<>();
        collect.forEach((k, v) -> {
            // 根据能否重复扣分进行分组
            Map<Integer, List<BEnterpriseRiskAssessmentLast>> collect1 = v.stream().collect(Collectors.groupingBy(BEnterpriseRiskAssessmentLast::getIsRepeatedGrade));
            // 获取不可重复扣分的内容
            List<BEnterpriseRiskAssessmentLast> bEnterpriseRiskAssessmentLasts1 = Optional.ofNullable(collect1.get(0)).orElse(new ArrayList<>());
            // 根据类型进行分组，重复类型只保留一个进行扣分即可
            Map<String, Integer> collect2 = bEnterpriseRiskAssessmentLasts1.stream().collect(Collectors.toMap(BEnterpriseRiskAssessmentLast::getProblemExist, BEnterpriseRiskAssessmentLast::getScore, (oldValue, newValue) -> newValue));
            // 计算不可重复扣分项，今日要扣的分数
            Integer reduce = collect2.values().stream().reduce(Integer::sum).orElse(0);
            // 计算重复扣分项，今日要扣的分数
            List<BEnterpriseRiskAssessmentLast> bEnterpriseRiskAssessmentLasts2 = Optional.ofNullable(collect1.get(1)).orElse(new ArrayList<>());
            Integer integer = bEnterpriseRiskAssessmentLasts2.stream().map(x -> x.getScore()).reduce(Integer::sum).orElse(0);
            ;
            int grade = 100 - reduce - integer;
            PcFactory tmpFactory = new PcFactory();
            tmpFactory.setId(k);
            tmpFactory.setScore(grade);
            // 更新企业的分数
            updatePcFactory.add(tmpFactory);
        });
        // 要存入的问题企业问题 批量插入
        List<List<BEnterpriseRiskAssessmentLast>> dataList = subList(toDaylist, 1000);
        for (int i = 0; i < dataList.size(); i++) {
            bEnterpriseRiskAssessmentLastMapper.insertBEnterpriseRiskAssessmentLasts(dataList.get(i));
        }

        // 更新企业的分数 批量插入数据库
        List<List<PcFactory>> dataList1 = subList(updatePcFactory, 1000);
        for (int i = 0; i < dataList1.size(); i++) {
            pcFactoryMapper.updateScoreBatch(dataList1.get(i));
        }
    }

    private void processSRaFactoryTransferRateAnalysis(EnvironmentalCodingGradeEnum x, SRaFactoryTransferRateAnalysis y, Date nowTime, String remark, List<BEnterpriseRiskAssessmentLast> toDaylist) {
        BEnterpriseRiskAssessmentLast last = new BEnterpriseRiskAssessmentLast();
        last.setFactoryId(y.getFactoryId());
        // 类型
        last.setProblemExist(x.getName());
        // 是否多次扣分
        last.setIsRepeatedGrade(x.getIsGrade() ? 1 : 0);
        // 存业务ID
        last.setBusinessId(y.getId() + "," + y.getFactoryId());
        // 存具体扣分项
        last.setRemark(remark);
        // 扣分
        last.setScore(EnvironmentalCodingGradeEnum.getGradeByName(x.getName()));
        last.setCreateTime(nowTime);
        toDaylist.add(last);
    }

    private List<BEnterpriseRiskAssessmentLast> processYesterdayGrade(List<SRaFactoryTransferRateAnalysis> tmpAnalsis, String startTime, String endTime) {
        String now = startTime.substring(0,10) + " " + DateUtils.parseDateToStr("HH:mm:ss",new Date());
        Date nowTime = DateUtils.dateTime("yyyy-MM-dd HH:mm:ss",now);
        // 查询昨日的扣分项，循环，查询是否有处理过的问题 (改一下，不能只查询昨日的扣分项，如果昨日的扣分没处理，那第三日的时候就查不到昨日信息了)
        List<BEnterpriseRiskAssessmentLast> bEnterpriseRiskAssessmentLasts = bEnterpriseRiskAssessmentLastMapper.selectList(
                new LambdaQueryWrapper<>());
        List<Long> ids = new ArrayList<>();
        // 关联分析系统今日查询的 每日数据传输率低于75 的数据
        List<String> transferFactoryIds = tmpAnalsis.stream().map(SRaFactoryTransferRateAnalysis::getFactoryId).collect(Collectors.toList());
        // 过滤一下 排污单位自行监测数据超标的数据 获取监测点ID
        List<String> selfMonitorsIds = bEnterpriseRiskAssessmentLasts.stream().filter(x -> EnvironmentalCodingGradeEnum.GLFXXT_01.getName().equals(x.getProblemExist())).map(x -> x.getRemark().split(",")[2]).collect(Collectors.toList());
        // 通过监测点ID和日期，查询出最新的数据
        List<SRaSelfMonitoringData> tmpSelfMonitoringDatas = environmentalCodingMapper.selectSRaSelfMonitoringDataListByParams(selfMonitorsIds, Timestamp.valueOf(startTime), Timestamp.valueOf(endTime));
        Map<String, SRaSelfMonitoringData> tmpSelfMonitoringDatasMap = tmpSelfMonitoringDatas.stream().collect(Collectors.toMap(x -> {
            return x.getFactoryId() + "-" + x.getMonitorId() + "-" + x.getPollutantsCode();
        }, Function.identity(), (oldValue, newValue) -> oldValue));

        bEnterpriseRiskAssessmentLasts.forEach(x -> {
            // 查询 "三监联动系统" 是否已经处理
            if ("SJLD".equals(EnvironmentalCodingGradeEnum.getTypeByName(x.getProblemExist()))) {
                BMainThreeSupervisionEnforc bMainThreeSupervisionEnforc = environmentalCodingMapper.selectBMainThreeSupervisionEnforcById(x.getBusinessId());
                // 任务状态;字典bus_task_status(任务状态（0=办理中 5=已办结 9=已归档)
                if ("5".equals(bMainThreeSupervisionEnforc.getTaskStatus()) || "9".equals(bMainThreeSupervisionEnforc.getTaskStatus())) {
                    ids.add(x.getRiskId());
                }
            }
            // 查询"在线监测系统" 、"分表计电系统" "关联分析系统" 是否已经处理
            List kyes = Arrays.asList(new String[]{"ZXJCXT_01", "FBJDXT_01", "GLFXXT_02", "GLFXXT_04"});
            if (kyes.contains(EnvironmentalCodingGradeEnum.getCodeByName(x.getProblemExist()))) {
                AmProblemFi amProblemFi = environmentalCodingMapper.selectMamProblemFiById(x.getBusinessId());
                // 当前时间大于等于结束时间 代表报警已结束
                if (amProblemFi.getAnalyseTimeEnd().getTime() < nowTime.getTime()) {
                    ids.add(x.getRiskId());
                }
            }
            // 判断 "关联分析系统-每日数据传输率低于75%"
            if ("GLFXXT_03".equals(EnvironmentalCodingGradeEnum.getCodeByName(x.getProblemExist()))) {
                if (transferFactoryIds.contains(x.getBusinessId().split(",")[1])) {
                    ids.add(x.getRiskId());
                }
            }
            // 判断 "关联分析系统-排污单位自行监测数据超标"
            if ("GLFXXT_01".equals(EnvironmentalCodingGradeEnum.getCodeByName(x.getProblemExist()))) {
                // key = 企业ID + 监测点ID + 污染物Code
                String key = x.getBusinessId().split(",")[1] + x.getBusinessId().split(",")[2] + x.getRemark();
                if (tmpSelfMonitoringDatasMap.containsKey(key)) {
                    // 查询最新超标的污染类型，如果有数据，就使用新的数据去判定是否超标，老的数据直接删掉
                    ids.add(x.getRiskId());
                }
            }

        });

        if (ids.size() > 0) {
            bEnterpriseRiskAssessmentLastMapper.deleteBatchIds(ids);
        }

        // 使用迭代器删除 bEnterpriseRiskAssessmentLasts
        bEnterpriseRiskAssessmentLasts.removeIf(x -> ids.contains(x.getRiskId()));
        return bEnterpriseRiskAssessmentLasts;
    }

    /**
     * 截取List
     *
     * @param tList
     * @param subNum
     * @param <T>
     * @return
     */
    public static <T> List<List<T>> subList(List<T> tList, Integer subNum) {
        // 新的截取到的list集合
        List<List<T>> tNewList = new ArrayList<List<T>>();
        // 要截取的下标上限
        Integer priIndex = 0;
        // 要截取的下标下限
        Integer lastIndex = 0;
        // 每次插入list的数量
        // Integer subNum = 500;
        // 查询出来list的总数目
        Integer totalNum = tList.size();
        // 总共需要插入的次数
        Integer insertTimes = totalNum / subNum;
        List<T> subNewList = new ArrayList<T>();
        for (int i = 0; i <= insertTimes; i++) {
            // [0--20) [20 --40) [40---60) [60---80) [80---100)
            priIndex = subNum * i;
            lastIndex = priIndex + subNum;
            // 判断是否是最后一次
            if (i == insertTimes) {
                //logger.info("最后一次截取："+priIndex + "," + lastIndex);
                subNewList = tList.subList(priIndex, tList.size());
            } else {
                // 非最后一次
                subNewList = tList.subList(priIndex, lastIndex);
            }
            if (subNewList.size() > 0) {
                //logger.info("开始将截取的list放入新的list中");
                tNewList.add(subNewList);
            }
        }
        return tNewList;
    }


    private Map getXianheGetTaskAccount(List<BEnterpriseRiskAssessmentLast> beforeList, Date nowTime) {
        List<String> delIds = new ArrayList<>();
        List<String> unDelIds = new ArrayList<>();

        String token = TokenConstants.AUTHENTICATION + " " + SecurityUtils.getToken();
        Map params = new HashMap();
        params.put("pageIndex", 1);
        params.put("pageSize", 100);
        Object o = ibMainThreeSupervisionEnforcServiceImpl.xianheGetTaskAccount(params, token);
        String jsonString = JSON.toJSONString(o);
        JSONObject jsonObject = JSON.parseObject(jsonString);
        if ("200".equals(jsonObject.get("code"))) {
            JSONArray list = jsonObject.getJSONArray("data");
            // 判断总条数是否大于100条
            if ((Integer) jsonObject.get("count") > 100) {
                // 要循环的次数
                int count = Math.floorDiv((Integer) jsonObject.get("count"), 100);
                for (int i = 2; i <= count; i++) {
                    params.put("pageIndex", i);
                    Object o1 = ibMainThreeSupervisionEnforcServiceImpl.xianheGetTaskAccount(params, token);
                    JSONArray data = JSON.parseObject(JSON.toJSONString(o1)).getJSONArray("data");
                    list.addAll(data);
                }
            }
            // 清理一下之前的数据
            Map<String, JSONObject> jsonObjectMap = list.stream().collect(Collectors.toMap(x -> JSON.parseObject(x.toString()).get("id").toString(),
                    x -> JSON.parseObject(x.toString()),
                    (oldValue, newValue) -> oldValue,
                    HashMap::new));
            List<String> beforeBusinessIds = beforeList.stream().map(BEnterpriseRiskAssessmentLast::getBusinessId).collect(Collectors.toList());
            beforeBusinessIds.forEach(x -> {
                if ("1".equals(jsonObjectMap.get(x).get("taskstate"))) {
                    // 此事件已办结，进入删除状态
                    delIds.add(x);
                } else {
                    // 未办结的事件
                    unDelIds.add(x);
                }
            });


            // 获取完所有的数据之后，过滤未办结的
            List<JSONObject> taskstate = list.stream().filter(x -> "0".equals(JSON.parseObject(x.toString()).get("taskstate"))).map(x -> JSON.parseObject(x.toString())).collect(Collectors.toList());
            List<BEnterpriseRiskAssessmentLast> newLast = new ArrayList<>();

            taskstate.forEach(x -> {
                // 判断一下之前数据是否存在，如果存在就不在进行插入
                if (!unDelIds.contains(x.get("id").toString())) {
                    BEnterpriseRiskAssessmentLast last = new BEnterpriseRiskAssessmentLast();
                    last.setFactoryId(x.get("enterpriseid").toString());
                    // 类型
                    last.setProblemExist(EnvironmentalCodingGradeEnum.ZFXT_02.getName());
                    // 是否多次扣分
                    last.setIsRepeatedGrade(EnvironmentalCodingGradeEnum.ZFXT_02.getIsGrade() ? 1 : 0);
                    // 存业务ID
                    last.setBusinessId(x.get("id").toString());
                    // 扣分
                    last.setScore(EnvironmentalCodingGradeEnum.ZFXT_02.getGrade());
                    last.setCreateTime(nowTime);
                    newLast.add(last);
                }
            });

            Map map = new HashMap();
            map.put("delIds", delIds);
            map.put("newLast", newLast);
            return map;
        }
        return null;
    }

}


