package com.njcn.csharmonic.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.nacos.shaded.com.google.gson.Gson;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.tocrhz.mqtt.publisher.MqttPublisher;
import com.google.common.collect.Lists;
import com.njcn.access.api.CsTopicFeignClient;
import com.njcn.access.enums.AccessEnum;
import com.njcn.access.enums.TypeEnum;
import com.njcn.access.pojo.dto.AskDataDto;
import com.njcn.access.pojo.dto.ReqAndResDto;
import com.njcn.csdevice.api.*;
import com.njcn.csdevice.pojo.dto.CsEquipmentDeliveryDTO;
import com.njcn.csdevice.pojo.dto.DevDetailDTO;
import com.njcn.csdevice.pojo.param.WlRecordParam;
import com.njcn.csdevice.pojo.po.CsDataSet;
import com.njcn.csdevice.pojo.po.CsEquipmentDeliveryPO;
import com.njcn.csdevice.pojo.po.CsLinePO;
import com.njcn.csdevice.pojo.po.WlRecord;
import com.njcn.csdevice.pojo.vo.DataGroupEventVO;
import com.njcn.csdevice.pojo.vo.EachModuleVO;
import com.njcn.csdevice.pojo.vo.RecordVo;
import com.njcn.csdevice.utils.DataChangeUtil;
import com.njcn.csdevice.utils.ReflectUtils;
import com.njcn.csharmonic.constant.HarmonicConstant;
import com.njcn.csharmonic.param.DataParam;
import com.njcn.csharmonic.param.ItemParam;
import com.njcn.csharmonic.pojo.po.CsEventPO;
import com.njcn.csharmonic.pojo.vo.AppLineDetailVo;
import com.njcn.csharmonic.service.CsEventPOService;
import com.njcn.csharmonic.service.IDataService;
import com.njcn.influx.imapper.*;
import com.njcn.influx.pojo.bo.CommonQueryParam;
import com.njcn.influx.pojo.dto.EventDataSetDTO;
import com.njcn.influx.pojo.dto.StatisticalDataDTO;
import com.njcn.influx.pojo.po.*;
import com.njcn.influx.pojo.po.cs.ApfData;
import com.njcn.influx.query.InfluxQueryWrapper;
import com.njcn.influx.service.CommonService;
import com.njcn.influx.service.EvtDataService;
import com.njcn.redis.pojo.enums.AppRedisKey;
import com.njcn.redis.utils.RedisUtil;
import com.njcn.system.api.*;
import com.njcn.system.pojo.po.*;
import lombok.AllArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.time.Duration;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * 类的介绍：
 *
 * @author xuyang
 * @version 1.0.0
 * @createTime 2023/6/1 10:11
 */
@Service
@AllArgsConstructor
public class DataServiceImpl implements IDataService {

    private final CommonService commonService;
    private final CsStatisticalSetFeignClient csStatisticalSetFeignClient;
    private final DictTreeFeignClient dictTreeFeignClient;
    private final CsLineFeignClient csLineFeignClient;
    private final WlRecordFeignClient wlRecordFeignClient;
    private final CsEventPOService csEventPOService;
    private final DecimalFormat df = new DecimalFormat("#0.00");
    private final EpdFeignClient epdFeignClient;
    private final EvtDataService evtDataService;
    private final EleEvtFeignClient eleEvtFeignClient;
    private final EquipmentFeignClient equipmentFeignClient;
    private final RedisUtil redisUtil;
    private static Integer mid = 1;
    private final CsTopicFeignClient csTopicFeignClient;
    private final MqttPublisher publisher;
    private final CsLedgerFeignClient csLedgerFeignClient;
    private final DicDataFeignClient dicDataFeignClient;
    @Resource
    private DataVMapper dataVMapper;
    @Resource
    private DataIMapper dataIMapper;
    @Resource
    private DataFlickerMapper dataFlickerMapper;
    @Resource
    private DataFlucMapper dataFlucMapper;
    @Resource
    private DataHarmPhasicVMapper dataHarmPhasicVMapper;
    @Resource
    private DataHarmPhasicIMapper dataHarmPhasicIMapper;
    @Resource
    private DataHarmPowerPMapper dataHarmPowerPMapper;
    @Resource
    private DataHarmPowerQMapper dataHarmPowerQMapper;
    @Resource
    private DataHarmPowerSMapper dataHarmPowerSMapper;
    @Resource
    private DataHarmRateVMapper dataHarmRateVMapper;
    @Resource
    private DataHarmRateIMapper dataHarmRateIMapper;
    @Resource
    private DataInHarmVMapper dataInHarmVMapper;
    @Resource
    private DataPltMapper dataPltMapper;
    @Resource
    private ApfDataMapper apfDataMapper;
    private final DataSetFeignClient dataSetFeignClient;
    private final static Double NULL_DATA = 3.14159;

    @Override
    public List<AppLineDetailVo> getRealTimeData(DataParam param) {
        List<AppLineDetailVo> result = new ArrayList<>();
        List<DataV> data1 = new ArrayList<>();
        List<DataI> data2 = new ArrayList<>();
        List<DataFlicker> data3 = new ArrayList<>();
        List<DataFluc> data4 = new ArrayList<>();
        List<DataHarmPhasicV> data5 = new ArrayList<>();
        List<DataHarmPhasicI> data6 = new ArrayList<>();
        List<DataHarmPowerP> data7 = new ArrayList<>();
        List<DataHarmPowerQ> data8 = new ArrayList<>();
        List<DataHarmPowerS> data9 = new ArrayList<>();
        List<DataHarmRateV> data10 = new ArrayList<>();
        List<DataHarmRateI> data11 = new ArrayList<>();
        List<DataInHarmV> data12 = new ArrayList<>();
        List<DataPlt> data13 = new ArrayList<>();
        List<ApfData> data14 = new ArrayList<>();

        List<CsLinePO> linePo = csLineFeignClient.queryLineById(Collections.singletonList(param.getLineId())).getData();
        Double ct = Objects.isNull(linePo.get(0).getCtRatio())?1.0:linePo.get(0).getCtRatio() / (Objects.isNull(linePo.get(0).getCt2Ratio())?1.0:linePo.get(0).getCt2Ratio());
        Double pt = Objects.isNull(linePo.get(0).getPtRatio())?1.0:linePo.get(0).getPtRatio() / (Objects.isNull(linePo.get(0).getPt2Ratio())?1.0:linePo.get(0).getPt2Ratio());
        Map<String,CsLinePO> lineMap = linePo.stream().collect(Collectors.toMap(CsLinePO::getLineId, item->item));
        //拆分治理监测点 、 监测监测点
        List<CsLinePO> line1 = linePo.stream().filter(item->item.getClDid()==0).collect(Collectors.toList());
        List<CsLinePO> line2 = linePo.stream().filter(item->item.getClDid()!=0).collect(Collectors.toList());
        List<String> lineList2 = line2.stream().map(CsLinePO::getLineId).collect(Collectors.toList());
        List<List<String>> partitions = Lists.partition(lineList2, 95);

        //表集合
        List<DictData> dataList = dicDataFeignClient.getDicDataByTypeCode("Data").getData();
        Map<String, DictData> map = dataList.stream().collect(Collectors.toMap(DictData::getId, v -> v));
        //获取需要查询的指标
        SysDicTreePO po = dictTreeFeignClient.queryById(param.getTargetType()).getData();
        List<SysDicTreePO> list = dictTreeFeignClient.queryByCodeList(po.getCode()).getData();
        List<SysDicTreePO> children = list.get(0).getChildren();
        children.sort(Comparator.comparing(SysDicTreePO::getSort));
        List<String> idList = children.stream().map(SysDicTreePO::getId).collect(Collectors.toList());
        List<EleEpdPqd> epdPqdList = csStatisticalSetFeignClient.queryStatisticalSelect(idList).getData();
        Map<String,List<EleEpdPqd>> epdPqdMap = epdPqdList.stream().collect(Collectors.groupingBy(EleEpdPqd::getClassId));
        Map<String,EleEpdPqd> epdPqdMap2 = epdPqdList.stream().collect(Collectors.toMap(EleEpdPqd::getId, v -> v));
        //获取监测点的数据集，转换一二次值
        List<String> dataSetIdList = linePo.stream().map(CsLinePO::getDataSetId).distinct().collect(Collectors.toList());
        List<CsDataSet> csDataSetList = dataSetFeignClient.getDataSetBySetIds(dataSetIdList).getData();
        Map<String,CsDataSet> csDataSetMap = csDataSetList.stream().collect(Collectors.toMap(CsDataSet::getId, v -> v));
        //获取指标名称和对应的指标集合
        List<CsStatisticalSetPO> csStatisticalSetPOList = csStatisticalSetFeignClient.queryStatisticalById(idList).getData();
        Map<String,List<CsStatisticalSetPO>> csStatisticalSetPOMap = csStatisticalSetPOList.stream().collect(Collectors.groupingBy(CsStatisticalSetPO::getStatisicalId));
        epdPqdMap.forEach((k,v) ->{
            if (Objects.equals(map.get(k).getName(), "data_v")) {
                partitions.forEach(l -> {
                    InfluxQueryWrapper influxQueryWrapper = new InfluxQueryWrapper(DataV.class);
                    v.forEach(item->{
                        if (!Objects.isNull(item.getHarmStart()) && !Objects.isNull(item.getHarmEnd())) {
                            for (int i = item.getHarmStart(); i <= item.getHarmEnd(); i++) {
                                influxQueryWrapper.select(item.getOtherName() + "_" + i,item.getOtherName() + "_" + i);
                            }
                        } else{
                            influxQueryWrapper.select(item.getOtherName(),item.getOtherName());
                        }
                    });
                    influxQueryWrapper.regular(DataV::getLineId, l)
                            .eq(DataV::getValueType,"AVG")
                            .groupBy(DataV::getPhaseType)
                            .groupBy(DataV::getLineId)
                            .timeDesc().limit(1);
                    List<DataV> dataV = dataVMapper.selectByQueryWrapper(influxQueryWrapper);
                    data1.addAll(dataV);
                });
            } else if (Objects.equals(map.get(k).getName(), "data_i")){
                partitions.forEach(l -> {
                    InfluxQueryWrapper influxQueryWrapper = new InfluxQueryWrapper(DataI.class);
                    v.forEach(item->{
                        if (!Objects.isNull(item.getHarmStart()) && !Objects.isNull(item.getHarmEnd())) {
                            for (int i = item.getHarmStart(); i <= item.getHarmEnd(); i++) {
                                influxQueryWrapper.select(item.getOtherName() + "_" + i,item.getOtherName() + "_" + i);
                            }
                        } else{
                            influxQueryWrapper.select(item.getOtherName(),item.getOtherName());
                        }
                    });
                    influxQueryWrapper.regular(DataI::getLineId, l)
                            .eq(DataI::getValueType,"AVG")
                            .groupBy(DataI::getPhaseType)
                            .groupBy(DataI::getLineId)
                            .timeDesc().limit(1);
                    List<DataI> dataI = dataIMapper.selectByQueryWrapper(influxQueryWrapper);
                    data2.addAll(dataI);
                });
            } else if (Objects.equals(map.get(k).getName(), "data_flicker")){
                partitions.forEach(l -> {
                    InfluxQueryWrapper influxQueryWrapper = new InfluxQueryWrapper(DataFlicker.class);
                    v.stream().map(EleEpdPqd::getOtherName).distinct().forEach(otherName -> influxQueryWrapper.select(otherName, otherName));
                    influxQueryWrapper.regular(DataFlicker::getLineId, l)
                            .eq(DataFlicker::getValueType,"AVG")
                            .groupBy(DataFlicker::getPhaseType)
                            .groupBy(DataFlicker::getLineId)
                            .timeDesc().limit(1);
                    List<DataFlicker> dataFlicker = dataFlickerMapper.selectByQueryWrapper(influxQueryWrapper);
                    data3.addAll(dataFlicker);
                });
            } else if (Objects.equals(map.get(k).getName(), "data_fluc")){
                partitions.forEach(l -> {
                    InfluxQueryWrapper influxQueryWrapper = new InfluxQueryWrapper(DataFluc.class);
                    v.stream().map(EleEpdPqd::getOtherName).distinct().forEach(otherName -> influxQueryWrapper.select(otherName, otherName));
                    influxQueryWrapper.regular(DataFluc::getLineId, l)
                            .eq(DataFluc::getValueType,"AVG")
                            .groupBy(DataFluc::getPhaseType)
                            .groupBy(DataFluc::getLineId)
                            .timeDesc().limit(1);
                    List<DataFluc> dataFluc = dataFlucMapper.selectByQueryWrapper(influxQueryWrapper);
                    data4.addAll(dataFluc);
                });
            } else if (Objects.equals(map.get(k).getName(), "data_harmphasic_v")){
                partitions.forEach(l -> {
                    InfluxQueryWrapper influxQueryWrapper = new InfluxQueryWrapper(DataHarmPhasicV.class);
                    v.forEach(item->{
                        if (!Objects.isNull(item.getHarmStart()) && !Objects.isNull(item.getHarmEnd())) {
                            for (int i = item.getHarmStart(); i <= item.getHarmEnd(); i++) {
                                influxQueryWrapper.select(item.getOtherName() + "_" + i,item.getOtherName() + "_" + i);
                            }
                        } else{
                            influxQueryWrapper.select(item.getOtherName(),item.getOtherName());
                        }
                    });
                    influxQueryWrapper.regular(DataHarmPhasicV::getLineId, l)
                            .eq(DataHarmPhasicV::getValueType,"AVG")
                            .groupBy(DataHarmPhasicV::getPhaseType)
                            .groupBy(DataHarmPhasicV::getLineId)
                            .timeDesc().limit(1);
                    List<DataHarmPhasicV> dataHarmPhasicV = dataHarmPhasicVMapper.selectByQueryWrapper(influxQueryWrapper);
                    data5.addAll(dataHarmPhasicV);
                });
            } else if (Objects.equals(map.get(k).getName(), "data_harmphasic_i")){
                partitions.forEach(l -> {
                    InfluxQueryWrapper influxQueryWrapper = new InfluxQueryWrapper(DataHarmPhasicI.class);
                    v.forEach(item->{
                        if (!Objects.isNull(item.getHarmStart()) && !Objects.isNull(item.getHarmEnd())) {
                            for (int i = item.getHarmStart(); i <= item.getHarmEnd(); i++) {
                                influxQueryWrapper.select(item.getOtherName() + "_" + i,item.getOtherName() + "_" + i);
                            }
                        } else{
                            influxQueryWrapper.select(item.getOtherName(),item.getOtherName());
                        }
                    });
                    influxQueryWrapper.regular(DataHarmPhasicI::getLineId, l)
                            .eq(DataHarmPhasicI::getValueType,"AVG")
                            .groupBy(DataHarmPhasicI::getPhaseType)
                            .groupBy(DataHarmPhasicI::getLineId)
                            .timeDesc().limit(1);
                    List<DataHarmPhasicI> dataHarmPhasicI = dataHarmPhasicIMapper.selectByQueryWrapper(influxQueryWrapper);
                    data6.addAll(dataHarmPhasicI);
                });
            } else if (Objects.equals(map.get(k).getName(), "data_harmpower_p")){
                partitions.forEach(l -> {
                    InfluxQueryWrapper influxQueryWrapper = new InfluxQueryWrapper(DataHarmPowerP.class);
                    v.forEach(item->{
                        if (!Objects.isNull(item.getHarmStart()) && !Objects.isNull(item.getHarmEnd())) {
                            for (int i = item.getHarmStart(); i <= item.getHarmEnd(); i++) {
                                influxQueryWrapper.select(item.getOtherName() + "_" + i,item.getOtherName() + "_" + i);
                            }
                        } else{
                            influxQueryWrapper.select(item.getOtherName(),item.getOtherName());
                        }
                    });
                    influxQueryWrapper.regular(DataHarmPowerP::getLineId, l)
                            .eq(DataHarmPowerP::getValueType,"AVG")
                            .groupBy(DataHarmPowerP::getPhaseType)
                            .groupBy(DataHarmPowerP::getLineId)
                            .timeDesc().limit(1);
                    List<DataHarmPowerP> dataHarmPowerP = dataHarmPowerPMapper.selectByQueryWrapper(influxQueryWrapper);
                    data7.addAll(dataHarmPowerP);
                });
            } else if (Objects.equals(map.get(k).getName(), "data_harmpower_q")){
                partitions.forEach(l -> {
                    InfluxQueryWrapper influxQueryWrapper = new InfluxQueryWrapper(DataHarmPowerQ.class);
                    v.forEach(item->{
                        if (!Objects.isNull(item.getHarmStart()) && !Objects.isNull(item.getHarmEnd())) {
                            for (int i = item.getHarmStart(); i <= item.getHarmEnd(); i++) {
                                influxQueryWrapper.select(item.getOtherName() + "_" + i,item.getOtherName() + "_" + i);
                            }
                        } else{
                            influxQueryWrapper.select(item.getOtherName(),item.getOtherName());
                        }
                    });
                    influxQueryWrapper.regular(DataHarmPowerQ::getLineId, l)
                            .eq(DataHarmPowerQ::getValueType,"AVG")
                            .groupBy(DataHarmPowerQ::getPhaseType)
                            .groupBy(DataHarmPowerQ::getLineId)
                            .timeDesc().limit(1);
                    List<DataHarmPowerQ> dataHarmPowerQ = dataHarmPowerQMapper.selectByQueryWrapper(influxQueryWrapper);
                    data8.addAll(dataHarmPowerQ);
                });
            } else if (Objects.equals(map.get(k).getName(), "data_harmpower_s")){
                partitions.forEach(l -> {
                    InfluxQueryWrapper influxQueryWrapper = new InfluxQueryWrapper(DataHarmPowerS.class);
                    v.forEach(item->{
                        if (!Objects.isNull(item.getHarmStart()) && !Objects.isNull(item.getHarmEnd())) {
                            for (int i = item.getHarmStart(); i <= item.getHarmEnd(); i++) {
                                influxQueryWrapper.select(item.getOtherName() + "_" + i,item.getOtherName() + "_" + i);
                            }
                        } else{
                            influxQueryWrapper.select(item.getOtherName(),item.getOtherName());
                        }
                    });
                    influxQueryWrapper.regular(DataHarmPowerS::getLineId, l)
                            .eq(DataHarmPowerS::getValueType,"AVG")
                            .groupBy(DataHarmPowerS::getPhaseType)
                            .groupBy(DataHarmPowerS::getLineId)
                            .timeDesc().limit(1);
                    List<DataHarmPowerS> dataHarmPowerS = dataHarmPowerSMapper.selectByQueryWrapper(influxQueryWrapper);
                    data9.addAll(dataHarmPowerS);
                });
            } else if (Objects.equals(map.get(k).getName(), "data_harmrate_v")){
                partitions.forEach(l -> {
                    InfluxQueryWrapper influxQueryWrapper = new InfluxQueryWrapper(DataHarmRateV.class);
                    v.forEach(item->{
                        if (!Objects.isNull(item.getHarmStart()) && !Objects.isNull(item.getHarmEnd())) {
                            for (int i = item.getHarmStart(); i <= item.getHarmEnd(); i++) {
                                influxQueryWrapper.select(item.getOtherName() + "_" + i,item.getOtherName() + "_" + i);
                            }
                        } else{
                            influxQueryWrapper.select(item.getOtherName(),item.getOtherName());
                        }
                    });
                    influxQueryWrapper.regular(DataHarmRateV::getLineId, l)
                            .eq(DataHarmRateV::getValueType,"AVG")
                            .groupBy(DataHarmRateV::getPhaseType)
                            .groupBy(DataHarmRateV::getLineId)
                            .timeDesc().limit(1);
                    List<DataHarmRateV> dataHarmRateV = dataHarmRateVMapper.selectByQueryWrapper(influxQueryWrapper);
                    data10.addAll(dataHarmRateV);
                });
            } else if (Objects.equals(map.get(k).getName(), "data_harmrate_i")){
                partitions.forEach(l -> {
                    InfluxQueryWrapper influxQueryWrapper = new InfluxQueryWrapper(DataHarmRateI.class);
                    v.forEach(item->{
                        if (!Objects.isNull(item.getHarmStart()) && !Objects.isNull(item.getHarmEnd())) {
                            for (int i = item.getHarmStart(); i <= item.getHarmEnd(); i++) {
                                influxQueryWrapper.select(item.getOtherName() + "_" + i,item.getOtherName() + "_" + i);
                            }
                        } else{
                            influxQueryWrapper.select(item.getOtherName(),item.getOtherName());
                        }
                    });
                    influxQueryWrapper.regular(DataHarmRateI::getLineId, l)
                            .eq(DataHarmRateI::getValueType,"AVG")
                            .groupBy(DataHarmRateI::getPhaseType)
                            .groupBy(DataHarmRateI::getLineId)
                            .timeDesc().limit(1);
                    List<DataHarmRateI> DataHarmRateI = dataHarmRateIMapper.selectByQueryWrapper(influxQueryWrapper);
                    data11.addAll(DataHarmRateI);
                });
            } else if (Objects.equals(map.get(k).getName(), "data_inharm_v")){
                partitions.forEach(l -> {
                    InfluxQueryWrapper influxQueryWrapper = new InfluxQueryWrapper(DataInHarmV.class);
                    v.forEach(item->{
                        if (!Objects.isNull(item.getHarmStart()) && !Objects.isNull(item.getHarmEnd())) {
                            for (int i = item.getHarmStart(); i <= item.getHarmEnd(); i++) {
                                influxQueryWrapper.select(item.getOtherName() + "_" + i,item.getOtherName() + "_" + i);
                            }
                        } else{
                            influxQueryWrapper.select(item.getOtherName(),item.getOtherName());
                        }
                    });
                    influxQueryWrapper.regular(DataInHarmV::getLineId, l)
                            .eq(DataInHarmV::getValueType,"AVG")
                            .groupBy(DataInHarmV::getPhaseType)
                            .groupBy(DataInHarmV::getLineId)
                            .timeDesc().limit(1);
                    List<DataInHarmV> dataInHarmV = dataInHarmVMapper.selectByQueryWrapper(influxQueryWrapper);
                    data12.addAll(dataInHarmV);
                });
            } else if (Objects.equals(map.get(k).getName(), "data_plt")){
                partitions.forEach(l -> {
                    InfluxQueryWrapper influxQueryWrapper = new InfluxQueryWrapper(DataPlt.class);
                    v.stream().map(EleEpdPqd::getOtherName).distinct().forEach(otherName -> influxQueryWrapper.select(otherName, otherName));
                    influxQueryWrapper.regular(DataPlt::getLineId, l)
                            .eq(DataPlt::getValueType,"AVG")
                            .groupBy(DataPlt::getPhaseType)
                            .groupBy(DataPlt::getLineId)
                            .timeDesc().limit(1);
                    List<DataPlt> dataPlt = dataPltMapper.selectByQueryWrapper(influxQueryWrapper);
                    data13.addAll(dataPlt);
                });
            }
        });
        //监测点第一层
        line2.forEach(item->{
            AppLineDetailVo vo = new AppLineDetailVo();
            vo.setLineType(1);
            vo.setPointId(item.getLineId());
            vo.setPointName(lineMap.get(item.getLineId()).getName());
            List<AppLineDetailVo.targetDetail> children2 = new ArrayList<>();
            //指标第二层
            List<AppLineDetailVo.targetDetail> finalChildren = children2;
            children.forEach(item3->{
                List<CsStatisticalSetPO> l1 = csStatisticalSetPOMap.get(item3.getId());
                if (CollUtil.isEmpty(l1)) {
                    return;
                }
                List<EleEpdPqd> list1 = new ArrayList<>();
                l1.forEach(item1 -> {
                    list1.add(epdPqdMap2.get(item1.getTargetId()));
                });
                list1.sort(Comparator.comparingInt(EleEpdPqd::getSort));
                list1.forEach(epdPqd -> {
                    AppLineDetailVo.targetDetail targetDetail = new AppLineDetailVo.targetDetail();
                    targetDetail.setTargetId(item3.getId());
                    targetDetail.setName(item3.getName());
                    targetDetail.setPhase(epdPqd.getPhase());
                    targetDetail.setUnit(epdPqd.getUnit());
                    targetDetail.setSort(item3.getSort());
                    targetDetail.setPrimaryFormula(epdPqd.getPrimaryFormula());
                    targetDetail.setOtherName(epdPqd.getShowName());
                    targetDetail.setOtherNameUnit(epdPqd.getUnit());
                    if (Objects.equals(map.get(epdPqd.getClassId()).getName(), "data_v")) {
                        if (!Objects.isNull(epdPqd.getHarmStart()) && !Objects.isNull(epdPqd.getHarmEnd())) {
                            for (int i = epdPqd.getHarmStart(); i <= epdPqd.getHarmEnd(); i++) {
                                AppLineDetailVo.targetDetail t1 = new AppLineDetailVo.targetDetail();
                                t1.setTargetId(item3.getId());
                                t1.setName(item3.getName());
                                t1.setPhase(epdPqd.getPhase());
                                t1.setUnit(epdPqd.getUnit());
                                t1.setSort(item3.getSort());
                                t1.setPrimaryFormula(epdPqd.getPrimaryFormula());
                                //根据otherName反射获取DataV中的字段值，按lineId和相别匹配
                                String otherName = epdPqd.getOtherName();
                                DataV matchedDataV = data1.stream()
                                        .filter(d -> Objects.equals(d.getLineId(), item.getLineId())
                                                && Objects.equals(d.getPhaseType(), epdPqd.getPhase()))
                                        .findFirst()
                                        .orElse(null);
                                if (matchedDataV != null) {
                                    Object value = ReflectUtils.getValue(matchedDataV, toCamelCase(otherName));
                                    if (value instanceof Number) {
                                        t1.setData(((Number) value).doubleValue());
                                    }
                                    vo.setDataTime(matchedDataV.getTime());
                                }
                                t1.setName(i + "次" + item3.getName());
                                finalChildren.add(t1);
                            }
                        } else {
                            //根据otherName反射获取DataV中的字段值，按lineId和相别匹配
                            String otherName = epdPqd.getOtherName();
                            DataV matchedDataV = data1.stream()
                                    .filter(d -> Objects.equals(d.getLineId(), item.getLineId())
                                            && Objects.equals(d.getPhaseType(), epdPqd.getPhase()))
                                    .findFirst()
                                    .orElse(null);
                            if (matchedDataV != null) {
                                Object value = ReflectUtils.getValue(matchedDataV, toCamelCase(otherName));
                                if (value instanceof Number) {
                                    targetDetail.setData(((Number) value).doubleValue());
                                }
                                vo.setDataTime(matchedDataV.getTime());
                            }
                        }
                    } else if (Objects.equals(map.get(epdPqd.getClassId()).getName(), "data_i")) {
                        if (!Objects.isNull(epdPqd.getHarmStart()) && !Objects.isNull(epdPqd.getHarmEnd())) {
                            for (int i = epdPqd.getHarmStart(); i <= epdPqd.getHarmEnd(); i++) {
                                AppLineDetailVo.targetDetail t1 = new AppLineDetailVo.targetDetail();
                                t1.setTargetId(item3.getId());
                                t1.setName(item3.getName());
                                t1.setPhase(epdPqd.getPhase());
                                t1.setUnit(epdPqd.getUnit());
                                t1.setSort(item3.getSort());
                                t1.setPrimaryFormula(epdPqd.getPrimaryFormula());
                                //根据otherName反射获取DataV中的字段值，按lineId和相别匹配
                                String otherName = epdPqd.getOtherName();
                                DataI matchedDataV = data2.stream()
                                        .filter(d -> Objects.equals(d.getLineId(), item.getLineId())
                                                && Objects.equals(d.getPhaseType(), epdPqd.getPhase()))
                                        .findFirst()
                                        .orElse(null);
                                if (matchedDataV != null) {
                                    Object value = ReflectUtils.getValue(matchedDataV, toCamelCase(otherName + "_" + i));
                                    if (value instanceof Number) {
                                        t1.setData(((Number) value).doubleValue());
                                    }
                                    vo.setDataTime(matchedDataV.getTime());
                                }
                                t1.setName(i + "次" + item3.getName());
                                finalChildren.add(t1);
                            }
                        } else {
                            //根据otherName反射获取DataV中的字段值，按lineId和相别匹配
                            String otherName = epdPqd.getOtherName();
                            DataI matchedDataV = data2.stream()
                                    .filter(d -> Objects.equals(d.getLineId(), item.getLineId())
                                            && Objects.equals(d.getPhaseType(), epdPqd.getPhase()))
                                    .findFirst()
                                    .orElse(null);
                            if (matchedDataV != null) {
                                Object value = ReflectUtils.getValue(matchedDataV, toCamelCase(otherName));
                                if (value instanceof Number) {
                                    targetDetail.setData(((Number) value).doubleValue());
                                }
                                vo.setDataTime(matchedDataV.getTime());
                            }
                        }
                    } else if (Objects.equals(map.get(epdPqd.getClassId()).getName(), "data_flicker")) {
                        //根据otherName反射获取DataV中的字段值，按lineId和相别匹配
                        String otherName = epdPqd.getOtherName();
                        DataFlicker matchedDataV = data3.stream()
                                .filter(d -> Objects.equals(d.getLineId(), item.getLineId())
                                        && Objects.equals(d.getPhaseType(), epdPqd.getPhase()))
                                .findFirst()
                                .orElse(null);
                        if (matchedDataV != null) {
                            Object value = ReflectUtils.getValue(matchedDataV, toCamelCase(otherName));
                            if (value instanceof Number) {
                                targetDetail.setData(((Number) value).doubleValue());
                            }
                            vo.setDataTime(matchedDataV.getTime());
                        }
                    } else if (Objects.equals(map.get(epdPqd.getClassId()).getName(), "data_fluc")) {
                        //根据otherName反射获取DataV中的字段值，按lineId和相别匹配
                        String otherName = epdPqd.getOtherName();
                        DataFluc matchedDataV = data4.stream()
                                .filter(d -> Objects.equals(d.getLineId(), item.getLineId())
                                        && Objects.equals(d.getPhaseType(), epdPqd.getPhase()))
                                .findFirst()
                                .orElse(null);
                        if (matchedDataV != null) {
                            Object value = ReflectUtils.getValue(matchedDataV, toCamelCase(otherName));
                            if (value instanceof Number) {
                                targetDetail.setData(((Number) value).doubleValue());
                            }
                            vo.setDataTime(matchedDataV.getTime());
                        }
                    } else if (Objects.equals(map.get(epdPqd.getClassId()).getName(), "data_harmphasic_v")) {
                        if (!Objects.isNull(epdPqd.getHarmStart()) && !Objects.isNull(epdPqd.getHarmEnd())) {
                            for (int i = epdPqd.getHarmStart(); i <= epdPqd.getHarmEnd(); i++) {
                                AppLineDetailVo.targetDetail t1 = new AppLineDetailVo.targetDetail();
                                t1.setTargetId(item3.getId());
                                t1.setName(item3.getName());
                                t1.setPhase(epdPqd.getPhase());
                                t1.setUnit(epdPqd.getUnit());
                                t1.setSort(item3.getSort());
                                t1.setPrimaryFormula(epdPqd.getPrimaryFormula());
                                //根据otherName反射获取DataV中的字段值，按lineId和相别匹配
                                String otherName = epdPqd.getOtherName();
                                DataHarmPhasicV matchedDataV = data5.stream()
                                        .filter(d -> Objects.equals(d.getLineId(), item.getLineId())
                                                && Objects.equals(d.getPhaseType(), epdPqd.getPhase()))
                                        .findFirst()
                                        .orElse(null);
                                if (matchedDataV != null) {
                                    Object value = ReflectUtils.getValue(matchedDataV, toCamelCase(otherName + "_" + i));
                                    if (value instanceof Number) {
                                        t1.setData(((Number) value).doubleValue());
                                    }
                                    vo.setDataTime(matchedDataV.getTime());
                                }
                                t1.setName(i + "次" + item3.getName());
                                finalChildren.add(t1);
                            }
                        } else {
                            //根据otherName反射获取DataV中的字段值，按lineId和相别匹配
                            String otherName = epdPqd.getOtherName();
                            DataHarmPhasicV matchedDataV = data5.stream()
                                    .filter(d -> Objects.equals(d.getLineId(), item.getLineId())
                                            && Objects.equals(d.getPhaseType(), epdPqd.getPhase()))
                                    .findFirst()
                                    .orElse(null);
                            if (matchedDataV != null) {
                                Object value = ReflectUtils.getValue(matchedDataV, toCamelCase(otherName));
                                if (value instanceof Number) {
                                    targetDetail.setData(((Number) value).doubleValue());
                                }
                                vo.setDataTime(matchedDataV.getTime());
                            }
                        }
                    } else if (Objects.equals(map.get(epdPqd.getClassId()).getName(), "data_harmphasic_i")) {
                        if (!Objects.isNull(epdPqd.getHarmStart()) && !Objects.isNull(epdPqd.getHarmEnd())) {
                            for (int i = epdPqd.getHarmStart(); i <= epdPqd.getHarmEnd(); i++) {
                                AppLineDetailVo.targetDetail t1 = new AppLineDetailVo.targetDetail();
                                t1.setTargetId(item3.getId());
                                t1.setName(item3.getName());
                                t1.setPhase(epdPqd.getPhase());
                                t1.setUnit(epdPqd.getUnit());
                                t1.setSort(item3.getSort());
                                t1.setPrimaryFormula(epdPqd.getPrimaryFormula());
                                //根据otherName反射获取DataV中的字段值，按lineId和相别匹配
                                String otherName = epdPqd.getOtherName();
                                DataHarmPhasicI matchedDataV = data6.stream()
                                        .filter(d -> Objects.equals(d.getLineId(), item.getLineId())
                                                && Objects.equals(d.getPhaseType(), epdPqd.getPhase()))
                                        .findFirst()
                                        .orElse(null);
                                if (matchedDataV != null) {
                                    Object value = ReflectUtils.getValue(matchedDataV, toCamelCase(otherName + "_" + i));
                                    if (value instanceof Number) {
                                        t1.setData(((Number) value).doubleValue());
                                    }
                                    vo.setDataTime(matchedDataV.getTime());
                                }
                                t1.setName(i + "次" + item3.getName());
                                finalChildren.add(t1);
                            }
                        } else {
                            //根据otherName反射获取DataV中的字段值，按lineId和相别匹配
                            String otherName = epdPqd.getOtherName();
                            DataHarmPhasicI matchedDataV = data6.stream()
                                    .filter(d -> Objects.equals(d.getLineId(), item.getLineId())
                                            && Objects.equals(d.getPhaseType(), epdPqd.getPhase()))
                                    .findFirst()
                                    .orElse(null);
                            if (matchedDataV != null) {
                                Object value = ReflectUtils.getValue(matchedDataV, toCamelCase(otherName));
                                if (value instanceof Number) {
                                    targetDetail.setData(((Number) value).doubleValue());
                                }
                                vo.setDataTime(matchedDataV.getTime());
                            }
                        }
                    } else if (Objects.equals(map.get(epdPqd.getClassId()).getName(), "data_harmpower_p")) {
                        if (!Objects.isNull(epdPqd.getHarmStart()) && !Objects.isNull(epdPqd.getHarmEnd())) {
                            for (int i = epdPqd.getHarmStart(); i <= epdPqd.getHarmEnd(); i++) {
                                AppLineDetailVo.targetDetail t1 = new AppLineDetailVo.targetDetail();
                                t1.setTargetId(item3.getId());
                                t1.setName(item3.getName());
                                t1.setPhase(epdPqd.getPhase());
                                t1.setUnit(epdPqd.getUnit());
                                t1.setSort(item3.getSort());
                                t1.setPrimaryFormula(epdPqd.getPrimaryFormula());
                                //根据otherName反射获取DataV中的字段值，按lineId和相别匹配
                                String otherName = epdPqd.getOtherName();
                                DataHarmPowerP matchedDataV = data7.stream()
                                        .filter(d -> Objects.equals(d.getLineId(), item.getLineId())
                                                && Objects.equals(d.getPhaseType(), epdPqd.getPhase()))
                                        .findFirst()
                                        .orElse(null);
                                if (matchedDataV != null) {
                                    Object value = ReflectUtils.getValue(matchedDataV, toCamelCase(otherName + "_" + i));
                                    if (value instanceof Number) {
                                        t1.setData(((Number) value).doubleValue());
                                    }
                                    vo.setDataTime(matchedDataV.getTime());
                                }
                                t1.setName(i + "次" + item3.getName());
                                finalChildren.add(t1);
                            }
                        } else {
                            //根据otherName反射获取DataV中的字段值，按lineId和相别匹配
                            String otherName = epdPqd.getOtherName();
                            DataHarmPowerP matchedDataV = data7.stream()
                                    .filter(d -> Objects.equals(d.getLineId(), item.getLineId())
                                            && Objects.equals(d.getPhaseType(), epdPqd.getPhase()))
                                    .findFirst()
                                    .orElse(null);
                            if (matchedDataV != null) {
                                Object value = ReflectUtils.getValue(matchedDataV, toCamelCase(otherName));
                                if (value instanceof Number) {
                                    targetDetail.setData(((Number) value).doubleValue());
                                }
                                vo.setDataTime(matchedDataV.getTime());
                            }
                        }
                    } else if (Objects.equals(map.get(epdPqd.getClassId()).getName(), "data_harmpower_q")) {
                        if (!Objects.isNull(epdPqd.getHarmStart()) && !Objects.isNull(epdPqd.getHarmEnd())) {
                            for (int i = epdPqd.getHarmStart(); i <= epdPqd.getHarmEnd(); i++) {
                                AppLineDetailVo.targetDetail t1 = new AppLineDetailVo.targetDetail();
                                t1.setTargetId(item3.getId());
                                t1.setName(item3.getName());
                                t1.setPhase(epdPqd.getPhase());
                                t1.setUnit(epdPqd.getUnit());
                                t1.setSort(item3.getSort());
                                t1.setPrimaryFormula(epdPqd.getPrimaryFormula());
                                //根据otherName反射获取DataV中的字段值，按lineId和相别匹配
                                String otherName = epdPqd.getOtherName();
                                DataHarmPowerQ matchedDataV = data8.stream()
                                        .filter(d -> Objects.equals(d.getLineId(), item.getLineId())
                                                && Objects.equals(d.getPhaseType(), epdPqd.getPhase()))
                                        .findFirst()
                                        .orElse(null);
                                if (matchedDataV != null) {
                                    Object value = ReflectUtils.getValue(matchedDataV, toCamelCase(otherName + "_" + i));
                                    if (value instanceof Number) {
                                        t1.setData(((Number) value).doubleValue());
                                    }
                                    vo.setDataTime(matchedDataV.getTime());
                                }
                                t1.setName(i + "次" + item3.getName());
                                finalChildren.add(t1);
                            }
                        } else {
                            //根据otherName反射获取DataV中的字段值，按lineId和相别匹配
                            String otherName = epdPqd.getOtherName();
                            DataHarmPowerQ matchedDataV = data8.stream()
                                    .filter(d -> Objects.equals(d.getLineId(), item.getLineId())
                                            && Objects.equals(d.getPhaseType(), epdPqd.getPhase()))
                                    .findFirst()
                                    .orElse(null);
                            if (matchedDataV != null) {
                                Object value = ReflectUtils.getValue(matchedDataV, toCamelCase(otherName));
                                if (value instanceof Number) {
                                    targetDetail.setData(((Number) value).doubleValue());
                                }
                                vo.setDataTime(matchedDataV.getTime());
                            }
                        }
                    } else if (Objects.equals(map.get(epdPqd.getClassId()).getName(), "data_harmpower_s")) {
                        if (!Objects.isNull(epdPqd.getHarmStart()) && !Objects.isNull(epdPqd.getHarmEnd())) {
                            for (int i = epdPqd.getHarmStart(); i <= epdPqd.getHarmEnd(); i++) {
                                AppLineDetailVo.targetDetail t1 = new AppLineDetailVo.targetDetail();
                                t1.setTargetId(item3.getId());
                                t1.setName(item3.getName());
                                t1.setPhase(epdPqd.getPhase());
                                t1.setUnit(epdPqd.getUnit());
                                t1.setSort(item3.getSort());
                                t1.setPrimaryFormula(epdPqd.getPrimaryFormula());
                                //根据otherName反射获取DataV中的字段值，按lineId和相别匹配
                                String otherName = epdPqd.getOtherName();
                                DataHarmPowerS matchedDataV = data9.stream()
                                        .filter(d -> Objects.equals(d.getLineId(), item.getLineId())
                                                && Objects.equals(d.getPhaseType(), epdPqd.getPhase()))
                                        .findFirst()
                                        .orElse(null);
                                if (matchedDataV != null) {
                                    Object value = ReflectUtils.getValue(matchedDataV, toCamelCase(otherName + "_" + i));
                                    if (value instanceof Number) {
                                        t1.setData(((Number) value).doubleValue());
                                    }
                                    vo.setDataTime(matchedDataV.getTime());
                                }
                                t1.setName(i + "次" + item3.getName());
                                finalChildren.add(t1);
                            }
                        } else {
                            //根据otherName反射获取DataV中的字段值，按lineId和相别匹配
                            String otherName = epdPqd.getOtherName();
                            DataHarmPowerS matchedDataV = data9.stream()
                                    .filter(d -> Objects.equals(d.getLineId(), item.getLineId())
                                            && Objects.equals(d.getPhaseType(), epdPqd.getPhase()))
                                    .findFirst()
                                    .orElse(null);
                            if (matchedDataV != null) {
                                Object value = ReflectUtils.getValue(matchedDataV, toCamelCase(otherName));
                                if (value instanceof Number) {
                                    targetDetail.setData(((Number) value).doubleValue());
                                }
                                vo.setDataTime(matchedDataV.getTime());
                            }
                        }
                    } else if (Objects.equals(map.get(epdPqd.getClassId()).getName(), "data_harmrate_v")) {
                        if (!Objects.isNull(epdPqd.getHarmStart()) && !Objects.isNull(epdPqd.getHarmEnd())) {
                            for (int i = epdPqd.getHarmStart(); i <= epdPqd.getHarmEnd(); i++) {
                                AppLineDetailVo.targetDetail t1 = new AppLineDetailVo.targetDetail();
                                t1.setTargetId(item3.getId());
                                t1.setName(item3.getName());
                                t1.setPhase(epdPqd.getPhase());
                                t1.setUnit(epdPqd.getUnit());
                                t1.setSort(item3.getSort());
                                t1.setPrimaryFormula(epdPqd.getPrimaryFormula());
                                //根据otherName反射获取DataV中的字段值，按lineId和相别匹配
                                String otherName = epdPqd.getOtherName();
                                DataHarmRateV matchedDataV = data10.stream()
                                        .filter(d -> Objects.equals(d.getLineId(), item.getLineId())
                                                && Objects.equals(d.getPhaseType(), epdPqd.getPhase()))
                                        .findFirst()
                                        .orElse(null);
                                if (matchedDataV != null) {
                                    Object value = ReflectUtils.getValue(matchedDataV, toCamelCase(otherName + "_" + i));
                                    if (value instanceof Number) {
                                        t1.setData(((Number) value).doubleValue());
                                    }
                                    vo.setDataTime(matchedDataV.getTime());
                                }
                                t1.setName(i + "次" + item3.getName());
                                finalChildren.add(t1);
                            }
                        } else {
                            //根据otherName反射获取DataV中的字段值，按lineId和相别匹配
                            String otherName = epdPqd.getOtherName();
                            DataHarmRateV matchedDataV = data10.stream()
                                    .filter(d -> Objects.equals(d.getLineId(), item.getLineId())
                                            && Objects.equals(d.getPhaseType(), epdPqd.getPhase()))
                                    .findFirst()
                                    .orElse(null);
                            if (matchedDataV != null) {
                                Object value = ReflectUtils.getValue(matchedDataV, toCamelCase(otherName));
                                if (value instanceof Number) {
                                    targetDetail.setData(((Number) value).doubleValue());
                                }
                            }
                        }
                    } else if (Objects.equals(map.get(epdPqd.getClassId()).getName(), "data_harmrate_i")) {
                        if (!Objects.isNull(epdPqd.getHarmStart()) && !Objects.isNull(epdPqd.getHarmEnd())) {
                            for (int i = epdPqd.getHarmStart(); i <= epdPqd.getHarmEnd(); i++) {
                                AppLineDetailVo.targetDetail t1 = new AppLineDetailVo.targetDetail();
                                t1.setTargetId(item3.getId());
                                t1.setName(item3.getName());
                                t1.setPhase(epdPqd.getPhase());
                                t1.setUnit(epdPqd.getUnit());
                                t1.setSort(item3.getSort());
                                t1.setPrimaryFormula(epdPqd.getPrimaryFormula());
                                //根据otherName反射获取DataV中的字段值，按lineId和相别匹配
                                String otherName = epdPqd.getOtherName();
                                DataHarmRateI matchedDataV = data11.stream()
                                        .filter(d -> Objects.equals(d.getLineId(), item.getLineId())
                                                && Objects.equals(d.getPhaseType(), epdPqd.getPhase()))
                                        .findFirst()
                                        .orElse(null);
                                if (matchedDataV != null) {
                                    Object value = ReflectUtils.getValue(matchedDataV, toCamelCase(otherName + "_" + i));
                                    if (value instanceof Number) {
                                        t1.setData(((Number) value).doubleValue());
                                    }
                                    vo.setDataTime(matchedDataV.getTime());
                                }
                                t1.setName(i + "次" + item3.getName());
                                finalChildren.add(t1);
                            }
                        } else {
                            //根据otherName反射获取DataV中的字段值，按lineId和相别匹配
                            String otherName = epdPqd.getOtherName();
                            DataHarmRateI matchedDataV = data11.stream()
                                    .filter(d -> Objects.equals(d.getLineId(), item.getLineId())
                                            && Objects.equals(d.getPhaseType(), epdPqd.getPhase()))
                                    .findFirst()
                                    .orElse(null);
                            if (matchedDataV != null) {
                                Object value = ReflectUtils.getValue(matchedDataV, toCamelCase(otherName));
                                if (value instanceof Number) {
                                    targetDetail.setData(((Number) value).doubleValue());
                                }
                                vo.setDataTime(matchedDataV.getTime());
                            }
                        }
                    } else if (Objects.equals(map.get(epdPqd.getClassId()).getName(), "data_inharm_v")) {
                        if (!Objects.isNull(epdPqd.getHarmStart()) && !Objects.isNull(epdPqd.getHarmEnd())) {
                            for (int i = epdPqd.getHarmStart(); i <= epdPqd.getHarmEnd(); i++) {
                                AppLineDetailVo.targetDetail t1 = new AppLineDetailVo.targetDetail();
                                t1.setTargetId(item3.getId());
                                t1.setName(item3.getName());
                                t1.setPhase(epdPqd.getPhase());
                                t1.setUnit(epdPqd.getUnit());
                                t1.setSort(item3.getSort());
                                t1.setPrimaryFormula(epdPqd.getPrimaryFormula());
                                //根据otherName反射获取DataV中的字段值，按lineId和相别匹配
                                String otherName = epdPqd.getOtherName();
                                DataInHarmV matchedDataV = data12.stream()
                                        .filter(d -> Objects.equals(d.getLineId(), item.getLineId())
                                                && Objects.equals(d.getPhaseType(), epdPqd.getPhase()))
                                        .findFirst()
                                        .orElse(null);
                                if (matchedDataV != null) {
                                    Object value = ReflectUtils.getValue(matchedDataV, toCamelCase(otherName + "_" + i));
                                    if (value instanceof Number) {
                                        t1.setData(((Number) value).doubleValue());
                                    }
                                    vo.setDataTime(matchedDataV.getTime());
                                }
                                t1.setName((i-0.5) + "次" + item3.getName());
                                finalChildren.add(t1);
                            }
                        } else {
                            //根据otherName反射获取DataV中的字段值，按lineId和相别匹配
                            String otherName = epdPqd.getOtherName();
                            DataInHarmV matchedDataV = data12.stream()
                                    .filter(d -> Objects.equals(d.getLineId(), item.getLineId())
                                            && Objects.equals(d.getPhaseType(), epdPqd.getPhase()))
                                    .findFirst()
                                    .orElse(null);
                            if (matchedDataV != null) {
                                Object value = ReflectUtils.getValue(matchedDataV, toCamelCase(otherName));
                                if (value instanceof Number) {
                                    targetDetail.setData(((Number) value).doubleValue());
                                }
                                vo.setDataTime(matchedDataV.getTime());
                            }
                        }
                    } else if (Objects.equals(map.get(epdPqd.getClassId()).getName(), "data_plt")) {
                        //根据otherName反射获取DataV中的字段值，按lineId和相别匹配
                        String otherName = epdPqd.getOtherName();
                        DataPlt matchedDataV = data13.stream()
                                .filter(d -> Objects.equals(d.getLineId(), item.getLineId())
                                        && Objects.equals(d.getPhaseType(), epdPqd.getPhase()))
                                .findFirst()
                                .orElse(null);
                        if (matchedDataV != null) {
                            Object value = ReflectUtils.getValue(matchedDataV, toCamelCase(otherName));
                            if (value instanceof Number) {
                                targetDetail.setData(((Number) value).doubleValue());
                            }
                            vo.setDataTime(matchedDataV.getTime());
                        }
                    }
                    if (Objects.isNull(epdPqd.getHarmStart()) && Objects.isNull(epdPqd.getHarmEnd())) {
                        finalChildren.add(targetDetail);
                    }
                });
            });
            // 根据接线方式处理相别
            chanelPhase(lineMap, item, finalChildren, children2);
            // 处理一二次值
            String dataLevel = csDataSetMap.get(lineMap.get(item.getLineId()).getDataSetId()).getDataLevel();
            chanelData(children2,param.getDataLevel(),dataLevel,pt,ct);
            if (CollUtil.isNotEmpty(children2)) {
                children2.sort(Comparator.comparingInt(AppLineDetailVo.targetDetail::getSort));
                children2.forEach(item2->{
                    if (Objects.isNull(item2.getData())) {
                        item2.setData(NULL_DATA);
                    }
                    if (!Objects.equals(item2.getData(),NULL_DATA)) {
                        item2.setData(BigDecimal.valueOf(item2.getData()).setScale(2, RoundingMode.HALF_UP).doubleValue());
                    }
                });
            }
            vo.setChildren(children2);
            result.add(vo);
        });
        if (CollectionUtil.isNotEmpty(line1)) {
            List<AppLineDetailVo> zhiLiLineData = getZhiLiLineData(line1,data14, map, null, lineMap, csDataSetMap, null, param.getTargetType(), param.getDataLevel());
            result.addAll(zhiLiLineData);
        }
        if (CollUtil.isNotEmpty(result)) {
            result.sort(Comparator.comparing(AppLineDetailVo::getProjectName)
                    .thenComparing(AppLineDetailVo::getDeviceName)
                    .thenComparing(AppLineDetailVo::getPointId));
        }
        return result;
    }

    @Override
    public List<RecordVo> getTestData(DataParam param) {
        WlRecordParam.lineRecord record = new WlRecordParam.lineRecord();
        record.setLineId(param.getLineId());
        String beginDay = LocalDateTimeUtil.format(LocalDateTimeUtil.beginOfDay(LocalDateTimeUtil.parse(param.getStartTime(), DatePattern.NORM_DATE_PATTERN)),DatePattern.NORM_DATETIME_PATTERN);
        String endDay = LocalDateTimeUtil.format(LocalDateTimeUtil.endOfDay(LocalDateTimeUtil.parse(param.getEndTime(), DatePattern.NORM_DATE_PATTERN)),DatePattern.NORM_DATETIME_PATTERN);
        record.setItemStartTime(beginDay);
        record.setItemEndTime(endDay);
        record.setDataSource(param.getDataSource());
        List<RecordVo> list = wlRecordFeignClient.findDevBaseDataByLineId(record).getData();
        if (CollUtil.isNotEmpty(list)) {
            list.forEach(item->{
                if (Objects.nonNull(item.getEndTime())) {
                    Duration duration = Duration.between(item.getStartTime(), item.getEndTime());
                    long totalMinutes = duration.toMinutes();
                    long completeHours = totalMinutes / 60;
                    long remainingMinutes = totalMinutes % 60;
                    long millis = duration.getSeconds();
                    if (completeHours == 0 && remainingMinutes == 0 && millis <= 60) {
                        remainingMinutes = 1;
                    }
                    item.setLastTime(completeHours + "小时" + remainingMinutes + "分钟");
                }
            });
        }
        return list;
    }

    @Override
    public List<DataGroupEventVO> getEventByItem(ItemParam param) {
        List<DataGroupEventVO> result = new ArrayList<>();
        List<WlRecord> list = wlRecordFeignClient.getWlAssByWlId(param.getId()).getData();
        if (CollUtil.isNotEmpty(list)) {
            Map<String, List<WlRecord>> map = list.stream().filter(record -> record.getLineId() != null).collect(Collectors.groupingBy(WlRecord::getLineId));
            map.forEach((k,v)->{
                LocalDateTime globalMin = v.stream()
                        .flatMap(record -> Stream.of(record.getStartTime(), record.getEndTime()))
                        .min(Comparator.naturalOrder())
                        .orElse(null);
                LocalDateTime globalMax = v.stream()
                        .flatMap(record -> Stream.of(record.getStartTime(), record.getEndTime()))
                        .max(Comparator.naturalOrder())
                        .orElse(null);
                if (!Objects.isNull(globalMin) && !Objects.isNull(globalMax)) {
                    List<DataGroupEventVO> eventList = csEventPOService.queryEventList(param,globalMin,globalMax,k);
                    result.addAll(eventList);
                }
            });
        }
        if (CollUtil.isNotEmpty(result)) {
            List<String> lineList = result.stream().map(DataGroupEventVO::getLineId).distinct().collect(Collectors.toList());
            List<String> devList = result.stream().map(DataGroupEventVO::getDeviceId).distinct().collect(Collectors.toList());
            List<CsLinePO> linePoList = csLineFeignClient.queryLineById(lineList).getData();
            Map<String, CsLinePO> lineMap = linePoList.stream().collect(Collectors.toMap(CsLinePO::getLineId, item -> item));
            List<CsEquipmentDeliveryDTO> devDtoList = equipmentFeignClient.queryDeviceById(devList).getData();
            Map<String, CsEquipmentDeliveryDTO> devMap = devDtoList.stream().collect(Collectors.toMap(CsEquipmentDeliveryDTO::getId, item -> item));
            result.forEach(temp->{
                temp.setLineName(lineMap.get(temp.getLineId()).getName());
                temp.setLineVoltage(lineMap.get(temp.getLineId()).getVolGrade());
                temp.setDevName(devMap.get(temp.getDeviceId()).getName());
                temp.setNDid(devMap.get(temp.getDeviceId()).getNdid());
                EleEpdPqd ele = epdFeignClient.findByName(temp.getTag()).getData();
                if(ele!=null){
                    temp.setShowName(ele.getShowName());
                    //相别
                    List<EleEvtParm> data1 = eleEvtFeignClient.queryByPid(ele.getId()).getData();
                    List<EventDataSetDTO> eventDataSetDTOS = new ArrayList<>();
                    for (EleEvtParm eleEvtParm : data1) {
                        EventDataSetDTO eventDataSetDTO = new EventDataSetDTO();
                        BeanUtils.copyProperties(eleEvtParm,eventDataSetDTO);
                        EventDataSetDTO evtData = evtDataService.getEventDataSet(com.njcn.csdevice.constant.DataParam.evtData, temp.getId(), eleEvtParm.getName());
                        if (evtData == null) {
                            eventDataSetDTO.setValue("-");
                        }else {
                            eventDataSetDTO.setValue(Optional.ofNullable(evtData.getValue()).orElse("-"));
                        }
                        eventDataSetDTOS.add(eventDataSetDTO);
                    }
                    List<EventDataSetDTO> evtParamPhase = eventDataSetDTOS.stream().
                            filter(dataSetDTO -> Objects.equals(dataSetDTO.getName(), com.njcn.csdevice.constant.DataParam.EvtParamPhase)).
                            collect(Collectors.toList());
                    if(CollectionUtil.isEmpty(evtParamPhase)){
                        temp.setPhaseType(null);
                    }else {
                        temp.setPhaseType(evtParamPhase.get(0).getValue()+(Objects.isNull(evtParamPhase.get(0).getUnit())?"":evtParamPhase.get(0).getUnit()));
                    }

                    List<EventDataSetDTO> evtParamDepth = eventDataSetDTOS.stream().
                            filter(dataSetDTO -> Objects.equals(dataSetDTO.getName(), com.njcn.csdevice.constant.DataParam.EvtParamDepth)).
                            collect(Collectors.toList());
                    if(CollectionUtil.isEmpty(evtParamDepth)){
                        temp.setFeatureAmplitude(null);
                    }else {
                        temp.setFeatureAmplitude("-".equals(evtParamDepth.get(0).getValue())?null:Float.parseFloat(evtParamDepth.get(0).getValue()));
                    }
                    List<EventDataSetDTO> evtParmTm = eventDataSetDTOS.stream().
                            filter(dataSetDTO -> Objects.equals(dataSetDTO.getName(), com.njcn.csdevice.constant.DataParam.EVTPARAMTM)).
                            collect(Collectors.toList());
                    if(CollectionUtil.isEmpty(evtParamDepth)){
                        temp.setPersistTime(null);
                    }else {
                        temp.setPersistTime("-".equals(evtParmTm.get(0).getValue())?null:Double.parseDouble(evtParmTm.get(0).getValue()));
                    }
                }
            });
        }
        return result;
    }

    @Override
    public List<EachModuleVO> allModelData(DataParam param) {
        List<EachModuleVO> result = new ArrayList<>();
        //根据监测点查询装置信息
        CsEquipmentDeliveryPO po = equipmentFeignClient.getDevByLineId(param.getLineId()).getData();
        if (ObjectUtil.isNotNull(po.getModuleNumber())) {

            CommonQueryParam commonQueryParam = new CommonQueryParam();
            commonQueryParam.setColumnName("Apf_ModWorkingSts");
            commonQueryParam.setResultName("value");
            commonQueryParam.setTableName("apf_data");
            commonQueryParam.setStartTime(param.getStartTime()+" 00:00:00");
            commonQueryParam.setEndTime(param.getEndTime()+" 23:59:59");
            commonQueryParam.setLineId(param.getLineId());
            commonQueryParam.setDataType("Apf_ModType");
            commonQueryParam.setProcess(Integer.toString(po.getProcess()));
            for (int i = 1; i <= po.getModuleNumber(); i++) {
                EachModuleVO moduleVO = new EachModuleVO();
                moduleVO.setModuleName("模块"+i);

                List<EachModuleVO.HarmonicVo> list1 = new ArrayList<>();
                commonQueryParam.setClDid(Integer.toString(i));

                List<EachModuleVO.DataVo> list2 = new ArrayList<>();
                List<EachModuleVO.DataVo> list3 = new ArrayList<>();
                List<EachModuleVO.DataVo> list4 = new ArrayList<>();

                //获取模块状态数据
                List<StatisticalDataDTO> dto = commonService.getEachModule(commonQueryParam);
                if (CollectionUtil.isNotEmpty(dto)) {
                    dto.forEach(item->{
                        EachModuleVO.HarmonicVo vo = new EachModuleVO.HarmonicVo();
                        vo.setTime(LocalDateTime.ofInstant(item.getTime().minus(8, ChronoUnit.HOURS), ZoneId.systemDefault()));
                        vo.setStateDesc(channelState(item.getValue()));
                        vo.setDataType(0);
                        list1.add(vo);
                    });
                } else {
                    moduleVO.setModuleState("离线");
                }

                //获取模块电流数据
                List<StatisticalDataDTO> dto2 = commonService.getModuleData(commonQueryParam);
                if (CollectionUtil.isNotEmpty(dto2)) {
                    dto2.forEach(item->{

                        EachModuleVO.DataVo vo1 = new EachModuleVO.DataVo();
                        vo1.setTime(LocalDateTime.ofInstant(item.getTime().minus(8, ChronoUnit.HOURS), ZoneId.systemDefault()));
                        vo1.setPhasicType(item.getPhaseType());
                        vo1.setData(Objects.isNull(item.getValue()) ? NULL_DATA : Double.parseDouble(df.format(item.getValue())));

                        EachModuleVO.DataVo vo2 = new EachModuleVO.DataVo();
                        vo2.setTime(LocalDateTime.ofInstant(item.getTime().minus(8, ChronoUnit.HOURS), ZoneId.systemDefault()));
                        vo2.setPhasicType(item.getPhaseType());
                        vo2.setData(Objects.isNull(item.getAvgValue()) ? NULL_DATA : Double.parseDouble(df.format(item.getAvgValue())));

                        if (Objects.equals(item.getPhaseType(),"T")) {
                            EachModuleVO.DataVo vo3 = new EachModuleVO.DataVo();
                            vo3.setTime(LocalDateTime.ofInstant(item.getTime().minus(8, ChronoUnit.HOURS), ZoneId.systemDefault()));
                            vo3.setPhasicType(item.getPhaseType());
                            vo3.setData(Objects.isNull(item.getMinValue()) ? NULL_DATA : Double.parseDouble(df.format(item.getMinValue())));
                            list4.add(vo3);
                        }
                        list2.add(vo1);
                        list3.add(vo2);
                    });
                }

                //获取模块事件
                LambdaQueryWrapper<CsEventPO> lambdaQueryWrapper = new LambdaQueryWrapper<>();
                lambdaQueryWrapper.eq(CsEventPO::getLineId, param.getLineId())
                        .between(CsEventPO::getStartTime,param.getStartTime()+" 00:00:00",param.getEndTime()+" 23:59:59")
                        .eq(CsEventPO::getClDid,i)
                        .eq(CsEventPO::getProcess,Integer.toString(po.getProcess()))
                        .orderByAsc(CsEventPO::getStartTime);
                List<CsEventPO> eventList = csEventPOService.list(lambdaQueryWrapper);
                if (CollectionUtil.isNotEmpty(eventList)) {
                    eventList.forEach(item->{
                        EleEpdPqd epdPqd = epdFeignClient.findByName(item.getTag()).getData();
                        EachModuleVO.HarmonicVo vo = new EachModuleVO.HarmonicVo();
                        vo.setTime(item.getStartTime());
                        //查询事件状态 如果往前查寻没有数据、则往后查询事件
                        if (Objects.equals("Alm_Apf_ModConnect",item.getTag())) {
                            if (ObjectUtil.isNotEmpty(list1)) {
                                Optional<EachModuleVO.HarmonicVo> optional = list1.stream()
                                        // 筛选时间早于参考时间且目标字段等于指定值的记录
                                        .filter(vo1 -> vo1.getTime().isBefore(item.getStartTime()))
                                        .filter(vo2 -> vo2.getDataType() == 0)
                                        .findFirst();
                                optional.ifPresent(harmonicVo -> vo.setStateDesc(harmonicVo.getStateDesc()));
                            }
                        } else {
                            vo.setStateDesc(channelState2(item.getTag()));
                        }
                        vo.setEventCode(item.getTag());
                        vo.setDataType(1);
                        if (ObjectUtil.isNotNull(epdPqd)) {
                            vo.setEventName(epdPqd.getShowName());
                        } else {
                            vo.setEventName(item.getTag());
                        }
                        list1.add(vo);
                    });
                }
                if (CollectionUtil.isNotEmpty(list1)) {
                    List<EachModuleVO.HarmonicVo> dataList = list1.stream()
                            .sorted(Comparator.comparing(EachModuleVO.HarmonicVo::getTime))
                            .collect(Collectors.toList());
                    //处理APF模块连接事件状态
                    dataList.forEach(item->{
                        if (Objects.equals(item.getEventCode(),"Alm_Apf_ModConnect")) {
                            Optional<EachModuleVO.HarmonicVo> optional = dataList.stream()
                                    // 筛选时间早于参考时间且目标字段等于指定值的记录
                                    .filter(vo1 -> vo1.getTime().isAfter(item.getTime()) && vo1.getDataType() == 1)
                                    .filter(vo2 -> !Objects.equals("Alm_Apf_ModDisConnect",vo2.getEventCode()) && !Objects.equals("Alm_Apf_ModConnect",vo2.getEventCode()))
                                    .findFirst();
                            if (optional.isPresent()) {
                                item.setStateDesc(optional.get().getStateDesc());
                            } else {
                                item.setStateDesc("无状态");
                            }
                        }
                    });

                    EachModuleVO.HarmonicVo last = dataList.get(dataList.size() - 1);
                    moduleVO.setModuleState(last.getStateDesc());
                    //如果模块掉线超过30分钟，则续上数据
                    int timeCompare = compareWithCurrentTime(commonQueryParam.getEndTime());
                    LocalDateTime currentTime;
                    switch (timeCompare) {
                        case -1:
                        case 0:
                            currentTime = LocalDateTime.now();
                            break;
                        case 1:
                            currentTime = LocalDateTime.parse(commonQueryParam.getEndTime(), DatePattern.NORM_DATETIME_FORMATTER);
                            break;
                        default:
                            currentTime = LocalDateTime.now();
                            System.out.println("比较失败");
                    }

                    LocalDateTime givenTime = last.getTime();
                    Duration duration = Duration.between(givenTime, currentTime);
                    boolean isMoreThan30Minutes = duration.toMinutes() > 30;
                    if (isMoreThan30Minutes) {
                        EachModuleVO.HarmonicVo vo = new EachModuleVO.HarmonicVo();
                        vo.setTime(currentTime);
                        vo.setStateDesc(last.getStateDesc());
                        vo.setDataType(0);
                        dataList.add(vo);
                    }
                    moduleVO.setDataList(dataList);
                }
                moduleVO.setModOutList(list2);
                moduleVO.setLoadList(list3);
                moduleVO.setTemperatureList(list4);
                result.add(moduleVO);
            }
        }
        return result;
    }

    @Override
    public List<EachModuleVO> getModuleState(String nDid) {
        List<EachModuleVO> result = new ArrayList<>();
        try {
            CsEquipmentDeliveryPO po = equipmentFeignClient.findDevByNDid(nDid).getData();
            for (int i = 1; i <= po.getModuleNumber(); i++) {
                EachModuleVO moduleVO = new EachModuleVO();
                moduleVO.setModuleName("模块"+i);
                Object object = redisUtil.getObjectByKey(AppRedisKey.DEVICE_MID + nDid);
                if (!Objects.isNull(object)) {
                    mid = (Integer) object;
                }
                ReqAndResDto.Req dto = askApfModuleData(mid,i,i);
                String version = csTopicFeignClient.find(nDid).getData();
                publisher.send("/Pfm/DevCmd/" + version + "/" + nDid, new Gson().toJson(dto), 1, false);
                Thread.sleep(800);
                Object redisUtilObjectByKey = redisUtil.getObjectByKey("ApfRtData:" + mid);
                if (ObjectUtil.isNotNull(redisUtilObjectByKey)) {
                    Double value = Double.parseDouble(redisUtilObjectByKey.toString());
                    moduleVO.setModuleState(channelState(value));
                } else {
                    //再询问一次
                    publisher.send("/Pfm/DevCmd/" + version + "/" + nDid, new Gson().toJson(dto), 1, false);
                    Thread.sleep(800);
                    Object redisUtilObjectByKey2 = redisUtil.getObjectByKey("ApfRtData:" + mid);
                    if (ObjectUtil.isNotNull(redisUtilObjectByKey2)) {
                        Double value = Double.parseDouble(redisUtilObjectByKey2.toString());
                        moduleVO.setModuleState(channelState(value));
                    } else {
                        moduleVO.setModuleState("离线");
                    }
                }
                mid = mid + 1;
                if (mid > 10000) {
                    mid = 1;
                }
                redisUtil.saveByKey(AppRedisKey.DEVICE_MID + nDid,mid);
                result.add(moduleVO);
            }
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        return result;
    }

    //1、根据监测点集合 100为1个单位进行查询
    //2、根据表名来进行查询 指标可以用循环的方式拼接起来 influxQueryWrapper.select("rms","rms")
    //3、根据相别来分开查询，数据类型统一查询avg
    @Override
    public List<AppLineDetailVo> getLineDataByEngineer(String id) {
        List<AppLineDetailVo> result = new ArrayList<>();
        //根据工程获取监测点信息
        List<DevDetailDTO> data = csLedgerFeignClient.getDevInfoByEngineerIds(Collections.singletonList(id)).getData();
        if (CollectionUtil.isNotEmpty(data)) {
            List<DataV> data1 = new ArrayList<>();
            List<DataI> data2 = new ArrayList<>();
            List<DataFlicker> data3 = new ArrayList<>();
            List<DataFluc> data4 = new ArrayList<>();
            List<DataHarmPhasicV> data5 = new ArrayList<>();
            List<DataHarmPhasicI> data6 = new ArrayList<>();
            List<DataHarmPowerP> data7 = new ArrayList<>();
            List<DataHarmPowerQ> data8 = new ArrayList<>();
            List<DataHarmPowerS> data9 = new ArrayList<>();
            List<DataHarmRateV> data10 = new ArrayList<>();
            List<DataHarmRateI> data11 = new ArrayList<>();
            List<DataInHarmV> data12 = new ArrayList<>();
            List<DataPlt> data13 = new ArrayList<>();
            List<ApfData> data14 = new ArrayList<>();

            //获取监测点集合 针对监测点的类型区分查询数据-治理监测点、监测监测点
            List<String> lineList = data.stream().flatMap(v -> v.getLineList().stream()).collect(Collectors.toList());
            if (CollectionUtil.isEmpty(lineList)) {
                return result;
            }
            List<CsLinePO> linePo = csLineFeignClient.queryLineById(lineList).getData();
            Map<String,CsLinePO> lineMap = linePo.stream().collect(Collectors.toMap(CsLinePO::getLineId, item->item));
            //拆分治理监测点 、 监测监测点
            List<CsLinePO> line1 = linePo.stream().filter(item->item.getClDid()==0).collect(Collectors.toList());
            List<CsLinePO> line2 = linePo.stream().filter(item->item.getClDid()!=0).collect(Collectors.toList());
            List<String> lineList2 = line2.stream().map(CsLinePO::getLineId).collect(Collectors.toList());
            List<List<String>> partitions = Lists.partition(lineList2, 95);

            //表集合
            List<DictData> dataList = dicDataFeignClient.getDicDataByTypeCode("Data").getData();
            Map<String, DictData> map = dataList.stream().collect(Collectors.toMap(DictData::getId, v -> v));
            //获取需要查询的指标
            List<SysDicTreePO> list = dictTreeFeignClient.queryByCodeList("Key_Power_Quality").getData();
            List<SysDicTreePO> children = list.get(0).getChildren();
            children.sort(Comparator.comparing(SysDicTreePO::getSort));
            List<String> idList = children.stream().map(SysDicTreePO::getId).collect(Collectors.toList());
            List<EleEpdPqd> epdPqdList = csStatisticalSetFeignClient.queryStatisticalSelect(idList).getData();
            Map<String,List<EleEpdPqd>> epdPqdMap = epdPqdList.stream().collect(Collectors.groupingBy(EleEpdPqd::getClassId));
            Map<String,EleEpdPqd> epdPqdMap2 = epdPqdList.stream().collect(Collectors.toMap(EleEpdPqd::getId, v -> v));
            //获取监测点的数据集，转换一二次值
            List<String> dataSetIdList = linePo.stream().map(CsLinePO::getDataSetId).distinct().collect(Collectors.toList());
            List<CsDataSet> csDataSetList = dataSetFeignClient.getDataSetBySetIds(dataSetIdList).getData();
            Map<String,CsDataSet> csDataSetMap = csDataSetList.stream().collect(Collectors.toMap(CsDataSet::getId, v -> v));
            //获取指标名称和对应的指标集合
            List<CsStatisticalSetPO> csStatisticalSetPOList = csStatisticalSetFeignClient.queryStatisticalById(idList).getData();
            Map<String,List<CsStatisticalSetPO>> csStatisticalSetPOMap = csStatisticalSetPOList.stream().collect(Collectors.groupingBy(CsStatisticalSetPO::getStatisicalId));

            epdPqdMap.forEach((k,v) ->{
                if (Objects.equals(map.get(k).getName(), "data_v")) {
                    partitions.forEach(l -> {
                        InfluxQueryWrapper influxQueryWrapper = new InfluxQueryWrapper(DataV.class);
                        v.stream().map(EleEpdPqd::getOtherName).distinct().forEach(otherName -> influxQueryWrapper.select(otherName, otherName));
                        influxQueryWrapper.regular(DataV::getLineId, l)
                                .eq(DataV::getValueType,"AVG")
                                .groupBy(DataV::getPhaseType)
                                .groupBy(DataV::getLineId)
                                .timeDesc().limit(1);
                        List<DataV> dataV = dataVMapper.selectByQueryWrapper(influxQueryWrapper);
                        data1.addAll(dataV);
                    });
                } else if (Objects.equals(map.get(k).getName(), "data_i")){
                    partitions.forEach(l -> {
                        InfluxQueryWrapper influxQueryWrapper = new InfluxQueryWrapper(DataI.class);
                        v.stream().map(EleEpdPqd::getOtherName).distinct().forEach(otherName -> influxQueryWrapper.select(otherName, otherName));
                        influxQueryWrapper.regular(DataI::getLineId, l)
                                .eq(DataI::getValueType,"AVG")
                                .groupBy(DataI::getPhaseType)
                                .groupBy(DataI::getLineId)
                                .timeDesc().limit(1);
                        List<DataI> dataI = dataIMapper.selectByQueryWrapper(influxQueryWrapper);
                        data2.addAll(dataI);
                    });
                } else if (Objects.equals(map.get(k).getName(), "data_flicker")){
                    partitions.forEach(l -> {
                        InfluxQueryWrapper influxQueryWrapper = new InfluxQueryWrapper(DataFlicker.class);
                        v.stream().map(EleEpdPqd::getOtherName).distinct().forEach(otherName -> influxQueryWrapper.select(otherName, otherName));
                        influxQueryWrapper.regular(DataFlicker::getLineId, l)
                                .eq(DataFlicker::getValueType,"AVG")
                                .groupBy(DataFlicker::getPhaseType)
                                .groupBy(DataFlicker::getLineId)
                                .timeDesc().limit(1);
                        List<DataFlicker> dataFlicker = dataFlickerMapper.selectByQueryWrapper(influxQueryWrapper);
                        data3.addAll(dataFlicker);
                    });
                } else if (Objects.equals(map.get(k).getName(), "data_fluc")){
                    partitions.forEach(l -> {
                        InfluxQueryWrapper influxQueryWrapper = new InfluxQueryWrapper(DataFluc.class);
                        v.stream().map(EleEpdPqd::getOtherName).distinct().forEach(otherName -> influxQueryWrapper.select(otherName, otherName));
                        influxQueryWrapper.regular(DataFluc::getLineId, l)
                                .eq(DataFluc::getValueType,"AVG")
                                .groupBy(DataFluc::getPhaseType)
                                .groupBy(DataFluc::getLineId)
                                .timeDesc().limit(1);
                        List<DataFluc> dataFluc = dataFlucMapper.selectByQueryWrapper(influxQueryWrapper);
                        data4.addAll(dataFluc);
                    });
                } else if (Objects.equals(map.get(k).getName(), "data_harmphasic_v")){
                    partitions.forEach(l -> {
                        InfluxQueryWrapper influxQueryWrapper = new InfluxQueryWrapper(DataHarmPhasicV.class);
                        v.stream().map(EleEpdPqd::getOtherName).distinct().forEach(otherName -> influxQueryWrapper.select(otherName, otherName));
                        influxQueryWrapper.regular(DataHarmPhasicV::getLineId, l)
                                .eq(DataHarmPhasicV::getValueType,"AVG")
                                .groupBy(DataHarmPhasicV::getPhaseType)
                                .groupBy(DataHarmPhasicV::getLineId)
                                .timeDesc().limit(1);
                        List<DataHarmPhasicV> dataHarmPhasicV = dataHarmPhasicVMapper.selectByQueryWrapper(influxQueryWrapper);
                        data5.addAll(dataHarmPhasicV);
                    });
                } else if (Objects.equals(map.get(k).getName(), "data_harmphasic_i")){
                    partitions.forEach(l -> {
                        InfluxQueryWrapper influxQueryWrapper = new InfluxQueryWrapper(DataHarmPhasicI.class);
                        v.stream().map(EleEpdPqd::getOtherName).distinct().forEach(otherName -> influxQueryWrapper.select(otherName, otherName));
                        influxQueryWrapper.regular(DataHarmPhasicI::getLineId, l)
                                .eq(DataHarmPhasicI::getValueType,"AVG")
                                .groupBy(DataHarmPhasicI::getPhaseType)
                                .groupBy(DataHarmPhasicI::getLineId)
                                .timeDesc().limit(1);
                        List<DataHarmPhasicI> dataHarmPhasicI = dataHarmPhasicIMapper.selectByQueryWrapper(influxQueryWrapper);
                        data6.addAll(dataHarmPhasicI);
                    });
                } else if (Objects.equals(map.get(k).getName(), "data_harmpower_p")){
                    partitions.forEach(l -> {
                        InfluxQueryWrapper influxQueryWrapper = new InfluxQueryWrapper(DataHarmPowerP.class);
                        v.stream().map(EleEpdPqd::getOtherName).distinct().forEach(otherName -> influxQueryWrapper.select(otherName, otherName));
                        influxQueryWrapper.regular(DataHarmPowerP::getLineId, l)
                                .eq(DataHarmPowerP::getValueType,"AVG")
                                .groupBy(DataHarmPowerP::getPhaseType)
                                .groupBy(DataHarmPowerP::getLineId)
                                .timeDesc().limit(1);
                        List<DataHarmPowerP> dataHarmPowerP = dataHarmPowerPMapper.selectByQueryWrapper(influxQueryWrapper);
                        data7.addAll(dataHarmPowerP);
                    });
                } else if (Objects.equals(map.get(k).getName(), "data_harmpower_q")){
                    partitions.forEach(l -> {
                        InfluxQueryWrapper influxQueryWrapper = new InfluxQueryWrapper(DataHarmPowerQ.class);
                        v.stream().map(EleEpdPqd::getOtherName).distinct().forEach(otherName -> influxQueryWrapper.select(otherName, otherName));
                        influxQueryWrapper.regular(DataHarmPowerQ::getLineId, l)
                                .eq(DataHarmPowerQ::getValueType,"AVG")
                                .groupBy(DataHarmPowerQ::getPhaseType)
                                .groupBy(DataHarmPowerQ::getLineId)
                                .timeDesc().limit(1);
                        List<DataHarmPowerQ> dataHarmPowerQ = dataHarmPowerQMapper.selectByQueryWrapper(influxQueryWrapper);
                        data8.addAll(dataHarmPowerQ);
                    });
                } else if (Objects.equals(map.get(k).getName(), "data_harmpower_s")){
                    partitions.forEach(l -> {
                        InfluxQueryWrapper influxQueryWrapper = new InfluxQueryWrapper(DataHarmPowerS.class);
                        v.stream().map(EleEpdPqd::getOtherName).distinct().forEach(otherName -> influxQueryWrapper.select(otherName, otherName));
                        influxQueryWrapper.regular(DataHarmPowerS::getLineId, l)
                                .eq(DataHarmPowerS::getValueType,"AVG")
                                .groupBy(DataHarmPowerS::getPhaseType)
                                .groupBy(DataHarmPowerS::getLineId)
                                .timeDesc().limit(1);
                        List<DataHarmPowerS> dataHarmPowerS = dataHarmPowerSMapper.selectByQueryWrapper(influxQueryWrapper);
                        data9.addAll(dataHarmPowerS);
                    });
                } else if (Objects.equals(map.get(k).getName(), "data_harmrate_v")){
                    partitions.forEach(l -> {
                        InfluxQueryWrapper influxQueryWrapper = new InfluxQueryWrapper(DataHarmRateV.class);
                        v.stream().map(EleEpdPqd::getOtherName).distinct().forEach(otherName -> influxQueryWrapper.select(otherName, otherName));
                        influxQueryWrapper.regular(DataHarmRateV::getLineId, l)
                                .eq(DataHarmRateV::getValueType,"AVG")
                                .groupBy(DataHarmRateV::getPhaseType)
                                .groupBy(DataHarmRateV::getLineId)
                                .timeDesc().limit(1);
                        List<DataHarmRateV> dataHarmRateV = dataHarmRateVMapper.selectByQueryWrapper(influxQueryWrapper);
                        data10.addAll(dataHarmRateV);
                    });
                } else if (Objects.equals(map.get(k).getName(), "data_harmrate_i")){
                    partitions.forEach(l -> {
                        InfluxQueryWrapper influxQueryWrapper = new InfluxQueryWrapper(DataHarmRateI.class);
                        v.stream().map(EleEpdPqd::getOtherName).distinct().forEach(otherName -> influxQueryWrapper.select(otherName, otherName));
                        influxQueryWrapper.regular(DataHarmRateI::getLineId, l)
                                .eq(DataHarmRateI::getValueType,"AVG")
                                .groupBy(DataHarmRateI::getPhaseType)
                                .groupBy(DataHarmRateI::getLineId)
                                .timeDesc().limit(1);
                        List<DataHarmRateI> DataHarmRateI = dataHarmRateIMapper.selectByQueryWrapper(influxQueryWrapper);
                        data11.addAll(DataHarmRateI);
                    });
                } else if (Objects.equals(map.get(k).getName(), "data_inharm_v")){
                    partitions.forEach(l -> {
                        InfluxQueryWrapper influxQueryWrapper = new InfluxQueryWrapper(DataInHarmV.class);
                        v.stream().map(EleEpdPqd::getOtherName).distinct().forEach(otherName -> influxQueryWrapper.select(otherName, otherName));
                        influxQueryWrapper.regular(DataInHarmV::getLineId, l)
                                .eq(DataInHarmV::getValueType,"AVG")
                                .groupBy(DataInHarmV::getPhaseType)
                                .groupBy(DataInHarmV::getLineId)
                                .timeDesc().limit(1);
                        List<DataInHarmV> dataInHarmV = dataInHarmVMapper.selectByQueryWrapper(influxQueryWrapper);
                        data12.addAll(dataInHarmV);
                    });
                } else if (Objects.equals(map.get(k).getName(), "data_plt")){
                    partitions.forEach(l -> {
                        InfluxQueryWrapper influxQueryWrapper = new InfluxQueryWrapper(DataPlt.class);
                        v.stream().map(EleEpdPqd::getOtherName).distinct().forEach(otherName -> influxQueryWrapper.select(otherName, otherName));
                        influxQueryWrapper.regular(DataPlt::getLineId, l)
                                .eq(DataPlt::getValueType,"AVG")
                                .groupBy(DataPlt::getPhaseType)
                                .groupBy(DataPlt::getLineId)
                                .timeDesc().limit(1);
                        List<DataPlt> dataPlt = dataPltMapper.selectByQueryWrapper(influxQueryWrapper);
                        data13.addAll(dataPlt);
                    });
                }
            });
            //监测点第一层
            line2.forEach(item->{
                AppLineDetailVo vo = new AppLineDetailVo();
                for (DevDetailDTO item2 : data) {
                    if (item2.getLineList() != null && item2.getLineList().contains(item.getLineId())) {
                        vo.setProjectName(item2.getProjectName());
                        vo.setDeviceName(item2.getEquipmentName());
                        vo.setRunStatus(item.getRunStatus());
                        break;
                    }
                }
                vo.setLineType(1);
                vo.setPointId(item.getLineId());
                vo.setPointName(lineMap.get(item.getLineId()).getName());
                List<AppLineDetailVo.targetDetail> children2 = new ArrayList<>();
                //指标第二层
                List<AppLineDetailVo.targetDetail> finalChildren = children2;
                children.forEach(item3->{
                    List<CsStatisticalSetPO> l1 = csStatisticalSetPOMap.get(item3.getId());
                    if (CollUtil.isEmpty(l1)) {
                        return;
                    }
                    List<EleEpdPqd> list1 = new ArrayList<>();
                    l1.forEach(item1 -> {
                        list1.add(epdPqdMap2.get(item1.getTargetId()));
                    });
                    list1.sort(Comparator.comparingInt(EleEpdPqd::getSort));
                    list1.forEach(epdPqd -> {
                        AppLineDetailVo.targetDetail targetDetail = new AppLineDetailVo.targetDetail();
                        targetDetail.setTargetId(item3.getId());
                        targetDetail.setName(item3.getName());
                        targetDetail.setPhase(epdPqd.getPhase());
                        targetDetail.setUnit(epdPqd.getUnit());
                        targetDetail.setSort(item3.getSort());
                        targetDetail.setPrimaryFormula(epdPqd.getPrimaryFormula());
                        if (Objects.equals(map.get(epdPqd.getClassId()).getName(), "data_v")) {
                            //根据otherName反射获取DataV中的字段值，按lineId和相别匹配
                            String otherName = epdPqd.getOtherName();
                            DataV matchedDataV = data1.stream()
                                    .filter(d -> Objects.equals(d.getLineId(), item.getLineId())
                                            && Objects.equals(d.getPhaseType(), epdPqd.getPhase()))
                                    .findFirst()
                                    .orElse(null);
                            if (matchedDataV != null) {
                                Object value = ReflectUtils.getValue(matchedDataV, toCamelCase(otherName));
                                if (value instanceof Number) {
                                    targetDetail.setData(((Number) value).doubleValue());
                                }
                                vo.setDataTime(matchedDataV.getTime());
                            }
                        } else if (Objects.equals(map.get(epdPqd.getClassId()).getName(), "data_i")) {
                            //根据otherName反射获取DataV中的字段值，按lineId和相别匹配
                            String otherName = epdPqd.getOtherName();
                            DataI matchedDataV = data2.stream()
                                    .filter(d -> Objects.equals(d.getLineId(), item.getLineId())
                                            && Objects.equals(d.getPhaseType(), epdPqd.getPhase()))
                                    .findFirst()
                                    .orElse(null);
                            if (matchedDataV != null) {
                                Object value = ReflectUtils.getValue(matchedDataV, toCamelCase(otherName));
                                if (value instanceof Number) {
                                    targetDetail.setData(((Number) value).doubleValue());
                                }
                                vo.setDataTime(matchedDataV.getTime());
                            }
                        } else if (Objects.equals(map.get(epdPqd.getClassId()).getName(), "data_flicker")) {
                            //根据otherName反射获取DataV中的字段值，按lineId和相别匹配
                            String otherName = epdPqd.getOtherName();
                            DataFlicker matchedDataV = data3.stream()
                                    .filter(d -> Objects.equals(d.getLineId(), item.getLineId())
                                            && Objects.equals(d.getPhaseType(), epdPqd.getPhase()))
                                    .findFirst()
                                    .orElse(null);
                            if (matchedDataV != null) {
                                Object value = ReflectUtils.getValue(matchedDataV, toCamelCase(otherName));
                                if (value instanceof Number) {
                                    targetDetail.setData(((Number) value).doubleValue());
                                }
                                vo.setDataTime(matchedDataV.getTime());
                            }
                        } else if (Objects.equals(map.get(epdPqd.getClassId()).getName(), "data_fluc")) {
                            //根据otherName反射获取DataV中的字段值，按lineId和相别匹配
                            String otherName = epdPqd.getOtherName();
                            DataFluc matchedDataV = data4.stream()
                                    .filter(d -> Objects.equals(d.getLineId(), item.getLineId())
                                            && Objects.equals(d.getPhaseType(), epdPqd.getPhase()))
                                    .findFirst()
                                    .orElse(null);
                            if (matchedDataV != null) {
                                Object value = ReflectUtils.getValue(matchedDataV, toCamelCase(otherName));
                                if (value instanceof Number) {
                                    targetDetail.setData(((Number) value).doubleValue());
                                }
                                vo.setDataTime(matchedDataV.getTime());
                            }
                        } else if (Objects.equals(map.get(epdPqd.getClassId()).getName(), "data_harmphasic_v")) {
                            //根据otherName反射获取DataV中的字段值，按lineId和相别匹配
                            String otherName = epdPqd.getOtherName();
                            DataHarmPhasicV matchedDataV = data5.stream()
                                    .filter(d -> Objects.equals(d.getLineId(), item.getLineId())
                                            && Objects.equals(d.getPhaseType(), epdPqd.getPhase()))
                                    .findFirst()
                                    .orElse(null);
                            if (matchedDataV != null) {
                                Object value = ReflectUtils.getValue(matchedDataV, toCamelCase(otherName));
                                if (value instanceof Number) {
                                    targetDetail.setData(((Number) value).doubleValue());
                                }
                                vo.setDataTime(matchedDataV.getTime());
                            }
                        } else if (Objects.equals(map.get(epdPqd.getClassId()).getName(), "data_harmphasic_i")) {
                            //根据otherName反射获取DataV中的字段值，按lineId和相别匹配
                            String otherName = epdPqd.getOtherName();
                            DataHarmPhasicI matchedDataV = data6.stream()
                                    .filter(d -> Objects.equals(d.getLineId(), item.getLineId())
                                            && Objects.equals(d.getPhaseType(), epdPqd.getPhase()))
                                    .findFirst()
                                    .orElse(null);
                            if (matchedDataV != null) {
                                Object value = ReflectUtils.getValue(matchedDataV, toCamelCase(otherName));
                                if (value instanceof Number) {
                                    targetDetail.setData(((Number) value).doubleValue());
                                }
                                vo.setDataTime(matchedDataV.getTime());
                            }
                        } else if (Objects.equals(map.get(epdPqd.getClassId()).getName(), "data_harmpower_p")) {
                            //根据otherName反射获取DataV中的字段值，按lineId和相别匹配
                            String otherName = epdPqd.getOtherName();
                            DataHarmPowerP matchedDataV = data7.stream()
                                    .filter(d -> Objects.equals(d.getLineId(), item.getLineId())
                                            && Objects.equals(d.getPhaseType(), epdPqd.getPhase()))
                                    .findFirst()
                                    .orElse(null);
                            if (matchedDataV != null) {
                                Object value = ReflectUtils.getValue(matchedDataV, toCamelCase(otherName));
                                if (value instanceof Number) {
                                    targetDetail.setData(((Number) value).doubleValue());
                                }
                                vo.setDataTime(matchedDataV.getTime());
                            }
                        } else if (Objects.equals(map.get(epdPqd.getClassId()).getName(), "data_harmpower_q")) {
                            //根据otherName反射获取DataV中的字段值，按lineId和相别匹配
                            String otherName = epdPqd.getOtherName();
                            DataHarmPowerQ matchedDataV = data8.stream()
                                    .filter(d -> Objects.equals(d.getLineId(), item.getLineId())
                                            && Objects.equals(d.getPhaseType(), epdPqd.getPhase()))
                                    .findFirst()
                                    .orElse(null);
                            if (matchedDataV != null) {
                                Object value = ReflectUtils.getValue(matchedDataV, toCamelCase(otherName));
                                if (value instanceof Number) {
                                    targetDetail.setData(((Number) value).doubleValue());
                                }
                                vo.setDataTime(matchedDataV.getTime());
                            }
                        } else if (Objects.equals(map.get(epdPqd.getClassId()).getName(), "data_harmpower_s")) {
                            //根据otherName反射获取DataV中的字段值，按lineId和相别匹配
                            String otherName = epdPqd.getOtherName();
                            DataHarmPowerS matchedDataV = data9.stream()
                                    .filter(d -> Objects.equals(d.getLineId(), item.getLineId())
                                            && Objects.equals(d.getPhaseType(), epdPqd.getPhase()))
                                    .findFirst()
                                    .orElse(null);
                            if (matchedDataV != null) {
                                Object value = ReflectUtils.getValue(matchedDataV, toCamelCase(otherName));
                                if (value instanceof Number) {
                                    targetDetail.setData(((Number) value).doubleValue());
                                }
                                vo.setDataTime(matchedDataV.getTime());
                            }
                        } else if (Objects.equals(map.get(epdPqd.getClassId()).getName(), "data_harmrate_v")) {
                            //根据otherName反射获取DataV中的字段值，按lineId和相别匹配
                            String otherName = epdPqd.getOtherName();
                            DataHarmRateV matchedDataV = data10.stream()
                                    .filter(d -> Objects.equals(d.getLineId(), item.getLineId())
                                            && Objects.equals(d.getPhaseType(), epdPqd.getPhase()))
                                    .findFirst()
                                    .orElse(null);
                            if (matchedDataV != null) {
                                Object value = ReflectUtils.getValue(matchedDataV, toCamelCase(otherName));
                                if (value instanceof Number) {
                                    targetDetail.setData(((Number) value).doubleValue());
                                }
                                vo.setDataTime(matchedDataV.getTime());
                            }
                        } else if (Objects.equals(map.get(epdPqd.getClassId()).getName(), "data_harmrate_i")) {
                            //根据otherName反射获取DataV中的字段值，按lineId和相别匹配
                            String otherName = epdPqd.getOtherName();
                            DataHarmRateI matchedDataV = data11.stream()
                                    .filter(d -> Objects.equals(d.getLineId(), item.getLineId())
                                            && Objects.equals(d.getPhaseType(), epdPqd.getPhase()))
                                    .findFirst()
                                    .orElse(null);
                            if (matchedDataV != null) {
                                Object value = ReflectUtils.getValue(matchedDataV, toCamelCase(otherName));
                                if (value instanceof Number) {
                                    targetDetail.setData(((Number) value).doubleValue());
                                }
                                vo.setDataTime(matchedDataV.getTime());
                            }
                        } else if (Objects.equals(map.get(epdPqd.getClassId()).getName(), "data_inharm_v")) {
                            //根据otherName反射获取DataV中的字段值，按lineId和相别匹配
                            String otherName = epdPqd.getOtherName();
                            DataInHarmV matchedDataV = data12.stream()
                                    .filter(d -> Objects.equals(d.getLineId(), item.getLineId())
                                            && Objects.equals(d.getPhaseType(), epdPqd.getPhase()))
                                    .findFirst()
                                    .orElse(null);
                            if (matchedDataV != null) {
                                Object value = ReflectUtils.getValue(matchedDataV, toCamelCase(otherName));
                                if (value instanceof Number) {
                                    targetDetail.setData(((Number) value).doubleValue());
                                }
                                vo.setDataTime(matchedDataV.getTime());
                            }
                        } else if (Objects.equals(map.get(epdPqd.getClassId()).getName(), "data_plt")) {
                            //根据otherName反射获取DataV中的字段值，按lineId和相别匹配
                            String otherName = epdPqd.getOtherName();
                            DataPlt matchedDataV = data13.stream()
                                    .filter(d -> Objects.equals(d.getLineId(), item.getLineId())
                                            && Objects.equals(d.getPhaseType(), epdPqd.getPhase()))
                                    .findFirst()
                                    .orElse(null);
                            if (matchedDataV != null) {
                                Object value = ReflectUtils.getValue(matchedDataV, toCamelCase(otherName));
                                if (value instanceof Number) {
                                    targetDetail.setData(((Number) value).doubleValue());
                                }
                                vo.setDataTime(matchedDataV.getTime());
                            }
                        }
                        //一二次值处理
                        if (!Objects.isNull(targetDetail.getData())) {
                            String dataLevel = csDataSetMap.get(lineMap.get(item.getLineId()).getDataSetId()).getDataLevel();
                            if (Objects.equals(dataLevel, "Primary")) {
                                if (targetDetail.getPrimaryFormula() != null && ("*PT".equals(targetDetail.getPrimaryFormula()) || "*PT*CT".equals(targetDetail.getPrimaryFormula()))) {
                                    targetDetail.setUnit("k" + targetDetail.getUnit());
                                    targetDetail.setData(Math.round(targetDetail.getData() * 100.0) / 100.0);
                                }
                            } else if (Objects.equals(dataLevel, "Secondary")) {
                                Double ct = Objects.isNull(item.getCtRatio())?1.0:item.getCtRatio() / (Objects.isNull(item.getCt2Ratio())?1.0:item.getCt2Ratio());
                                Double pt = Objects.isNull(item.getPtRatio())?1.0:item.getPtRatio() / (Objects.isNull(item.getPt2Ratio())?1.0:item.getPt2Ratio());
                                String formula = targetDetail.getPrimaryFormula();
                                if (formula == null) {
                                    targetDetail.setData(Math.round(targetDetail.getData() * 100.0) / 100.0);
                                }
                                if ("*PT".equals(formula) || "*PT*CT".equals(formula)) {
                                    targetDetail.setUnit("k" + targetDetail.getUnit());
                                    double finalData = DataChangeUtil.secondaryToPrimary(formula, targetDetail.getData(), pt, ct);
                                    targetDetail.setData(Math.round((finalData/1000) * 100.0) / 100.0);
                                }
                                if ("*CT".equals(formula)) {
                                    double finalData = DataChangeUtil.secondaryToPrimary(formula, targetDetail.getData(), pt, ct);
                                    targetDetail.setData(Math.round(finalData * 100.0) / 100.0);
                                }
                            }
                        }
                        finalChildren.add(targetDetail);
                    });
                });
                // 根据接线方式处理相别
                chanelPhase(lineMap, item, finalChildren, children2);
                if (CollUtil.isNotEmpty(children2)) {
                    children2.sort(Comparator.comparingInt(AppLineDetailVo.targetDetail::getSort));
                }
                vo.setChildren(children2);
                result.add(vo);
            });
            if (CollectionUtil.isNotEmpty(line1)) {
                List<AppLineDetailVo> zhiLiLineData = getZhiLiLineData(line1,data14, map, data, lineMap, csDataSetMap, "Key_Power_Quality_Pq_Com", null, "Primary");
                result.addAll(zhiLiLineData);
            }
        }
        if (CollUtil.isNotEmpty(result)) {
            result.sort(Comparator.comparing(AppLineDetailVo::getProjectName)
                    .thenComparing(AppLineDetailVo::getDeviceName)
                    .thenComparing(AppLineDetailVo::getPointId));
        }
        return result;
    }

    public void chanelPhase(Map<String,CsLinePO> lineMap,CsLinePO item,List<AppLineDetailVo.targetDetail> finalChildren, List<AppLineDetailVo.targetDetail> children2) {
        // 根据接线方式处理相别
        Integer conType = lineMap.get(item.getLineId()).getConType();
        if (conType != null && conType == 0) {
            // 星型接线: 保留A/B/C/T，去除AB/BC/CA 除了 线电压总有效值 外
            finalChildren.removeIf(d ->
                    ("AB".equals(d.getPhase()) || "BC".equals(d.getPhase()) || "CA".equals(d.getPhase()))
                            && !Objects.equals(d.getName(), "线电压总有效值")
            );
        } else if (conType != null) {
            // 角型/V型接线: A/B/C数据用AB/BC/CA替换，然后去除AB/BC/CA
            Map<String, List<AppLineDetailVo.targetDetail>> groupByTargetId = finalChildren.stream()
                    .collect(Collectors.groupingBy(AppLineDetailVo.targetDetail::getTargetId));
            List<AppLineDetailVo.targetDetail> newChildren2 = new ArrayList<>();
            for (List<AppLineDetailVo.targetDetail> group : groupByTargetId.values()) {
                // 提取AB/BC/CA的数据
                Map<String, Double> abDataMap = new HashMap<>();
                for (AppLineDetailVo.targetDetail d : group) {
                    if ("AB".equals(d.getPhase()) || "BC".equals(d.getPhase()) || "CA".equals(d.getPhase())) {
                        abDataMap.put(d.getPhase(), d.getData());
                    }
                }
                // 用AB/BC/CA替换A/B/C数据，保留T相
                for (AppLineDetailVo.targetDetail d : group) {
                    if ("A".equals(d.getPhase())) {
                        if (abDataMap.containsKey("AB")) {
                            d.setData(abDataMap.get("AB"));
                        }
                        newChildren2.add(d);
                    } else if ("B".equals(d.getPhase())) {
                        if (abDataMap.containsKey("BC")) {
                            d.setData(abDataMap.get("BC"));
                        }
                        newChildren2.add(d);
                    } else if ("C".equals(d.getPhase())) {
                        if (abDataMap.containsKey("CA")) {
                            d.setData(abDataMap.get("CA"));
                        }
                        newChildren2.add(d);
                    } else if ("T".equals(d.getPhase())) {
                        newChildren2.add(d);
                    }
                }
            }
            children2 = newChildren2;
        }
    }

    public void chanelData(List<AppLineDetailVo.targetDetail> finalChildren, String dataLevel1, String dataLevel2, Double pt, Double ct) {
        finalChildren.forEach(item->{
            if(Objects.equals(item.getOtherName(),"电压负序分量") || Objects.equals(item.getOtherName(),"电压零序分量")) {
                return;
            }
            Double re;
            String unit = item.getUnit();

            if (Objects.equals("Primary",dataLevel1)) {
                if (Objects.equals("Primary",dataLevel2)) {
                    if (HarmonicConstant.POWER_LIST.contains(item.getName())) {
                        re = Objects.isNull(item.getData()) ? NULL_DATA : Double.parseDouble(df.format(item.getData() / 1000));
                        item.setData(re);
                        unit = "k" + item.getUnit();
                    } else {
                        item.setData(Objects.isNull(item.getData()) ? NULL_DATA : Double.parseDouble(df.format(item.getData())));
                        unit = item.getUnit();
                    }
                } else {
                    if(Objects.nonNull(item.getPrimaryFormula())){
                        switch (item.getPrimaryFormula()) {
                            case "*PT":
                                re = Objects.isNull(item.getData()) ? NULL_DATA : item.getData() * pt / 1000;
                                unit = "k" + item.getUnit();
                                break;
                            case "*CT":
                                re = Objects.isNull(item.getData()) ? NULL_DATA : item.getData() * ct;
                                unit = item.getUnit();
                                break;
                            case "*PT*CT":
                                re = Objects.isNull(item.getData()) ? NULL_DATA : item.getData() * pt * ct / 1000;
                                unit = "k" + item.getUnit();
                                break;
                            default:
                                re = Objects.isNull(item.getData()) ? NULL_DATA : item.getData();
                                unit = item.getUnit();
                                break;
                        }
                        item.setData(Objects.equals(re,NULL_DATA) ? NULL_DATA : Double.parseDouble(df.format(re)));
                    }else {
                        item.setData(Objects.isNull(item.getData()) ? NULL_DATA : Double.parseDouble(df.format(item.getData())));
                    }
                }
            } else {
                if (Objects.equals("Primary",dataLevel2)) {
                    if(Objects.nonNull(item.getPrimaryFormula())) {
                        switch (item.getPrimaryFormula()) {
                            case "*PT":
                                re = Objects.isNull(item.getData()) ? NULL_DATA : item.getData() / pt;
                                break;
                            case "*CT":
                                re = Objects.isNull(item.getData()) ? NULL_DATA : item.getData() / ct;
                                break;
                            case "*PT*CT":
                                re = Objects.isNull(item.getData()) ? NULL_DATA : item.getData() / pt / ct * 1000;
                                break;
                            default:
                                re = Objects.isNull(item.getData()) ? NULL_DATA : item.getData();
                                break;
                        }
                        item.setData(Objects.equals(re,NULL_DATA) ? NULL_DATA : Double.parseDouble(df.format(re)));
                    }else {
                        if (Objects.nonNull(item.getData())) {
                            re = item.getData();
                            item.setData(Double.valueOf(df.format(re)));
                        }
                    }
                } else {
                    item.setData(Objects.isNull(item.getData()) ? NULL_DATA : Double.parseDouble(df.format(item.getData())));
                }
            }
            item.setUnit(unit);
            item.setOtherNameUnit(unit);
        });
    }

    //处理治理监测点
    public List<AppLineDetailVo> getZhiLiLineData(List<CsLinePO> poList
            ,List<ApfData> data14
            , Map<String, DictData> map
            ,  List<DevDetailDTO> data
            , Map<String,CsLinePO> lineMap
            , Map<String,CsDataSet> csDataSetMap
            , String code
            , String codeId
            , String dataLevel1) {
        List<AppLineDetailVo> result = new ArrayList<>();
        if (CollUtil.isEmpty(poList)) {
            return result;
        }
        List<String> lineList = poList.stream().map(CsLinePO::getLineId).collect(Collectors.toList());
        List<List<String>> partitions = Lists.partition(lineList, 95);
        //获取需要查询的指标
        List<SysDicTreePO> list;
        if (Objects.isNull(codeId)) {
            list = dictTreeFeignClient.queryByCodeList(code).getData();
        } else {
            SysDicTreePO po = dictTreeFeignClient.queryById(codeId).getData();
            list = dictTreeFeignClient.queryByCodeList(po.getCode()).getData();
        }
        List<SysDicTreePO> children = list.get(0).getChildren();
        children.sort(Comparator.comparing(SysDicTreePO::getSort));
        List<String> idList = children.stream().map(SysDicTreePO::getId).collect(Collectors.toList());
        List<EleEpdPqd> epdPqdList = csStatisticalSetFeignClient.queryStatisticalSelect(idList).getData();
        Map<String,List<EleEpdPqd>> epdPqdMap = epdPqdList.stream().collect(Collectors.groupingBy(EleEpdPqd::getClassId));
        Map<String,EleEpdPqd> epdPqdMap2 = epdPqdList.stream().collect(Collectors.toMap(EleEpdPqd::getId, v -> v));
        //获取指标名称和对应的指标集合
        List<CsStatisticalSetPO> csStatisticalSetPOList = csStatisticalSetFeignClient.queryStatisticalById(idList).getData();
        Map<String,List<CsStatisticalSetPO>> csStatisticalSetPOMap = csStatisticalSetPOList.stream().collect(Collectors.groupingBy(CsStatisticalSetPO::getStatisicalId));

        epdPqdMap.forEach((k,v) ->{
            if (Objects.equals(map.get(k).getName(), "apf_data")) {
                partitions.forEach(l -> {
                    InfluxQueryWrapper influxQueryWrapper = new InfluxQueryWrapper(ApfData.class);
                    v.forEach(item->{
                        if (!Objects.isNull(item.getHarmStart()) && !Objects.isNull(item.getHarmEnd())) {
                            for (int i = item.getHarmStart(); i <= item.getHarmEnd(); i++) {
                                influxQueryWrapper.select(item.getOtherName() + "_" + i,item.getOtherName() + "_" + i);
                            }
                        } else{
                            influxQueryWrapper.select(item.getOtherName(),item.getOtherName());
                        }
                    });
                    influxQueryWrapper.regular(ApfData::getLineId, l)
                            .eq(ApfData::getValueType,"AVG")
                            .eq(ApfData::getClDid,"0")
                            .groupBy(ApfData::getPhaseType)
                            .groupBy(ApfData::getLineId)
                            .timeDesc().limit(1);
                    List<ApfData> apfData = apfDataMapper.selectByQueryWrapper(influxQueryWrapper);
                    data14.addAll(apfData);
                });
            }
        });

        //监测点第一层
        poList.forEach(item->{
            AppLineDetailVo vo = new AppLineDetailVo();
            if (!CollUtil.isEmpty(data)) {
                for (DevDetailDTO item2 : data) {
                    if (item2.getLineList() != null && item2.getLineList().contains(item.getLineId())) {
                        vo.setProjectName(item2.getProjectName());
                        vo.setDeviceName(item2.getEquipmentName());
                        break;
                    }
                }
            }
            vo.setLineType(0);
            vo.setPointId(item.getLineId());
            vo.setPointName(lineMap.get(item.getLineId()).getName());
            Double ct = lineMap.get(item.getLineId()).getCtRatio() / (Objects.isNull(lineMap.get(item.getLineId()).getCt2Ratio())?1.0:lineMap.get(item.getLineId()).getCtRatio());
            Double pt = lineMap.get(item.getLineId()).getPtRatio() / (Objects.isNull(lineMap.get(item.getLineId()).getPt2Ratio())?1.0:lineMap.get(item.getLineId()).getPtRatio());
            List<AppLineDetailVo.targetDetail> children2 = new ArrayList<>();
            //指标第二层
            List<AppLineDetailVo.targetDetail> finalChildren = children2;
            children.forEach(item3->{
                List<CsStatisticalSetPO> l1 = csStatisticalSetPOMap.get(item3.getId());
                if (CollUtil.isEmpty(l1)) {
                    return;
                }
                List<EleEpdPqd> list1 = new ArrayList<>();
                l1.forEach(item1 -> {
                    list1.add(epdPqdMap2.get(item1.getTargetId()));
                });
                list1.forEach(epdPqd -> {
                    AppLineDetailVo.targetDetail targetDetail = new AppLineDetailVo.targetDetail();
                    targetDetail.setTargetId(item3.getId());
                    targetDetail.setName(item3.getName());
                    targetDetail.setPhase(epdPqd.getPhase());
                    targetDetail.setUnit(epdPqd.getUnit());
                    targetDetail.setSort(item3.getSort());
                    targetDetail.setPrimaryFormula(epdPqd.getPrimaryFormula());
                    if (Objects.equals(map.get(epdPqd.getClassId()).getName(), "apf_data")) {
                        if (!Objects.isNull(epdPqd.getHarmStart()) && !Objects.isNull(epdPqd.getHarmEnd())) {
                            for (int i = epdPqd.getHarmStart(); i <= epdPqd.getHarmEnd(); i++) {
                                AppLineDetailVo.targetDetail t1 = new AppLineDetailVo.targetDetail();
                                t1.setTargetId(item3.getId());
                                t1.setName(item3.getName());
                                t1.setPhase(epdPqd.getPhase());
                                t1.setUnit(epdPqd.getUnit());
                                t1.setSort(item3.getSort());
                                t1.setPrimaryFormula(epdPqd.getPrimaryFormula());
                                //根据otherName反射获取DataV中的字段值，按lineId和相别匹配
                                String otherName = epdPqd.getOtherName();
                                ApfData matchedDataV = data14.stream()
                                        .filter(d -> Objects.equals(d.getLineId(), item.getLineId())
                                                && Objects.equals(d.getPhaseType(), epdPqd.getPhase()))
                                        .findFirst()
                                        .orElse(null);
                                if (matchedDataV != null) {
                                    Object value = ReflectUtils.getValue(matchedDataV, toCamelCase(otherName + "_" + i));
                                    if (value instanceof Number) {
                                        t1.setData(((Number) value).doubleValue());
                                    }
                                    vo.setDataTime(matchedDataV.getTime());
                                }
                                t1.setName(i + "次" + item3.getName());
                                finalChildren.add(t1);
                            }
                        } else {
                            //根据otherName反射获取DataV中的字段值，按lineId和相别匹配
                            String otherName = epdPqd.getOtherName();
                            ApfData matchedDataV = data14.stream()
                                    .filter(d -> Objects.equals(d.getLineId(), item.getLineId())
                                            && Objects.equals(d.getPhaseType(), epdPqd.getPhase()))
                                    .findFirst()
                                    .orElse(null);
                            if (matchedDataV != null) {
                                Object value = ReflectUtils.getValue(matchedDataV, toCamelCase(otherName));
                                if (value instanceof Number) {
                                    targetDetail.setData(((Number) value).doubleValue());
                                }
                                vo.setDataTime(matchedDataV.getTime());
                            }
                        }
                    }
                    if (Objects.isNull(epdPqd.getHarmStart()) && Objects.isNull(epdPqd.getHarmEnd())) {
                        finalChildren.add(targetDetail);
                    }
                });
            });
            // 根据接线方式处理相别
            chanelPhase(lineMap, item, finalChildren, children2);
            // 处理一二次值
            String dataLevel = csDataSetMap.get(lineMap.get(item.getLineId()).getDataSetId()).getDataLevel();
            chanelData(children2,dataLevel1,dataLevel,pt,ct);
            if (CollUtil.isNotEmpty(children2)) {
                children2.sort(Comparator.comparingInt(AppLineDetailVo.targetDetail::getSort));
                children2.forEach(item2->{
                    if (Objects.isNull(item2.getData())) {
                        item2.setData(3.15159);
                    }
                    if (!Objects.equals(item2.getData(),NULL_DATA)) {
                        item2.setData(BigDecimal.valueOf(item2.getData()).setScale(2, RoundingMode.HALF_UP).doubleValue());
                    }
                });
            }
            vo.setChildren(children2);
            result.add(vo);
        });
        return result;
    }

    public String toCamelCase(String input) {
        if (input == null || input.isEmpty()) {
            return input;
        }
        StringBuilder result = new StringBuilder();
        boolean toUpper = false;

        for (char c : input.toCharArray()) {
            if (c == '_') {
                toUpper = true;
            } else {
                if (toUpper) {
                    result.append(Character.toUpperCase(c));
                    toUpper = false;
                } else {
                    result.append(c);
                }
            }
        }
        // 确保首字母小写，以匹配Java实体字段命名规范
        if (result.length() > 0 && Character.isUpperCase(result.charAt(0))) {
            result.setCharAt(0, Character.toLowerCase(result.charAt(0)));
        }
        return result.toString();
    }

    public int compareWithCurrentTime(String timeString) {
        // 定义日期时间格式
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        // 解析字符串时间为LocalDateTime对象
        LocalDateTime specifiedTime = LocalDateTime.parse(timeString, formatter);
        // 获取当前时间
        LocalDateTime currentTime = LocalDateTime.now();
        // 比较两个时间
        return currentTime.compareTo(specifiedTime);
    }


    public ReqAndResDto.Req askApfModuleData(Integer mid, Integer clDId, Integer idx) {
        ReqAndResDto.Req reqAndResParam = new ReqAndResDto.Req();
        reqAndResParam.setMid(mid);
        reqAndResParam.setPri(AccessEnum.FIRST_CHANNEL.getCode());
        reqAndResParam.setType(Integer.parseInt(TypeEnum.TYPE_6.getCode()));
        reqAndResParam.setExpire(-1);
        //fixme 目前设备都是直连设备，因此did就是其本身，默认为1，后期涉及网关，此did是需要动态变化的
        reqAndResParam.setDid(1);
        AskDataDto askDataDto = new AskDataDto();
        askDataDto.setCldid(clDId);
        askDataDto.setDataAttr(1);
        askDataDto.setDataType(15);
        askDataDto.setOperate(1);
        askDataDto.setStartTime(-1);
        askDataDto.setEndTime(-1);
        askDataDto.setDsNameIdx(idx);
        reqAndResParam.setMsg(askDataDto);
        return reqAndResParam;
    }

    public String channelState(Double value) {
        String str;
        int val = (int) Math.round(value);
        switch (val) {
            case 0:
                str = "离线";
                break;
            case 1:
                str = "停止";
                break;
            case 2:
                str = "运行";
                break;
            case 3:
                str = "故障";
                break;
            default:
                str = "无状态";
                break;
        }
        return str;
    }

    public String channelState2(String code) {
        String str = null;
        if ("Alm_Apf_ModDisConnect".equals(code)) {
            str = "离线";
        } else if ("Alm_Apf_ModRunStop".equals(code) || "Alm_Apf_JT_stsLock".equals(code) || "Alm_Apf_JT_stsUnLock".equals(code)) {
            str = "停止";
        } else if ("Alm_Apf_ModRunRun".equals(code)) {
            str = "运行";
        } else if ("Alm_Apf_ModRunFault".equals(code)) {
            str = "故障";
        }
        return str;
    }

}
