package com.njcn.device.pq.service.impl;


import cn.hutool.core.codec.Base64;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.*;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.njcn.algorithm.pojo.api.PqReasonableRangeFeignClient;
import com.njcn.algorithm.pojo.dto.PqReasonableRangeDto;
import com.njcn.algorithm.pojo.param.DataCleanParam;
import com.njcn.common.pojo.exception.BusinessException;
import com.njcn.dataProcess.api.DataLimitRateDetailFeignClient;
import com.njcn.dataProcess.api.DataLimitRateFeignClient;
import com.njcn.dataProcess.api.DataLimitTargetFeignClient;
import com.njcn.dataProcess.enums.DataCleanEnum;
import com.njcn.dataProcess.param.LineCountEvaluateParam;
import com.njcn.dataProcess.pojo.dto.DataLimitRateDetailDto;
import com.njcn.dataProcess.pojo.dto.DataLimitTargetDto;
import com.njcn.device.biz.pojo.po.Overlimit;
import com.njcn.device.line.mapper.LineMapper;
import com.njcn.device.line.service.DeptLineService;
import com.njcn.device.overlimit.service.IOverLimitService;
import com.njcn.device.pq.mapper.DataVerifyMapper;
import com.njcn.device.pq.pojo.param.dataClean.MonitorBaseParam;
import com.njcn.device.pq.pojo.po.DataVerify;
import com.njcn.device.pq.pojo.po.DeptLine;
import com.njcn.device.pq.pojo.vo.AreaLineInfoVO;
import com.njcn.device.pq.pojo.vo.LineDetailDataVO;
import com.njcn.device.pq.pojo.vo.dataClean.*;
import com.njcn.device.pq.service.CommTerminalService;
import com.njcn.device.pq.service.IDataVerifyService;
import com.njcn.system.api.DicDataFeignClient;
import com.njcn.system.api.DictTreeFeignClient;
import com.njcn.system.enums.DicDataEnum;
import com.njcn.system.enums.DicDataTypeEnum;
import com.njcn.system.pojo.po.DictData;
import lombok.RequiredArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;


/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author cdf
 * @since 2025-03-26
 */
@Service
@RequiredArgsConstructor
public class DataVerifyServiceImpl extends ServiceImpl<DataVerifyMapper, DataVerify> implements IDataVerifyService {

    private static final Logger logger = LoggerFactory.getLogger(DataVerifyServiceImpl.class);
    private static final String SEPARATOR = "&";
    private static final DateTimeFormatter DATE_FORMAT = DateTimeFormatter.ofPattern(DatePattern.NORM_DATE_PATTERN);
    private final CommTerminalService commTerminalService;
    private final LineMapper lineMapper;
    private final DictTreeFeignClient dictTreeFeignClient;
    private final PqReasonableRangeFeignClient pqReasonableRangeFeignClient;
    private final DataLimitTargetFeignClient dataLimitTargetFeignClient;
    private final DataLimitRateFeignClient dataLimitRateFeignClient;
    private final DataLimitRateDetailFeignClient dataLimitRateDetailFeignClient;
    private final DicDataFeignClient dicDataFeignClient;
    private final IOverLimitService overLimitService;
    private final DeptLineService deptLineService;


    @Override
    public VerifyMonitorVO getMonitorLimitData(MonitorBaseParam monitorBaseParam) {
        List<String> monitorIds = commTerminalService.getRunMonitorByDept(monitorBaseParam);
        LineCountEvaluateParam lineCountEvaluateParam = new LineCountEvaluateParam();
        lineCountEvaluateParam.setLineId(monitorIds);
        lineCountEvaluateParam.setStartTime(monitorBaseParam.getSearchBeginTime());
        lineCountEvaluateParam.setEndTime(monitorBaseParam.getSearchEndTime());
        List<DataLimitTargetDto> limitTarget = dataLimitTargetFeignClient.getRawData(lineCountEvaluateParam).getData();
        List<DataLimitTargetDto> limitList = limitTarget.stream().filter(it -> (it.getAllTime() > 0 || it.getFlickerAllTime() > 0)).collect(Collectors.toList());
        long abnormalCount = limitList.stream().map(DataLimitTargetDto::getLineId).distinct().count();
        VerifyMonitorVO verifyMonitorVO = new VerifyMonitorVO();
        verifyMonitorVO.setRunNum(monitorIds.size());
        verifyMonitorVO.setAbnormalNum((int) abnormalCount);

        List<Map<String, Object>> mapList = getRangeLimitMonitor(monitorBaseParam, limitList);
        verifyMonitorVO.setMapList(mapList);
        verifyMonitorVO.setMonitorAlarmInfo(getLimitTable(limitList, monitorBaseParam));
        verifyMonitorVO.setTargetList(assLimitTarget(limitTarget));
        return verifyMonitorVO;
    }

    @Override
    public List<PowerQualityIndicatorsVO> getMonitorLimitDataDay(MonitorBaseParam monitorBaseParam) {
        List<String> monitorIds = commTerminalService.getRunMonitorByDept(monitorBaseParam);
        LineCountEvaluateParam lineCountEvaluateParam = new LineCountEvaluateParam();
        lineCountEvaluateParam.setLineId(monitorIds);
        lineCountEvaluateParam.setStartTime(monitorBaseParam.getSearchBeginTime());
        lineCountEvaluateParam.setEndTime(monitorBaseParam.getSearchEndTime());
        List<DataLimitTargetDto> limitTarget = dataLimitTargetFeignClient.getRawData(lineCountEvaluateParam).getData();
        List<DataLimitTargetDto> limitList = limitTarget.stream().filter(it -> (it.getAllTime() > 0 || it.getFlickerAllTime() > 0)).collect(Collectors.toList());
        return getLimitTable(limitList, monitorBaseParam);
    }

    @Override
    public List<DetailAbnormalVO> monitorLimitTable(MonitorBaseParam monitorBaseParam) {
        List<DetailAbnormalVO> result = new ArrayList<>();
        List<LineDetailDataVO> lineDetailList = lineMapper.getLineDetailDataVO(monitorBaseParam.getMonitorIds());
        Map<String, LineDetailDataVO> lineDetailMap = lineDetailList.stream().collect(Collectors.toMap(LineDetailDataVO::getLineId, Function.identity()));
        LineCountEvaluateParam lineCountEvaluateParam = new LineCountEvaluateParam();
        lineCountEvaluateParam.setLineId(monitorBaseParam.getMonitorIds());
        lineCountEvaluateParam.setStartTime(monitorBaseParam.getSearchBeginTime());
        lineCountEvaluateParam.setEndTime(monitorBaseParam.getSearchEndTime());
        List<DataLimitTargetDto> dataLimitTargetDtoList = dataLimitTargetFeignClient.getRawData(lineCountEvaluateParam).getData();
        Map<String, List<DataLimitTargetDto>> limitMap = dataLimitTargetDtoList.stream().filter(it -> (it.getAllTime() > 0 || it.getFlickerAllTime() > 0)).collect(Collectors.groupingBy(DataLimitTargetDto::getLineId));
        limitMap.forEach((lineId, value) -> {
            LineDetailDataVO lineInfoVO = lineDetailMap.get(lineId);
            DetailAbnormalVO detailAbnormalVO = new DetailAbnormalVO();
            detailAbnormalVO.setMonitorId(lineId);
            List<DetailAbnormalVO.TimeAndTargetKey> targetKeyList = new ArrayList<>();
            DetailAbnormalVO.TimeAndTargetKey targetKey;
            for (DataLimitTargetDto dto : value) {
                List<VerifyTargetVO> verifyS = assLimitTarget(Arrays.asList(dto)).stream().filter(x -> x.getIds().size() > 0).collect(Collectors.toList());
                if (StrUtil.isNotBlank(monitorBaseParam.getTargetKey())) {
                    List<VerifyTargetVO> verify = verifyS.stream().filter(x -> x.getKey().equals(monitorBaseParam.getTargetKey())).collect(Collectors.toList());
                    if (CollUtil.isNotEmpty(verify)) {
                        targetKey = new DetailAbnormalVO.TimeAndTargetKey();
                        targetKey.setDate(dto.getTime().format(DatePattern.NORM_DATE_FORMATTER));
                        targetKey.setTargetKeys(verify);
                        targetKeyList.add(targetKey);
                    }
                } else {
                    targetKey = new DetailAbnormalVO.TimeAndTargetKey();
                    targetKey.setDate(dto.getTime().format(DatePattern.NORM_DATE_FORMATTER));
                    targetKey.setTargetKeys(verifyS);
                    targetKeyList.add(targetKey);
                }
            }
            detailAbnormalVO.setDateTargetList(targetKeyList);
            detailAbnormalVO.setMonitorName(lineInfoVO.getLineName());
            detailAbnormalVO.setBdName(lineInfoVO.getBdName());
            detailAbnormalVO.setTargetKey(monitorBaseParam.getTargetKey());
            result.add(detailAbnormalVO);
        });

        return result;
    }

    @Override
    public DetailAbnormalVO.DetailLimitCountVO monitorLimitTableDetail(MonitorBaseParam monitorBaseParam) {
        List<LineDetailDataVO> lineDetailList = lineMapper.getLineDetailDataVO(monitorBaseParam.getMonitorIds());
        Map<String, LineDetailDataVO> lineDetailMap = lineDetailList.stream().collect(Collectors.toMap(LineDetailDataVO::getLineId, Function.identity()));
        DetailAbnormalVO.DetailLimitCountVO v = new DetailAbnormalVO.DetailLimitCountVO();
        List<DetailAbnormalVO.DetailLimitInnerVO> result = new ArrayList<>();
        LineCountEvaluateParam lineCountEvaluateParam = new LineCountEvaluateParam();
        lineCountEvaluateParam.setLineId(Collections.singletonList(monitorBaseParam.getMonitorIds().get(0)));
        lineCountEvaluateParam.setStartTime(monitorBaseParam.getSearchBeginTime());
        lineCountEvaluateParam.setEndTime(monitorBaseParam.getSearchBeginTime());
        List<DataLimitRateDetailDto> dtoList = dataLimitRateDetailFeignClient.getRawData(lineCountEvaluateParam).getData();
        if (CollUtil.isEmpty(dtoList)) {
            return v;
        }

        DataLimitRateDetailDto dto = dtoList.get(0);
        Map<String, DictData> targetMap = getTargetMap();
        if (StrUtil.isNotBlank(monitorBaseParam.getTargetKey())) {
            processSingleTarget(dto, monitorBaseParam.getTargetKey(), targetMap, result);
        } else {
            processAllTargets(dto, targetMap, result);
        }
        int size = result.stream().map(DetailAbnormalVO.DetailLimitInnerVO::getTime).collect(Collectors.toSet()).size();
        v.setTimeSum(lineDetailMap.get(monitorBaseParam.getMonitorIds().get(0)).getTimeInterval() * size);
        v.setTime(result);
        return v;
    }

    @Override
    public DetailAbnormalVO.Assess limitTableDetail(MonitorBaseParam monitorBaseParam) {
        DetailAbnormalVO.Assess assess = new DetailAbnormalVO.Assess();
        LineCountEvaluateParam lineCountEvaluateParam = new LineCountEvaluateParam();
        lineCountEvaluateParam.setLineId(Collections.singletonList(monitorBaseParam.getMonitorIds().get(0)));
        lineCountEvaluateParam.setStartTime(monitorBaseParam.getSearchBeginTime());
        lineCountEvaluateParam.setEndTime(monitorBaseParam.getSearchEndTime());
        List<DataLimitRateDetailDto> dtoList = dataLimitRateDetailFeignClient.getRawData(lineCountEvaluateParam).getData();
        Overlimit overLimitDataById = overLimitService.getOverLimitDataById(monitorBaseParam.getMonitorIds().get(0));

        List<DetailAbnormalVO.DetailLimitInnerVO> freq = new ArrayList<>();
        List<DetailAbnormalVO.DetailLimitInnerVO> voltage = new ArrayList<>();
        List<DetailAbnormalVO.DetailLimitInnerVO> uaberrance = new ArrayList<>();
        List<DetailAbnormalVO.DetailLimitInnerVO> ubalance = new ArrayList<>();
        List<DetailAbnormalVO.DetailLimitInnerVO> flicker = new ArrayList<>();
        List<DetailAbnormalVO.DetailLimitInnerVO> iNeg = new ArrayList<>();

        List<DetailAbnormalVO.DetailLimitInnerVO> uharm = new ArrayList<>();
        List<DetailAbnormalVO.DetailLimitInnerVO> iharm = new ArrayList<>();
        List<DetailAbnormalVO.DetailLimitInnerVO> inuharm = new ArrayList<>();

        for (DataLimitRateDetailDto dto : dtoList) {
            dealJsonArr(new JSONArray(dto.getFreqDevOvertime()), freq, DicDataEnum.FREQUENCY_DEV.getName(), null);
            dealJsonArr(new JSONArray(dto.getVoltageDevOvertime()), voltage, DicDataEnum.VOLTAGE_DEV.getName(), null);
            dealJsonArr(new JSONArray(dto.getUaberranceOvertime()), uaberrance, DicDataEnum.THD_V.getName(), null);
            dealJsonArr(new JSONArray(dto.getUbalanceOvertime()), ubalance, DicDataEnum.phase_Voltage.getName(), null);
            dealJsonArr(new JSONArray(dto.getFlickerOvertime()), flicker, DicDataEnum.FLICKER.getName(), null);
            dealJsonArr(new JSONArray(dto.getINegOvertime()), iNeg, DicDataEnum.NEG_CURRENT.getName(), null);
            // 处理谐波类指标
            processHarmonicTargetHarm(dto, DicDataEnum.HARMONIC_VOLTAGE.getName(), "uharm", 2, 25, uharm);
            processHarmonicTargetHarm(dto, DicDataEnum.HARMONIC_CURRENT.getName(), "iharm", 2, 25, iharm);
            processHarmonicTargetHarm(dto, DicDataEnum.INTERHARMONIC_VOLTAGE.getName(), "inuharm", 1, 16, inuharm);
        }
        assess.setFreqLimit(overLimitDataById.getFreqDev());
        assess.setVDevLimit(overLimitDataById.getVoltageDev());
        assess.setUDevLimit(overLimitDataById.getUvoltageDev());
        assess.setUaberranceLimit(overLimitDataById.getUaberrance());
        assess.setUnbalanceLimit(overLimitDataById.getUbalance());
        assess.setFlickerLimit(overLimitDataById.getFlicker());
        assess.setINegLimit(overLimitDataById.getINeg());
        Map<String, List<PqReasonableRangeDto>> map = new HashMap<>();
        DataCleanParam param = new DataCleanParam();
        param.setSystemType(DataCleanEnum.Pqs.getCode());
        List<PqReasonableRangeDto> list = pqReasonableRangeFeignClient.getData(param).getData();
        if (CollUtil.isNotEmpty(list)) {
            map = list.stream().collect(Collectors.groupingBy(PqReasonableRangeDto::getInfluxdbTableName));
        }

        List<PqReasonableRangeDto> dataV = map.get(DataCleanEnum.DataV.getCode());
        Map<String, PqReasonableRangeDto> dataVCode = dataV.stream().collect(Collectors.toMap(PqReasonableRangeDto::getIndexCode, Function.identity()));
        //频率偏差
        if (CollUtil.isNotEmpty(freq)) {
            PqReasonableRangeDto dto = dataVCode.get(DataCleanEnum.FreqDev.getCode());
            DetailAbnormalVO.DetailLimitInnerVO val = reasonAble(freq, dto);
            assess.setFreqData(NumberUtil.round(val.getVal(), 2).doubleValue());
        }

        //电压偏差
        if (CollUtil.isNotEmpty(voltage)) {
            //上偏差
            PqReasonableRangeDto dto1 = dataVCode.get(DataCleanEnum.VuDev.getCode());
            List<DetailAbnormalVO.DetailLimitInnerVO> collect = voltage.stream()
                    .filter(x -> Double.valueOf(x.getVal()) > 0)
                    .filter(x -> Double.valueOf(x.getVal()) < dto1.getMaxValue())
                    .sorted(Comparator.comparing(DetailAbnormalVO.DetailLimitInnerVO::getVal).reversed()).collect(Collectors.toList());
            if (CollUtil.isNotEmpty(collect)) {
                DetailAbnormalVO.DetailLimitInnerVO val;
                if (CollUtil.isNotEmpty(collect)) {
                    val = collect.get(0);
                } else {
                    List<DetailAbnormalVO.DetailLimitInnerVO> collect2 = voltage.stream()
                            .filter(x -> Double.valueOf(x.getVal()) > 0)
                            .sorted(Comparator.comparing(DetailAbnormalVO.DetailLimitInnerVO::getVal).reversed())
                            .collect(Collectors.toList());
                    val = collect2.get(0);
                    val.setVal(dto1.getMaxValue().toString());
                }
                assess.setVDevData(NumberUtil.round(val.getVal(), 2).doubleValue());
            }
            //下偏差
            PqReasonableRangeDto dto2 = dataVCode.get(DataCleanEnum.VlDev.getCode());
            List<DetailAbnormalVO.DetailLimitInnerVO> collect2 = voltage.stream()
                    .filter(x -> Double.valueOf(x.getVal()) < 0)
                    .filter(x -> dto2.getMinValue() < Double.valueOf(x.getVal()))
                    .sorted(Comparator.comparing(DetailAbnormalVO.DetailLimitInnerVO::getVal)).collect(Collectors.toList());
            if (CollUtil.isNotEmpty(collect2)) {
                DetailAbnormalVO.DetailLimitInnerVO val2;
                if (CollUtil.isNotEmpty(collect)) {
                    val2 = collect.get(0);
                } else {
                    List<DetailAbnormalVO.DetailLimitInnerVO> collect3 = voltage.stream()
                            .filter(x -> Double.valueOf(x.getVal()) < 0)
                            .sorted(Comparator.comparing(DetailAbnormalVO.DetailLimitInnerVO::getVal).reversed())
                            .collect(Collectors.toList());
                    val2 = collect3.get(0);
                    val2.setVal(dto2.getMaxValue().toString());
                }
                assess.setUDevData(NumberUtil.round(val2.getVal(), 2).doubleValue());
            }
        }
        //负序电流
        if (CollUtil.isNotEmpty(iNeg)) {
            List<DetailAbnormalVO.DetailLimitInnerVO> collect = iNeg.stream()
                    .sorted(Comparator.comparing(DetailAbnormalVO.DetailLimitInnerVO::getVal).reversed())
                    .collect(Collectors.toList());
            DetailAbnormalVO.DetailLimitInnerVO val = collect.get(0);
            assess.setINegData(NumberUtil.round(val.getVal(), 2).doubleValue());
        }
        //电压总谐波
        if (CollUtil.isNotEmpty(uaberrance)) {
            PqReasonableRangeDto dto = dataVCode.get(DataCleanEnum.VThd.getCode());
            DetailAbnormalVO.DetailLimitInnerVO val = reasonAble(uaberrance, dto);
            assess.setUaberranceData(NumberUtil.round(val.getVal(), 2).doubleValue());
        }
        //三相不平衡度
        if (CollUtil.isNotEmpty(ubalance)) {
            PqReasonableRangeDto dto = dataVCode.get(DataCleanEnum.VUnbalance.getCode());
            DetailAbnormalVO.DetailLimitInnerVO val = reasonAble(ubalance, dto);
            assess.setUnbalanceData(NumberUtil.round(val.getVal(), 2).doubleValue());
        }
        //闪变
        List<PqReasonableRangeDto> dataPlt = map.get(DataCleanEnum.DataPlt.getCode());
        Map<String, PqReasonableRangeDto> dataPltCode = dataPlt.stream().collect(Collectors.toMap(PqReasonableRangeDto::getIndexCode, Function.identity()));
        if (CollUtil.isNotEmpty(flicker)) {
            PqReasonableRangeDto dto = dataPltCode.get(DataCleanEnum.Plt.getCode());
            DetailAbnormalVO.DetailLimitInnerVO val = reasonAble(flicker, dto);
            assess.setFlickerData(NumberUtil.round(val.getVal(), 2).doubleValue());
        }
        //谐波电压
        List<PqReasonableRangeDto> dataHarmRate = map.get(DataCleanEnum.DataHarmRateV.getCode());
        Map<String, PqReasonableRangeDto> dataHarmRateCode = dataHarmRate.stream().collect(Collectors.toMap(PqReasonableRangeDto::getIndexCode, Function.identity()));
        if (CollUtil.isNotEmpty(uharm)) {
            PqReasonableRangeDto dto = dataHarmRateCode.get(DataCleanEnum.V_Rate.getCode());
            DetailAbnormalVO.DetailLimitInnerVO val = reasonAble(uharm, dto);
            assess.setUharmData(NumberUtil.round(val.getVal(), 2).doubleValue());
            String[] split = val.getTargetName().split("次");
            try {
                Class<?> clazz = overLimitDataById.getClass();
                String methodName = "getUharm" + split[0];
                Method method = clazz.getMethod(methodName);
                Float value = (Float) method.invoke(overLimitDataById);
                assess.setUharmLimit(value);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        } else {
            if(CollUtil.isNotEmpty(uaberrance)){
                PqReasonableRangeDto dto = dataVCode.get(DataCleanEnum.VThd.getCode());
                DetailAbnormalVO.DetailLimitInnerVO val = reasonAble(uaberrance, dto);
                assess.setUharmData(NumberUtil.round(val.getVal(), 2).doubleValue());
            }
        }
        //谐波电流
        if (CollUtil.isNotEmpty(iharm)) {
            List<DetailAbnormalVO.DetailLimitInnerVO> collect = iharm.stream()
                    .sorted(Comparator.comparing(DetailAbnormalVO.DetailLimitInnerVO::getVal).reversed())
                    .collect(Collectors.toList());
            DetailAbnormalVO.DetailLimitInnerVO val = collect.get(0);
            assess.setIharmData(NumberUtil.round(val.getVal(), 2).doubleValue());
            String[] split = val.getTargetName().split("次");
            try {
                Class<?> clazz = overLimitDataById.getClass();
                String methodName = "getIharm" + split[0];
                Method method = clazz.getMethod(methodName);
                Float value = (Float) method.invoke(overLimitDataById);
                assess.setIharmLimit(value);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }

        }
        //间谐波电压
        List<PqReasonableRangeDto> dataInHarm = map.get(DataCleanEnum.DataInHarmV.getCode());
        Map<String, PqReasonableRangeDto> dataInHarmCode = dataInHarm.stream().collect(Collectors.toMap(PqReasonableRangeDto::getIndexCode, Function.identity()));
        if (CollUtil.isNotEmpty(inuharm)) {
            PqReasonableRangeDto dto = dataInHarmCode.get(DataCleanEnum.V_InHarm.getCode());
            DetailAbnormalVO.DetailLimitInnerVO val = reasonAble(inuharm, dto);
            assess.setInuharmData(NumberUtil.round(val.getVal(), 2).doubleValue());
            String[] split = val.getTargetName().split("次");
            try {
                Class<?> clazz = overLimitDataById.getClass();
                String methodName = "getInuharm" + (int)(Double.valueOf(split[0])+0.5);
                Method method = clazz.getMethod(methodName);
                Float value = (Float) method.invoke(overLimitDataById);
                assess.setInuharmLimit(value);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
        return assess;
    }

    private DetailAbnormalVO.DetailLimitInnerVO reasonAble(List<DetailAbnormalVO.DetailLimitInnerVO> limit, PqReasonableRangeDto dto) {
        List<DetailAbnormalVO.DetailLimitInnerVO> collect = limit.stream()
                .filter(x -> dto.getMinValue() < Double.valueOf(x.getVal()) && Double.valueOf(x.getVal()) < dto.getMaxValue())
                .sorted(Comparator.comparing(DetailAbnormalVO.DetailLimitInnerVO::getVal).reversed()).collect(Collectors.toList());
        DetailAbnormalVO.DetailLimitInnerVO val;
        if (CollUtil.isNotEmpty(collect)) {
            val = collect.get(0);
        } else {
            List<DetailAbnormalVO.DetailLimitInnerVO> collect2 = limit.stream()
                    .sorted(Comparator.comparing(DetailAbnormalVO.DetailLimitInnerVO::getVal).reversed())
                    .collect(Collectors.toList());
            val = collect2.get(0);
            val.setVal(dto.getMaxValue().toString());
        }
        return val;
    }

    private Map<String, DictData> getTargetMap() {
        List<DictData> dictDataList = dicDataFeignClient.getDicDataByTypeCode(DicDataTypeEnum.STEADY_STATIS.getCode()).getData();
        return dictDataList.stream().collect(Collectors.toMap(DictData::getCode, Function.identity()));
    }

    private void processSingleTarget(DataLimitRateDetailDto dto, String targetKey, Map<String, DictData> targetMap, List<DetailAbnormalVO.DetailLimitInnerVO> result) {
        if (!targetMap.containsKey(targetKey)) {
            throw new BusinessException("异常指标参数");
        }

        String targetName = targetMap.get(targetKey).getName();
        List<String> specialTargetList = new ArrayList<>();
        JSONArray jsonArray = new JSONArray();

        DicDataEnum targetEnum = DicDataEnum.getDicDataEnumValue(targetKey);
        switch (Objects.requireNonNull(targetEnum)) {
            case VOLTAGE_DEV:
                jsonArray = new JSONArray(dto.getVoltageDevOvertime());
                break;
            case FLICKER:
                jsonArray = new JSONArray(dto.getFlickerOvertime());
                break;
            case PHASE_VOLTAGE:
                jsonArray = new JSONArray(dto.getUbalanceOvertime());
                break;
            case FREQUENCY_DEV:
                jsonArray = new JSONArray(dto.getFreqDevOvertime());
                break;
            case NEG_CURRENT:
                jsonArray = new JSONArray(dto.getINegOvertime());
                break;
            case THD_V:
                jsonArray = new JSONArray(dto.getUaberranceOvertime());
                break;
            case HARMONIC_VOLTAGE:
                collectHarmonicData(dto, "uharm", 2, 25, specialTargetList);
                break;
            case HARMONIC_CURRENT:
                collectHarmonicData(dto, "iharm", 2, 25, specialTargetList);
                break;
            case INTERHARMONIC_VOLTAGE:
                collectHarmonicData(dto, "inuharm", 1, 16, specialTargetList);
                break;
            default:
                throw new BusinessException("未支持的指标类型: " + targetKey);
        }
        if (CollUtil.isNotEmpty(specialTargetList)) {
            processSpecialTargets(specialTargetList, result, targetName);
        } else {
            dealJsonArr(jsonArray, result, targetName, null);
        }
    }

    private void processAllTargets(DataLimitRateDetailDto dto, Map<String, DictData> targetMap,
                                   List<DetailAbnormalVO.DetailLimitInnerVO> result) {
        // 处理标准指标
        processStandardTarget(dto, targetMap, DicDataEnum.VOLTAGE_DEV.getCode(), dto.getVoltageDevOvertime(), result);
        processStandardTarget(dto, targetMap, DicDataEnum.FLICKER.getCode(), dto.getFlickerOvertime(), result);
        processStandardTarget(dto, targetMap, DicDataEnum.phase_Voltage.getCode(), dto.getUbalanceOvertime(), result);
        processStandardTarget(dto, targetMap, DicDataEnum.FREQUENCY_DEV.getCode(), dto.getFreqDevOvertime(), result);
        processStandardTarget(dto, targetMap, DicDataEnum.NEG_CURRENT.getCode(), dto.getINegOvertime(), result);
        processStandardTarget(dto, targetMap, DicDataEnum.THD_V.getCode(), dto.getUaberranceOvertime(), result);

        // 处理谐波类指标
        processHarmonicTarget(dto, targetMap, DicDataEnum.HARMONIC_VOLTAGE.getCode(), "uharm", 2, 25, result);
        processHarmonicTarget(dto, targetMap, DicDataEnum.HARMONIC_CURRENT.getCode(), "iharm", 2, 25, result);
        processHarmonicTarget(dto, targetMap, DicDataEnum.INTERHARMONIC_VOLTAGE.getCode(), "inuharm", 1, 16, result);
    }

    private void processStandardTarget(DataLimitRateDetailDto dto, Map<String, DictData> targetMap,
                                       String targetCode, String data,
                                       List<DetailAbnormalVO.DetailLimitInnerVO> result) {
        if (StrUtil.isNotBlank(data)) {
            JSONArray jsonArray = new JSONArray(data);
            String targetName = targetMap.get(targetCode).getName();
            dealJsonArr(jsonArray, result, targetName, null);
        }
    }

    private void processHarmonicTarget(DataLimitRateDetailDto dto, Map<String, DictData> targetMap,
                                       String targetCode, String prefix, int start, int end,
                                       List<DetailAbnormalVO.DetailLimitInnerVO> result) {
        List<String> tempList = new ArrayList<>();
        String targetName = targetMap.get(targetCode).getName();
        collectHarmonicData(dto, prefix, start, end, tempList);
        processSpecialTargets(tempList, result, targetName);
    }

    private void processHarmonicTargetHarm(DataLimitRateDetailDto dto, String targetCode, String prefix, int start, int end,
                                           List<DetailAbnormalVO.DetailLimitInnerVO> result) {
        List<String> tempList = new ArrayList<>();
        collectHarmonicData(dto, prefix, start, end, tempList);
        processSpecialTargets(tempList, result, targetCode);
    }

    private void processSpecialTargets(List<String> specialTargetList, List<DetailAbnormalVO.DetailLimitInnerVO> result, String targetName) {
        for (String strJson : specialTargetList) {
            String[] temStr = strJson.split(SEPARATOR);
            JSONArray jsonTem = new JSONArray(temStr[0]);
            dealJsonArr(jsonTem, result, targetName, temStr[1]);
        }
    }

    /**
     * 处理json数组
     */
    private void dealJsonArr(JSONArray jsonArray, List<DetailAbnormalVO.DetailLimitInnerVO> result, String targetName, String count) {
        List<JsonBaseVO> jsonBaseVOList = jsonArray.toList(JsonBaseVO.class);
        Map<String, List<JsonBaseVO>> jsonMap = jsonBaseVOList.stream().collect(Collectors.groupingBy(JsonBaseVO::getPhasic));
        jsonMap.forEach((phasic, list) -> {
            Map<String, List<JsonBaseVO>> valueTypeMap = list.stream().collect(Collectors.groupingBy(JsonBaseVO::getValueType));
            valueTypeMap.forEach((valueTypeId, vList) -> {
                vList.forEach(it -> {
                    String[] timeArr = it.getTime().split(StrUtil.COMMA);
                    String[] valArr = it.getValue().split(StrUtil.COMMA);
                    for (int i = 0; i < timeArr.length; i++) {
                        DetailAbnormalVO.DetailLimitInnerVO vo = new DetailAbnormalVO.DetailLimitInnerVO();
                        vo.setTime(timeArr[i]);
                        vo.setType(it.getValueType());
                        vo.setVal(valArr[i]);
                        vo.setPhaseType(phasic);
                        vo.setTargetName(StrUtil.isNotBlank(count) ? count + "次" + targetName : targetName);
                        vo.setOverLimitValue(it.getOverLimitValue());
                        result.add(vo);
                    }
                });
            });
        });
    }


    private List<DataVerify> commQuery(List<String> monitorIds, MonitorBaseParam monitorBaseParam) {
        LambdaQueryWrapper<DataVerify> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.between(DataVerify::getTime, DateUtil.beginOfDay(DateUtil.parse(monitorBaseParam.getSearchBeginTime())), DateUtil.endOfDay(DateUtil.parse(monitorBaseParam.getSearchEndTime())))
                .in(DataVerify::getLineId, monitorIds).orderByAsc(DataVerify::getTime);
        return this.list(lambdaQueryWrapper);
    }


    private List<VerifyTargetVO> assLimitTarget(List<DataLimitTargetDto> limitList) {
        List<VerifyTargetVO> verifyTargetVOList = new ArrayList<>();
        Set<String> FLICKER = new HashSet<>();
        Set<String> VOLTAGE_DEV = new HashSet<>();
        Set<String> HARMONIC_VOLTAGE = new HashSet<>();
        Set<String> HARMONIC_CURRENT = new HashSet<>();
        Set<String> INTERHARMONIC_VOLTAGE = new HashSet<>();
        Set<String> FREQUENCY_DEV = new HashSet<>();
        Set<String> NEG_CURRENT = new HashSet<>();
        Set<String> THD_V = new HashSet<>();
        Set<String> phase_Voltage = new HashSet<>();
        limitList.forEach(it -> {
            if (it.getFlickerOvertime() > 0) {
                FLICKER.add(it.getLineId());
            }
            if (it.getFreqDevOvertime() > 0) {
                FREQUENCY_DEV.add(it.getLineId());
            }
            if (it.getVoltageDevOvertime() > 0) {
                VOLTAGE_DEV.add(it.getLineId());
            }
            if (it.getINegOvertime() > 0) {
                NEG_CURRENT.add(it.getLineId());
            }
            if (it.getUaberranceOvertime() > 0) {
                THD_V.add(it.getLineId());
            }
            if (it.getUbalanceOvertime() > 0) {
                phase_Voltage.add(it.getLineId());
            }
            for (int i = 2; i <= 25; i++) {
                String uHarmKey = "uharm" + i + "Overtime";
                String iHarmKey = "iharm" + i + "Overtime";
                if (getFieldValue(it, uHarmKey) != null && getFieldValue(it, uHarmKey) == 1) {
                    HARMONIC_VOLTAGE.add(it.getLineId());
                }
                if (getFieldValue(it, iHarmKey) != null && getFieldValue(it, iHarmKey) == 1) {
                    HARMONIC_CURRENT.add(it.getLineId());
                }
            }
            for (int i = 1; i <= 16; i++) {
                String inuHarmKey = "inuharm" + i + "Overtime";
                if (getFieldValue(it, inuHarmKey) != null && getFieldValue(it, inuHarmKey) == 1) {
                    INTERHARMONIC_VOLTAGE.add(it.getLineId());
                }
            }
        });

        Map<String, Set<String>> overLimitCount = new HashMap<>();
        overLimitCount.put(DicDataEnum.FLICKER.getCode() + SEPARATOR + DicDataEnum.FLICKER.getName(), FLICKER);
        overLimitCount.put(DicDataEnum.VOLTAGE_DEV.getCode() + SEPARATOR + DicDataEnum.VOLTAGE_DEV.getName(), VOLTAGE_DEV);
        overLimitCount.put(DicDataEnum.HARMONIC_VOLTAGE.getCode() + SEPARATOR + DicDataEnum.HARMONIC_VOLTAGE.getName(), HARMONIC_VOLTAGE);
        overLimitCount.put(DicDataEnum.HARMONIC_CURRENT.getCode() + SEPARATOR + DicDataEnum.HARMONIC_CURRENT.getName(), HARMONIC_CURRENT);
        overLimitCount.put(DicDataEnum.INTERHARMONIC_VOLTAGE.getCode() + SEPARATOR + DicDataEnum.INTERHARMONIC_VOLTAGE.getName(), INTERHARMONIC_VOLTAGE);
        overLimitCount.put(DicDataEnum.FREQUENCY_DEV.getCode() + SEPARATOR + DicDataEnum.FREQUENCY_DEV.getName(), FREQUENCY_DEV);
        overLimitCount.put(DicDataEnum.NEG_CURRENT.getCode() + SEPARATOR + DicDataEnum.NEG_CURRENT.getName(), NEG_CURRENT);
        overLimitCount.put(DicDataEnum.THD_V.getCode() + SEPARATOR + DicDataEnum.THD_V.getName(), THD_V);
        overLimitCount.put(DicDataEnum.phase_Voltage.getCode() + SEPARATOR + DicDataEnum.phase_Voltage.getName(), phase_Voltage);

        overLimitCount.forEach((key, set) -> {
            String[] str = key.split(SEPARATOR);
            VerifyTargetVO verifyTargetVO = new VerifyTargetVO();
            verifyTargetVO.setTargetName(str[1]);
            verifyTargetVO.setIds(set);
            verifyTargetVO.setKey(str[0]);
            verifyTargetVOList.add(verifyTargetVO);
        });
        return verifyTargetVOList;
    }

    private void collectHarmonicData(DataLimitRateDetailDto dto, String prefix, int start, int end, List<String> result) {
        for (int i = start; i <= end; i++) {
            String fieldName = prefix + i + "Overtime";
            String json = getFieldValueForDetail(dto, fieldName);
            if (StrUtil.isNotBlank(json)) {
                if (end == 16) {
                    result.add(json + SEPARATOR + (i - 0.5));
                } else {
                    result.add(json + SEPARATOR + i);
                }

            }
        }
    }


    private Integer getFieldValue(DataLimitTargetDto dto, String fieldName) {
        try {
            Field field = DataLimitTargetDto.class.getDeclaredField(fieldName);
            field.setAccessible(true);
            return (Integer) field.get(dto);
        } catch (NoSuchFieldException | IllegalAccessException e) {
            logger.error("DataLimitTarget反射方法异常:{}", e.getMessage());
            return null;
        }
    }

    private String getFieldValueForDetail(DataLimitRateDetailDto dto, String fieldName) {
        try {
            Field field = DataLimitRateDetailDto.class.getDeclaredField(fieldName);
            field.setAccessible(true);
            return (String) field.get(dto);
        } catch (NoSuchFieldException | IllegalAccessException e) {
            logger.error("DataLimitRateDetail反射方法异常:{}", e.getMessage());
            return null;
        }
    }

    private List<Map<String, Object>> getRangeLimitMonitor(MonitorBaseParam monitorBaseParam, List<DataLimitTargetDto> limitList) {
        List<Map<String, Object>> result = new ArrayList<>();
        DateTime startTime = DateUtil.parse(monitorBaseParam.getSearchBeginTime());
        DateTime endTime = DateUtil.parse(monitorBaseParam.getSearchEndTime());
        if (startTime.year() == endTime.year() && startTime.month() == endTime.month()) {
            DateRange ranged = DateUtil.range(DateUtil.parse(monitorBaseParam.getSearchBeginTime()), DateUtil.parse(monitorBaseParam.getSearchEndTime()), DateField.DAY_OF_MONTH);
            Map<String, Integer> map = limitList.stream().collect(Collectors.groupingBy(it -> it.getTime().format(DATE_FORMAT),
                    Collectors.mapping(DataLimitTargetDto::getLineId, Collectors.collectingAndThen(Collectors.toSet(), Set::size))));
            PqDataVerifyBakServiceImpl.setTime(result, ranged, map, DATE_FORMAT);
        } else {
            //不在一个月则展示月数据
            DateRange ranged = DateUtil.range(DateUtil.parse(monitorBaseParam.getSearchBeginTime()), DateUtil.parse(monitorBaseParam.getSearchEndTime()), DateField.MONTH);
            if (CollUtil.isNotEmpty(limitList)) {
                Map<String, Integer> map = limitList.stream().collect(Collectors.groupingBy(it -> it.getTime().format(DateTimeFormatter.ofPattern(DatePattern.NORM_MONTH_PATTERN)),
                        Collectors.mapping(DataLimitTargetDto::getLineId, Collectors.collectingAndThen(Collectors.toSet(), Set::size))));
                for (DateTime dateTime : ranged) {
                    Map<String, Object> rangeMap = new HashMap<>();
                    String time = DateUtil.format(dateTime, DateTimeFormatter.ofPattern(DatePattern.NORM_MONTH_PATTERN));
                    rangeMap.put("time", time);
                    rangeMap.put("val", map.getOrDefault(time, 0));
                    result.add(rangeMap);
                }
            }
        }
        return result;
    }


    /**
     * 时间范围异常测点数量
     */
    private List<Map<String, Object>> getRangeAbnormalMonitor(MonitorBaseParam monitorBaseParam, List<DataVerify> dataVerifyList) {
        List<Map<String, Object>> result = new ArrayList<>();
        DateTime startTime = DateUtil.parse(monitorBaseParam.getSearchBeginTime());
        DateTime endTime = DateUtil.parse(monitorBaseParam.getSearchEndTime());
        if (startTime.year() == endTime.year() && startTime.month() == endTime.month()) {
            DateRange ranged = DateUtil.range(DateUtil.parse(monitorBaseParam.getSearchBeginTime()), DateUtil.parse(monitorBaseParam.getSearchEndTime()), DateField.DAY_OF_MONTH);
            Map<String, Integer> map = dataVerifyList.stream().collect(Collectors.groupingBy(it -> it.getTime().format(DATE_FORMAT),
                    Collectors.mapping(DataVerify::getLineId, Collectors.collectingAndThen(Collectors.toSet(), Set::size))));
            PqDataVerifyBakServiceImpl.setTime(result, ranged, map, DATE_FORMAT);
        } else {
            //不在一个月则展示月数据
            DateRange ranged = DateUtil.range(DateUtil.parse(monitorBaseParam.getSearchBeginTime()), DateUtil.parse(monitorBaseParam.getSearchEndTime()), DateField.MONTH);
            if (CollUtil.isNotEmpty(dataVerifyList)) {
                Map<String, Integer> map = dataVerifyList.stream().collect(Collectors.groupingBy(it -> it.getTime().format(DateTimeFormatter.ofPattern(DatePattern.NORM_MONTH_PATTERN)),
                        Collectors.mapping(DataVerify::getLineId, Collectors.collectingAndThen(Collectors.toSet(), Set::size))));
                for (DateTime dateTime : ranged) {
                    Map<String, Object> rangeMap = new HashMap<>();
                    String time = DateUtil.format(dateTime, DateTimeFormatter.ofPattern(DatePattern.NORM_MONTH_PATTERN));
                    rangeMap.put("time", time);
                    rangeMap.put("val", map.getOrDefault(time, 0));
                    result.add(rangeMap);
                }
            }
        }
        return result;
    }

    private DateRange getDateRange(MonitorBaseParam monitorBaseParam) {
        DateTime start = DateUtil.parse(monitorBaseParam.getSearchBeginTime());
        DateTime end = DateUtil.parse(monitorBaseParam.getSearchEndTime());
        return DateUtil.range(start, end, start.year() == end.year() && start.month() == end.month() ? DateField.DAY_OF_MONTH : DateField.MONTH);
    }


    /**
     * 指标异常测点数量
     */
    public List<VerifyTargetVO> getAbnormalTarget(List<DataVerify> dataVerifyList) {
        Map<String, Set<String>> dataMap = dataVerifyList.stream().collect(Collectors.groupingBy(it ->
                it.getIndexCode() + SEPARATOR + it.getIndexTable(), Collectors.mapping(DataVerify::getLineId, Collectors.toSet())));
        Map<String, PqReasonableRangeDto> rangeMap = getStandRange();
        //正序、负序和零序电压
        List<VerifyTargetVO> result = new ArrayList<>();
        dataMap.forEach((key, num) -> {
            if (rangeMap.containsKey(key)) {
                PqReasonableRangeDto desc = rangeMap.get(key);
                assembleEntity(num, desc, result);
            } else {
                logger.error("存在未知异常指标: {}", key);
            }
        });
        Map<String, VerifyTargetVO> vMap = result.stream().collect(Collectors.toMap(VerifyTargetVO::getKey, Function.identity()));
        Iterator<Map.Entry<String, PqReasonableRangeDto>> iterator = rangeMap.entrySet().iterator();
        while (iterator.hasNext()) {
            Map.Entry<String, PqReasonableRangeDto> entry = iterator.next();
            if (!vMap.containsKey(entry.getKey())) {
                PqReasonableRangeDto dto = entry.getValue();
                assembleEntity(new HashSet<>(), dto, result);
            }
        }
        return result.stream().sorted(Comparator.comparing(VerifyTargetVO::getSort)).collect(Collectors.toList());
    }

    /**
     * 组装实体
     */
    private void assembleEntity(Set<String> ids, PqReasonableRangeDto dto, List<VerifyTargetVO> result) {
        VerifyTargetVO verifyTargetVO = new VerifyTargetVO();
        verifyTargetVO.setKey(dto.getIndexCode() + SEPARATOR + dto.getInfluxdbTableName());
        verifyTargetVO.setTargetName(dto.getIndexName());
        verifyTargetVO.setIds(ids);
        verifyTargetVO.setRemark(dto.getRemark());
        verifyTargetVO.setSort(dto.getSort());
        String unit = "";
        if (StrUtil.isNotBlank(dto.getUnit())) {
            unit = dto.getUnit();
        }
        verifyTargetVO.setRangeDesc(dto.getMinValue() + unit + " ~ " + dto.getMaxValue() + unit);
        result.add(verifyTargetVO);
    }


    /**
     * 获取异常范围标准
     */
    private Map<String, PqReasonableRangeDto> getStandRange() {
        DataCleanParam dataCleanParam = new DataCleanParam();
        dataCleanParam.setSystemType(DataCleanEnum.Pqs.getCode());
        List<PqReasonableRangeDto> pqReasonableRangeDtoList = pqReasonableRangeFeignClient.getData(dataCleanParam).getData();
        return pqReasonableRangeDtoList.stream().collect(Collectors.toMap(it -> it.getIndexCode() + SEPARATOR + it.getInfluxdbTableName(), Function.identity()));
    }


    public List<PowerQualityIndicatorsVO> getAbnormalTable(List<DataVerify> dataVerifyList, MonitorBaseParam monitorBaseParam) {
        List<PowerQualityIndicatorsVO> result = new ArrayList<>();
        Map<String, List<DataVerify>> dataMap = dataVerifyList.stream().collect(Collectors.groupingBy(DataVerify::getLineId));
        dataMap.forEach((key, list) -> {
            List<LocalDate> dateList = list.stream().map(it -> it.getTime().toLocalDate()).distinct().sorted(Comparator.comparing(Function.identity())).collect(Collectors.toList());
            processTable(monitorBaseParam, dateList, result, key);
        });
        dealTableResult(result, monitorBaseParam.getSearchValue());
        return result;
    }


    public List<PowerQualityIndicatorsVO> getLimitTable(List<DataLimitTargetDto> dataVerifyList, MonitorBaseParam monitorBaseParam) {
        List<PowerQualityIndicatorsVO> result = new ArrayList<>();
        Map<String, List<DataLimitTargetDto>> dataMap = dataVerifyList.stream().collect(Collectors.groupingBy(DataLimitTargetDto::getLineId));
        dataMap.forEach((key, list) -> {
            List<LocalDate> dateList = list.stream().map(DataLimitTargetDto::getTime).distinct().sorted(Comparator.comparing(Function.identity())).collect(Collectors.toList());
            processTable(monitorBaseParam, dateList, result, key);
        });
        dealTableResult(result, monitorBaseParam.getSearchValue());
        return result;
    }


    /**
     * 判断测点是否存在连续异常数据
     */
    private void processTable(MonitorBaseParam monitorBaseParam, List<LocalDate> dateList, List<PowerQualityIndicatorsVO> result, String lineId) {
        Integer warnDay = monitorBaseParam.getWarnDayLimit();
        Integer alarmDay = monitorBaseParam.getAlarmDayLimit();
        //检查是否有连续指定天数的告警
        boolean warnFlag = verData(dateList, warnDay);
        boolean alarmFlag = verData(dateList, alarmDay);
        if (warnFlag) {
            PowerQualityIndicatorsVO vo = new PowerQualityIndicatorsVO();
            vo.setMonitorId(lineId);
            if (alarmFlag) {
                vo.setSeverity(1);
            } else {
                vo.setSeverity(0);
            }
            vo.setAbnormalDay(dateList.size());
            result.add(vo);
        }
    }

    private void dealTableResult(List<PowerQualityIndicatorsVO> result, String searchValue) {
        if (CollUtil.isNotEmpty(result)) {
//            List<SysDicTreePO> dicTreePOList = dictTreeFeignClient.queryAllByType(Integer.valueOf(DicDataEnum.Obj_Type.getCode())).getData();
//            Map<String, SysDicTreePO> sysDicTreePOMap = dicTreePOList.stream().collect(Collectors.toMap(SysDicTreePO::getId, Function.identity()));
            List<String> ids = result.stream().map(PowerQualityIndicatorsVO::getMonitorId).distinct().collect(Collectors.toList());
            List<AreaLineInfoVO> areaLineInfoVOList = lineMapper.getBaseLineAreaInfo(ids, searchValue, null);
            Map<String, PowerQualityIndicatorsVO> areaMap = result.stream().collect(Collectors.toMap(PowerQualityIndicatorsVO::getMonitorId, Function.identity()));
            List<DeptLine> deptLines = deptLineService.selectDeptLine(ids);
            Map<String, String> deptName = deptLines.stream().collect(Collectors.toMap(DeptLine::getLineId, DeptLine::getId));
//            List<String> objIds = areaLineInfoVOList.stream().map(AreaLineInfoVO::getObjId).distinct().collect(Collectors.toList());
//            List<NewUserReportVO> userLedgerVOList = userLedgerFeignClient.getUserReportByIds(objIds).getData();
//            Map<String, NewUserReportVO> userMap = userLedgerVOList.stream().collect(Collectors.toMap(NewUserReportVO::getId, Function.identity()));
            List<PowerQualityIndicatorsVO> info = new ArrayList<>();
            for (AreaLineInfoVO lineDetail : areaLineInfoVOList) {
                if (areaMap.containsKey(lineDetail.getLineId())) {
                    PowerQualityIndicatorsVO it = areaMap.get(lineDetail.getLineId());
                    it.setMonitorName(lineDetail.getLineName());
                    it.setStationName(lineDetail.getSubName());
                    if (deptName.containsKey(lineDetail.getLineId())) {
                        it.setCity(deptName.get(lineDetail.getLineId()));
                    }
                    it.setDevName(lineDetail.getDeviceName());
                    it.setVoltageLevel(lineDetail.getVoltageScale());
                    it.setIp(Base64.encode(lineDetail.getIp()));
                    it.setManufacturer(lineDetail.getManufacturer());
                    it.setObjType(lineDetail.getLoadType());
                    it.setObjName(lineDetail.getObjName());
                    info.add(it);
//                    if (sysDicTreePOMap.containsKey(areaLineInfoVO.getSmallObjType())) {
//                        it.setObjType(sysDicTreePOMap.get(areaLineInfoVO.getSmallObjType()).getName());
//                    }
//                    if (userMap.containsKey(areaLineInfoVO.getObjId())) {
//                        it.setObjName(userMap.get(areaLineInfoVO.getObjId()).getProjectName());
//                    }
                }
            }
            result.clear();
            result.addAll(info);
        }
    }

    /**
     * 检查日期列表中是否存在连续指定天数的异常
     *
     * @param dateList 日期列表（已排序）
     * @param day      连续天数阈值
     * @return 是否存在连续异常
     */
    private Boolean verData(List<LocalDate> dateList, Integer day) {
        for (int i = 0; i <= dateList.size() - day; i++) {
            boolean isConsecutive = true;
            for (int j = 1; j < day; j++) {
                if (!dateList.get(i).plusDays(j).equals(dateList.get(i + j))) {
                    isConsecutive = false;
                    break;
                }
            }
            if (isConsecutive) {
                return true;
            }
        }
        return false;
    }


}
