package com.njcn.csdevice.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.DateUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONConfig;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.njcn.common.pojo.exception.BusinessException;
import com.njcn.csdevice.api.CsLineFeignClient;
import com.njcn.csdevice.api.EquipmentFeignClient;
import com.njcn.csdevice.constant.DataParam;
import com.njcn.csdevice.enums.AlgorithmResponseEnum;
import com.njcn.csdevice.enums.LineBaseEnum;
import com.njcn.csdevice.mapper.CsDataArrayMapper;
import com.njcn.csdevice.mapper.CsDataSetMapper;
import com.njcn.csdevice.mapper.CsGroArrMapper;
import com.njcn.csdevice.mapper.CsGroupMapper;
import com.njcn.csdevice.pojo.dto.CsEquipmentDeliveryDTO;
import com.njcn.csdevice.pojo.dto.CsLineDTO;
import com.njcn.csdevice.pojo.param.EnergyBaseParam;
import com.njcn.csdevice.pojo.po.*;
import com.njcn.csdevice.pojo.vo.CsGroupVO;
import com.njcn.csdevice.pojo.vo.DataGroupEventVO;
import com.njcn.csdevice.pojo.vo.DataGroupTemplateVO;
import com.njcn.csdevice.pojo.vo.EnergyTemplateVO;
import com.njcn.csdevice.service.CsLinePOService;
import com.njcn.csdevice.service.ICsDataArrayService;
import com.njcn.csdevice.service.ICsGroupService;
import com.njcn.csdevice.service.ICsLedgerService;
import com.njcn.csdevice.util.InfluxDbParamUtil;
import com.njcn.csdevice.utils.DataChangeUtil;
import com.njcn.csharmonic.api.EventFeignClient;
import com.njcn.csharmonic.api.PqGovernPlanFeignClient;
import com.njcn.csharmonic.constant.HarmonicConstant;
import com.njcn.csharmonic.param.*;
import com.njcn.csharmonic.pojo.po.PqGovernPlan;
import com.njcn.csharmonic.pojo.vo.ThdDataTdVO;
import com.njcn.csharmonic.pojo.vo.ThdDataVO;
import com.njcn.device.biz.mapper.OverLimitWlMapper;
import com.njcn.device.biz.pojo.po.Overlimit;
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.service.CommonService;
import com.njcn.influx.service.EvtDataService;
import com.njcn.system.api.*;
import com.njcn.system.pojo.po.EleEpdPqd;
import com.njcn.system.pojo.po.EleEvtParm;
import com.njcn.system.pojo.vo.CsStatisticalSetVO;
import com.njcn.system.pojo.vo.EleEpdPqdListVO;
import lombok.AllArgsConstructor;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.time.Instant;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * <p>
 * 数据分组表 服务实现类
 * </p>
 *
 * @author xuyang
 * @since 2023-06-16
 */
@Service
@AllArgsConstructor
public class CsGroupServiceImpl extends ServiceImpl<CsGroupMapper, CsGroup> implements ICsGroupService {

    private final ICsDataArrayService csDataArrayService;
    private final CsGroArrMapper csGroArrMapper;
    private final CsGroupMapper csGroupMapper;
    private final CsDataArrayMapper csDataArrayMapper;
    private final CommonService commonService;
    private final EpdFeignClient epdFeignClient;
    private final CsLineFeignClient csLineFeignClient;
    private final ICsLedgerService iCsLedgerService;
    private final EquipmentFeignClient equipmentFeignClient;
    private final CsStatisticalSetFeignClient csStatisticalSetFeignClient;
    private final EvtDataService evtDataService;
    private final DecimalFormat df = new DecimalFormat("#0.00");
    private final EleEvtFeignClient eleEvtFeignClient;
    private final OverLimitWlMapper overLimitWlMapper;
    private final CsDataSetMapper csDataSetMapper;
    private final EventFeignClient eventFeignClient;
    private final InfluxDbParamUtil influxDbParamUtil;
    private final DictTreeFeignClient dictTreeFeignClient;
    private final DicDataFeignClient dicDataFeignClient;
    private static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd");
    private static final ZoneId DEFAULT_ZONE = ZoneId.systemDefault();

    private final String GRID_SIDE_DICT_CODE = "Grid_Side";
    private final String LOAD_SIDE_DICT_CODE = "Load_Side";
    private final CsLinePOService csLinePOService;
    private final PqGovernPlanFeignClient pqGovernPlanFeignClient;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public List<CsGroupVO> getGroupData(String dataSet) {
        List<CsGroupVO> list = this.baseMapper.getGroupData(dataSet);
        List<CsGroupVO> result;
        if (CollectionUtil.isEmpty(list)) {
            result = insertGroupData(dataSet);
        } else {
            List<String> groupList = list.stream().map(CsGroupVO::getId).collect(Collectors.toList());
            List<CsGroupVO> arrayList = this.baseMapper.getArrayData(groupList);
            result = list.stream().peek((item -> item.setChildren(getChildrenes(item.getId(), arrayList)))).collect(Collectors.toList());
        }
        return result;
    }


    @Override
    public IPage<DataGroupTemplateVO> getDeviceRtData(String id, Integer pageNum, Integer pageSize, String lineId, String searchValue, String dataLevel) {
        IPage<DataGroupTemplateVO> pageTurn = new Page<>();
        List<EnergyTemplateVO> arrayList = new ArrayList<>();
        IPage<DataGroupTemplateVO> pageRes = csGroupMapper.getGroupDataList(new Page<>(pageNum, pageSize),id,searchValue);
        if (pageRes.getTotal() != 0) {
            List<DataGroupTemplateVO> groupList = pageRes.getRecords();
            List<String> group = groupList.stream().map(DataGroupTemplateVO::getId).collect(Collectors.toList());
            //获取当前组的所有指标项
            List<EnergyTemplateVO> list = csDataArrayMapper.getArrayByGroup(group);
            //获取所有字典指标
            List<EleEpdPqd> epdPqdList = epdFeignClient.selectByIds(list.stream().map(EnergyTemplateVO::getDataId).distinct().collect(Collectors.toList())).getData();
            Map<String, EleEpdPqd> eventTypeMap = epdPqdList.stream().collect(Collectors.toMap(EleEpdPqd::getId, Function.identity()));
            getUnit(list,epdPqdList,groupList,dataLevel);
            //根据lineId获取监测点pt、ct变比
            CsLinePO csLinePO = csLineFeignClient.queryLineById(Collections.singletonList(lineId)).getData().get(0);
            CsDataSet csDataSet = csDataSetMapper.selectOne(new LambdaQueryWrapper<CsDataSet>().eq(CsDataSet::getId,csLinePO.getDataSetId()));
            if(Objects.isNull(csDataSet) || StrUtil.isBlank(csDataSet.getDataLevel())){
                throw new BusinessException("当前测点数据集主要信息缺失,请联系管理员排查(测点表里面数据集id缺失)");
            }
            //获取测点模板
            for (EnergyTemplateVO item : list) {
                EnergyTemplateVO vo = new EnergyTemplateVO();
                BeanUtils.copyProperties(item,vo);
                EleEpdPqd eleEpdPqd = eventTypeMap.get(item.getDataId());
                vo.setClassId(eleEpdPqd.getClassId());
                vo.setUnit(eleEpdPqd.getUnit());
                StatisticalDataDTO statisticalDataDTO = commonService.getLineRtData(lineId,influxDbParamUtil.getTableNameByClassId(eleEpdPqd.getClassId()),item.getName(),item.getPhase(),item.getStatMethod(),influxDbParamUtil.getClDidByLineId(lineId));
                if (Objects.nonNull(statisticalDataDTO)) {
                    vo.setTime(statisticalDataDTO.getTime());
                    //判断监测点类型 针对治理设备 模块数据是一次值、电能质量设备是二次值
                    if (ObjectUtil.isNotNull(eleEpdPqd.getPrimaryFormula()) && !Objects.equals(csDataSet.getDataLevel(),dataLevel)) {
                        double re;
                        if("Primary".equals(csDataSet.getDataLevel())){
                            re = DataChangeUtil.primaryToSecondary(eleEpdPqd.getPrimaryFormula(), statisticalDataDTO.getValue(), csLinePO.getPtRatio(), csLinePO.getCtRatio());
                        }else {
                            re = DataChangeUtil.secondaryToPrimary(eleEpdPqd.getPrimaryFormula(), statisticalDataDTO.getValue(), csLinePO.getPtRatio(), csLinePO.getCtRatio());
                        }
                        if (changePower(vo.getAnotherName()) && Objects.equals(dataLevel,"Primary")) {
                            vo.setDataValue(Double.valueOf(df.format(BigDecimal.valueOf(re / 1000).setScale(2, RoundingMode.HALF_UP).doubleValue())));
                        } else {
                            vo.setDataValue(Double.valueOf(df.format(BigDecimal.valueOf(re).setScale(2, RoundingMode.HALF_UP).doubleValue())));
                        }
                    } else {
                        if (changePower(vo.getAnotherName()) && Objects.equals(dataLevel,"Primary")) {
                            vo.setDataValue(Double.valueOf(df.format(BigDecimal.valueOf(statisticalDataDTO.getValue()/1000).setScale(2, RoundingMode.HALF_UP).doubleValue())));
                        } else {
                            vo.setDataValue(Double.valueOf(df.format(BigDecimal.valueOf(statisticalDataDTO.getValue()).setScale(2, RoundingMode.HALF_UP).doubleValue())));
                        }
                    }
                } else {
                    vo.setDataValue(3.1415926);
                }
                if (vo.getAnotherName().contains("A相") || vo.getAnotherName().contains("B相") || vo.getAnotherName().contains("C相")) {
                    vo.setAnotherName(vo.getAnotherName().substring(0,2));
                } else if (vo.getAnotherName().contains("AB") || vo.getAnotherName().contains("BC") || vo.getAnotherName().contains("CA")) {
                    vo.setAnotherName(vo.getAnotherName().substring(0,2).concat("相"));
                }
                arrayList.add(vo);
            }
            if (CollectionUtil.isNotEmpty(arrayList)){
                List<DataGroupTemplateVO> grList = groupList.stream().peek((item) -> {item.setChildren(getChildren(item.getId(), arrayList));}).collect(Collectors.toList());
                pageTurn.setRecords(grList);
                pageTurn.setTotal(pageRes.getTotal());
                pageTurn.setSize(pageRes.getSize());
                pageTurn.setCurrent(pageRes.getCurrent());
                pageTurn.setPages(pageRes.getPages());
            }
        } else {
            pageTurn.setRecords(new ArrayList<>());
            pageTurn.setTotal(pageRes.getTotal());
            pageTurn.setSize(pageRes.getSize());
            pageTurn.setCurrent(pageRes.getCurrent());
            pageTurn.setPages(pageRes.getPages());
        }
        return pageTurn;
    }

    @Override
    public IPage<DataGroupTemplateVO> getDeviceHistoryData(EnergyBaseParam energyBaseParam) {
        IPage<DataGroupTemplateVO> pageTurn = new Page<>();
        List<EnergyTemplateVO> arrayList = new ArrayList<>();
        IPage<DataGroupTemplateVO> pageRes = csGroupMapper.getGroupDataList(new Page<>(energyBaseParam.getPageNum(), energyBaseParam.getPageSize()), energyBaseParam.getId(), energyBaseParam.getSearchValue());
        if (pageRes.getTotal() != 0) {
            List<DataGroupTemplateVO> groupList = pageRes.getRecords();
            List<String> group = groupList.stream().map(DataGroupTemplateVO::getId).collect(Collectors.toList());
            //获取当前组的所有指标项
            List<EnergyTemplateVO> list = csDataArrayMapper.getArrayByGroup(group);
            //获取所有字典指标
            List<EleEpdPqd> epdPqdList = epdFeignClient.selectByIds(list.stream().map(EnergyTemplateVO::getDataId).distinct().collect(Collectors.toList())).getData();
            Map<String, EleEpdPqd> eventTypeMap = epdPqdList.stream().collect(Collectors.toMap(EleEpdPqd::getId, Function.identity()));
            getUnit(list,epdPqdList,groupList,energyBaseParam.getDataLevel());
            //根据lineId获取监测点pt、ct变比
            CsLinePO po = csLineFeignClient.queryLineById(Collections.singletonList(energyBaseParam.getLineId())).getData().get(0);
            CsDataSet csDataSet = csDataSetMapper.selectOne(new LambdaQueryWrapper<CsDataSet>().eq(CsDataSet::getId,po.getDataSetId()));
            if(Objects.isNull(csDataSet) || StrUtil.isBlank(csDataSet.getDataLevel())){
                throw new BusinessException("当前测点数据集主要信息缺失,请联系管理员排查(测点表里面数据集id缺失)");
            }

            for (EnergyTemplateVO item : list) {
                EnergyTemplateVO vo = new EnergyTemplateVO();
                BeanUtils.copyProperties(item,vo);
                EleEpdPqd eleEpdPqd = eventTypeMap.get(item.getDataId());
                if (Objects.nonNull(eleEpdPqd.getUnit())){
                    vo.setAnotherName(vo.getAnotherName()+"("+eleEpdPqd.getUnit()+")");
                }
                vo.setClassId(eleEpdPqd.getClassId());
                vo.setUnit(eleEpdPqd.getUnit());
                StatisticalDataDTO statisticalDataDTO = commonService.getLineHistoryData(energyBaseParam.getLineId(),influxDbParamUtil.getTableNameByClassId(eleEpdPqd.getClassId()),item.getName(),energyBaseParam.getStartTime() + " 00:00:00",energyBaseParam.getEndTime() + " 23:59:59",influxDbParamUtil.getClDidByLineId(energyBaseParam.getLineId()));
                if (Objects.nonNull(statisticalDataDTO)) {
                    vo.setTime(statisticalDataDTO.getTime());
                    //判断监测点类型 针对治理设备 模块数据是一次值、电能质量设备是二次值
                    if (ObjectUtil.isNotNull(eleEpdPqd.getPrimaryFormula()) && !Objects.equals(csDataSet.getDataLevel(),energyBaseParam.getDataLevel()) ) {
                        double secondaryData1;
                        double secondaryData2;
                        double secondaryData3;
                        if("Primary".equals(csDataSet.getDataLevel())){
                            secondaryData1 = DataChangeUtil.primaryToSecondary(eleEpdPqd.getPrimaryFormula(), statisticalDataDTO.getMaxValue(), po.getPtRatio(), po.getCtRatio());
                            secondaryData2 = DataChangeUtil.primaryToSecondary(eleEpdPqd.getPrimaryFormula(), statisticalDataDTO.getMinValue(), po.getPtRatio(), po.getCtRatio());
                            secondaryData3 = DataChangeUtil.primaryToSecondary(eleEpdPqd.getPrimaryFormula(), statisticalDataDTO.getAvgValue(), po.getPtRatio(), po.getCtRatio());
                        }else {
                            secondaryData1 = DataChangeUtil.secondaryToPrimary(eleEpdPqd.getPrimaryFormula(), statisticalDataDTO.getMaxValue(), po.getPtRatio(), po.getCtRatio());
                            secondaryData2 = DataChangeUtil.secondaryToPrimary(eleEpdPqd.getPrimaryFormula(), statisticalDataDTO.getMinValue(), po.getPtRatio(), po.getCtRatio());
                            secondaryData3 = DataChangeUtil.secondaryToPrimary(eleEpdPqd.getPrimaryFormula(), statisticalDataDTO.getAvgValue(), po.getPtRatio(), po.getCtRatio());
                        }

                        if (changePower(vo.getAnotherName())) {
                            vo.setMaxValue(Double.valueOf(df.format(BigDecimal.valueOf(secondaryData1/1000).setScale(2, RoundingMode.HALF_UP).doubleValue())));
                            vo.setMinValue(Double.valueOf(df.format(BigDecimal.valueOf(secondaryData2/1000).setScale(2, RoundingMode.HALF_UP).doubleValue())));
                            vo.setAvgValue(Double.valueOf(df.format(BigDecimal.valueOf(secondaryData3/1000).setScale(2, RoundingMode.HALF_UP).doubleValue())));
                        } else {
                            vo.setMaxValue(Double.valueOf(df.format(BigDecimal.valueOf(secondaryData1).setScale(2, RoundingMode.HALF_UP).doubleValue())));
                            vo.setMinValue(Double.valueOf(df.format(BigDecimal.valueOf(secondaryData2).setScale(2, RoundingMode.HALF_UP).doubleValue())));
                            vo.setAvgValue(Double.valueOf(df.format(BigDecimal.valueOf(secondaryData3).setScale(2, RoundingMode.HALF_UP).doubleValue())));
                        }
                    } else {
                        if (changePower(vo.getAnotherName())) {
                            vo.setMaxValue(Double.valueOf(df.format(BigDecimal.valueOf(statisticalDataDTO.getMaxValue()/1000).setScale(2, RoundingMode.HALF_UP).doubleValue())));
                            vo.setMinValue(Double.valueOf(df.format(BigDecimal.valueOf(statisticalDataDTO.getMinValue()/1000).setScale(2, RoundingMode.HALF_UP).doubleValue())));
                            vo.setAvgValue(Double.valueOf(df.format(BigDecimal.valueOf(statisticalDataDTO.getAvgValue()/1000).setScale(2, RoundingMode.HALF_UP).doubleValue())));
                        } else {
                            vo.setMaxValue(Double.valueOf(df.format(BigDecimal.valueOf(statisticalDataDTO.getMaxValue()).setScale(2, RoundingMode.HALF_UP).doubleValue())));
                            vo.setMinValue(Double.valueOf(df.format(BigDecimal.valueOf(statisticalDataDTO.getMinValue()).setScale(2, RoundingMode.HALF_UP).doubleValue())));
                            vo.setAvgValue(Double.valueOf(df.format(BigDecimal.valueOf(statisticalDataDTO.getAvgValue()).setScale(2, RoundingMode.HALF_UP).doubleValue())));
                        }
                    }
                } else {
                    vo.setMaxValue(3.1415956);
                    vo.setMinValue(3.1415956);
                    vo.setAvgValue(3.1415956);
                }
                arrayList.add(vo);
            }
            if (CollectionUtil.isNotEmpty(arrayList)){
                List<DataGroupTemplateVO> grList = groupList.stream().peek((item) -> {item.setChildren(getChildren(item.getId(), arrayList));}).collect(Collectors.toList());
                pageTurn.setRecords(grList);
                pageTurn.setTotal(pageRes.getTotal());
                pageTurn.setSize(pageRes.getSize());
                pageTurn.setCurrent(pageRes.getCurrent());
                pageTurn.setPages(pageRes.getPages());
            }
        } else {
            pageTurn.setRecords(new ArrayList<>());
            pageTurn.setTotal(pageRes.getTotal());
            pageTurn.setSize(pageRes.getSize());
            pageTurn.setCurrent(pageRes.getCurrent());
            pageTurn.setPages(pageRes.getPages());
        }
        return pageTurn;
    }

    @Override
    public Object deviceDataByType(CommonStatisticalQueryParam commonStatisticalQueryParam) {
        String type = commonStatisticalQueryParam.getType();
        if (type == null){
            throw new BusinessException(LineBaseEnum.NOTYPE_FAIL.getMessage());
        }
        //传1 则是趋势数据tab页面
        if("1".equals(type)){
            formatQueryParamList(commonStatisticalQueryParam);
            List<ThdDataVO> result = new ArrayList<>();
            List<CsEquipmentDeliveryDTO> data1 = equipmentFeignClient.queryDeviceById(Stream.of(commonStatisticalQueryParam.getDevId()).collect(Collectors.toList())).getData();
            List<CsLinePO> finalCsLinePOList = csLineFeignClient.queryLineById(Collections.singletonList(commonStatisticalQueryParam.getLineId())).getData();
            CsDataSet csDataSet = csDataSetMapper.selectOne(new LambdaQueryWrapper<CsDataSet>().eq(CsDataSet::getId,finalCsLinePOList.get(0).getDataSetId()));
            if(Objects.isNull(csDataSet) || StrUtil.isBlank(csDataSet.getDataLevel())){
                throw new BusinessException("当前测点数据集主要信息缺失,请联系管理员排查(测点表里面数据集id缺失)");
            }
            Double ct = finalCsLinePOList.get(0).getCtRatio() / (Objects.isNull(finalCsLinePOList.get(0).getCt2Ratio())?1.0:finalCsLinePOList.get(0).getCt2Ratio());
            Double pt = finalCsLinePOList.get(0).getPtRatio() / (Objects.isNull(finalCsLinePOList.get(0).getPt2Ratio())?1.0:finalCsLinePOList.get(0).getPt2Ratio());
            if(CollectionUtil.isNotEmpty(commonStatisticalQueryParam.getList())){
                for (CommonStatisticalQueryParam param : commonStatisticalQueryParam.getList()){

                    List<EleEpdPqd> eleEpdPqds = csStatisticalSetFeignClient.queryStatisticalSelect(Collections.singletonList(param.getStatisticalId())).getData();
                    eleEpdPqds.forEach(epdPqd->{
                        List<CommonQueryParam> commonQueryParams = finalCsLinePOList.stream().map(temp -> {
                            CommonQueryParam commonQueryParam = new CommonQueryParam();
                            commonQueryParam.setLineId(temp.getLineId());
                            commonQueryParam.setTableName(influxDbParamUtil.getTableNameByClassId(epdPqd.getClassId()));
                            if (epdPqd.getName() == null || epdPqd.getName().isEmpty()) {
                                commonQueryParam.setColumnName(epdPqd.getName()+ (StringUtils.isEmpty(param.getFrequency()) ? "":"_"+param.getFrequency()));
                            } else {
                                commonQueryParam.setColumnName(epdPqd.getOtherName()+ (StringUtils.isEmpty(param.getFrequency()) ? "":"_"+param.getFrequency()));
                            }
                            commonQueryParam.setPhasic(epdPqd.getPhase());

                            commonQueryParam.setStartTime(DateUtil.format(DateUtil.parse(commonStatisticalQueryParam.getStartTime(),DatePattern.NORM_DATE_PATTERN), DatePattern.NORM_DATETIME_PATTERN));
                            commonQueryParam.setEndTime(DateUtil.format(DateUtil.endOfDay(DateUtil.parse(commonStatisticalQueryParam.getEndTime(),DatePattern.NORM_DATE_PATTERN)), DatePattern.NORM_DATETIME_PATTERN));

                            commonQueryParam.setDataType(commonStatisticalQueryParam.getValueType().toUpperCase());
                            commonQueryParam.setProcess(data1.get(0).getProcess()+"");
                            commonQueryParam.setClDid(influxDbParamUtil.getClDidByLineId(temp.getLineId()));
                            return commonQueryParam;
                        }).collect(Collectors.toList());
                        List<StatisticalDataDTO> deviceRtData = commonService.getDeviceRtDataByTime(commonQueryParams);
                        List<ThdDataVO> collect1 = deviceRtData.stream().map(temp -> {
                            String unit;
                            ThdDataVO vo = new ThdDataVO();
                            vo.setLineId(temp.getLineId());
                            vo.setPhase(Objects.equals("T",temp.getPhaseType())?null:temp.getPhaseType());
                            String position = finalCsLinePOList.stream().filter(csLinePO -> Objects.equals(csLinePO.getLineId(), vo.getLineId())).collect(Collectors.toList()).get(0).getPosition();
                            vo.setPosition(position);
                            vo.setTime(temp.getTime());
                            vo.setStatMethod(temp.getValueType());
                            vo.setStatisticalData(Double.valueOf(df.format(temp.getValue())));
                            if(temp.getValue()!=null) {
                                double re = 0;
                                if (Objects.equals("Primary",commonStatisticalQueryParam.getDataLevel())) {
                                    if (Objects.equals("Primary",csDataSet.getDataLevel())) {
                                        if (HarmonicConstant.POWER_LIST.contains(epdPqd.getShowName())) {
                                            re = Objects.isNull(temp.getValue()) ? 3.14159 : Double.parseDouble(df.format(temp.getValue() / 1000));
                                            vo.setStatisticalData(re);
                                            unit = "k" + epdPqd.getUnit();
                                        } else {
                                            vo.setStatisticalData(Objects.isNull(temp.getValue()) ? 3.14159 : Double.parseDouble(df.format(temp.getValue())));
                                            unit = epdPqd.getUnit();
                                        }
                                    } else {
                                        if(Objects.nonNull(epdPqd.getPrimaryFormula())){
                                            switch (epdPqd.getPrimaryFormula()) {
                                                case "*PT":
                                                    re = temp.getValue() * pt / 1000;
                                                    unit = "k" + epdPqd.getUnit();
                                                    break;
                                                case "*CT":
                                                    re = temp.getValue() * ct;
                                                    unit = epdPqd.getUnit();
                                                    break;
                                                case "*PT*CT":
                                                    re = temp.getValue() * pt * ct / 1000;
                                                    unit = "k" + epdPqd.getUnit();
                                                    break;
                                                default:
                                                    re = temp.getValue();
                                                    unit = epdPqd.getUnit();
                                                    break;
                                            }
                                            vo.setStatisticalData(Double.valueOf(df.format(re)));
                                        }else {
                                            re = temp.getValue();
                                            unit = epdPqd.getUnit();
                                            vo.setStatisticalData(Double.valueOf(df.format(re)));
                                        }

                                    }
                                } else {
                                    if (Objects.equals("Primary",csDataSet.getDataLevel())) {
                                        if(Objects.nonNull(epdPqd.getPrimaryFormula())){
                                            switch (epdPqd.getPrimaryFormula()) {
                                                case "*PT":
                                                    re = temp.getValue() / pt;
                                                    break;
                                                case "*CT":
                                                    re = temp.getValue() / ct;
                                                    break;
                                                case "*PT*CT":
                                                    re = temp.getValue() / pt / ct;
                                                    break;
                                                default:
                                                    re = temp.getValue();
                                                    break;
                                            }
                                            vo.setStatisticalData(Double.valueOf(df.format(re)));
                                        }else {
                                            re = temp.getValue();
                                            vo.setStatisticalData(Double.valueOf(df.format(re)));
                                        }
                                    } else {
                                        vo.setStatisticalData(Double.valueOf(df.format(temp.getValue())));
                                    }
                                    unit = epdPqd.getUnit();
                                }
                            } else {
                                vo.setStatisticalData(null);
                                if (Objects.equals("Primary",commonStatisticalQueryParam.getDataLevel())) {
                                    if (Objects.equals("Primary",csDataSet.getDataLevel())) {
                                        unit = epdPqd.getUnit();
                                    } else {
                                        if(Objects.nonNull(epdPqd.getPrimaryFormula())){
                                            switch (epdPqd.getPrimaryFormula()) {
                                                case "*PT":
                                                    unit = "k" + epdPqd.getUnit();
                                                    break;
                                                case "*CT":
                                                    unit = epdPqd.getUnit();
                                                    break;
                                                case "*PT*CT":
                                                    unit = "k" + epdPqd.getUnit();
                                                    break;
                                                default:
                                                    unit = epdPqd.getUnit();
                                                    break;
                                            }
                                        }else {
                                            unit = epdPqd.getUnit();
                                        }
                                    }
                                } else {
                                    unit = epdPqd.getUnit();
                                }
                            }
                            vo.setUnit(unit);
                            vo.setStatisticalIndex(epdPqd.getId());
                            vo.setStatisticalName(epdPqd.getName());
                            vo.setAnotherName(epdPqd.getShowName());
                            return vo;
                        }).collect(Collectors.toList());
                        result.addAll(collect1);
                    });
                }
            }
            return result;
        }else if("2".equals(type)){
            //传2 则是实时数据tab页面
            List<ThdDataVO> result = new ArrayList();
            List<CsLinePO> finalCsLinePOList = csLineFeignClient.queryLineById(Arrays.asList(commonStatisticalQueryParam.getLineId())).getData();
            List<CsEquipmentDeliveryDTO> data1 = equipmentFeignClient.queryDeviceById(Stream.of(commonStatisticalQueryParam.getDevId()).collect(Collectors.toList())).getData();
            //便携式设备的稳态指标
            CsStatisticalSetVO csStatisticalSetVO = csStatisticalSetFeignClient.queryStatistical(DataParam.portableDevStatisticalId).getData();
            List<EleEpdPqd> eleEpdPqds = new ArrayList<>();
            csStatisticalSetVO.getSelectedList().forEach(css->{
                eleEpdPqds.addAll(css.getEleEpdPqdVOS());
            });
            eleEpdPqds.forEach(epdPqd->{
                String frequency = "";
                if(epdPqd.getHarmStart() != null && epdPqd.getHarmEnd() != null){
                    frequency = "_" + epdPqd.getHarmStart().intValue();
                }
                String finalFrequency = frequency;
                List<CommonQueryParam> commonQueryParams = finalCsLinePOList.stream().map(temp -> {
                    CommonQueryParam commonQueryParam = new CommonQueryParam();
                    commonQueryParam.setLineId(temp.getLineId());
                    commonQueryParam.setTableName(influxDbParamUtil.getTableNameByClassId(epdPqd.getClassId()));
                    commonQueryParam.setColumnName(epdPqd.getName()+ finalFrequency);
                    if (epdPqd.getName() == null || epdPqd.getName().isEmpty()) {
                        commonQueryParam.setColumnName(epdPqd.getName()+ finalFrequency);
                    } else {
                        commonQueryParam.setColumnName(epdPqd.getOtherName()+ finalFrequency);
                    }
                    commonQueryParam.setPhasic(epdPqd.getPhase());
                    commonQueryParam.setDataType(commonStatisticalQueryParam.getValueType() == null ? DataParam.portableDevStatisticalMethods.toUpperCase():commonStatisticalQueryParam.getValueType().toUpperCase());
                    commonQueryParam.setProcess(data1.get(0).getProcess()+"");
                    commonQueryParam.setClDid(influxDbParamUtil.getClDidByLineId(temp.getLineId()));
                    return commonQueryParam;
                }).collect(Collectors.toList());
                List<StatisticalDataDTO> deviceRtData = commonService.getDeviceRtData(commonQueryParams);
                List<ThdDataVO> collect1 = deviceRtData.stream().map(temp -> {
                    ThdDataVO vo = new ThdDataVO();
                    vo.setLineId(temp.getLineId());
                    vo.setPhase(Objects.equals("T",temp.getPhaseType())?null:temp.getPhaseType());
                    String position = finalCsLinePOList.stream().filter(csLinePO -> Objects.equals(csLinePO.getLineId(), vo.getLineId())).collect(Collectors.toList()).get(0).getPosition();
                    vo.setPosition(position);
                    vo.setTime(temp.getTime());
                    vo.setStatMethod(temp.getValueType());
                    vo.setStatisticalData(Double.valueOf(df.format(temp.getValue())));
                    vo.setStatisticalIndex(epdPqd.getId());
                    vo.setUnit(epdPqd.getUnit());
                    vo.setStatisticalName(epdPqd.getName());
                    vo.setAnotherName(epdPqd.getShowName());
                    return vo;
                }).collect(Collectors.toList());
                result.addAll(collect1);
            });
            return result;
        }else if("3".equals(type)){
            //传3 则是暂态事件tab页面
            CsEventUserQueryPage csEventUserQueryPage = new CsEventUserQueryPage();
            csEventUserQueryPage.setPageNum(commonStatisticalQueryParam.getPageNum());
            csEventUserQueryPage.setPageSize(commonStatisticalQueryParam.getPageSize());
            csEventUserQueryPage.setLineId(commonStatisticalQueryParam.getLineId());
            csEventUserQueryPage.setStartTime(commonStatisticalQueryParam.getStartTime());
            csEventUserQueryPage.setEndTime(commonStatisticalQueryParam.getEndTime());
            csEventUserQueryPage.setEvtParamTmMin(commonStatisticalQueryParam.getEvtParamTmMin());
            csEventUserQueryPage.setEvtParamTmMax(commonStatisticalQueryParam.getEvtParamTmMax());
            csEventUserQueryPage.setFeatureAmplitudeMin(commonStatisticalQueryParam.getFeatureAmplitudeMin());
            csEventUserQueryPage.setFeatureAmplitudeMax(commonStatisticalQueryParam.getFeatureAmplitudeMax());
            csEventUserQueryPage.setSeverityMin(commonStatisticalQueryParam.getSeverityMin());
            csEventUserQueryPage.setSeverityMax(commonStatisticalQueryParam.getSeverityMax());
            csEventUserQueryPage.setTarget(commonStatisticalQueryParam.getTarget());
            csEventUserQueryPage.setFileFlag(commonStatisticalQueryParam.getFileFlag());
            Page<DataGroupEventVO> csEventVOPage = eventFeignClient.pageQueryByLineId(csEventUserQueryPage).getData();
            //获取监测点电压等级
            List<CsLineDTO> list = csLinePOService.getAllLineDetail();
            Map<String, CsLineDTO> map = list.stream().collect(Collectors.toMap(CsLineDTO::getLineId, temp -> temp));
            csEventVOPage.getRecords().forEach(temp->{
                //监测点电压等级
                Double volGrade = map.get(temp.getLineId()).getVolGrade();
                if (!Objects.isNull(volGrade)) {
                    temp.setLineVoltage(volGrade);
                }
                //事件描述、相别、暂降幅值,需要特殊处理赋值
                //事件描述
                CsLedger dataById = iCsLedgerService.findDataById(temp.getLineId());
                temp.setLineName(dataById.getName());
                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(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(), 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(), DataParam.EvtParamDepth)).
                            collect(Collectors.toList());
                    if(CollectionUtil.isEmpty(evtParamDepth)){
                        temp.setFeatureAmplitude(null);
                    }else {
                        temp.setFeatureAmplitude(evtParamDepth.get(0).getValue().equals("-")?null:Float.parseFloat(evtParamDepth.get(0).getValue()));
                    }
                    List<EventDataSetDTO> evtParmTm = eventDataSetDTOS.stream().
                            filter(dataSetDTO -> Objects.equals(dataSetDTO.getName(), DataParam.EVTPARAMTM)).
                            collect(Collectors.toList());
                    if(CollectionUtil.isEmpty(evtParamDepth)){
                        temp.setPersistTime(null);
                    }else {
                        temp.setPersistTime(evtParmTm.get(0).getValue().equals("-")?null:Double.parseDouble(evtParmTm.get(0).getValue()));
                    }
                }
            });
            return csEventVOPage;
        } else if ("4".equals(type)) {
            formatQueryParamList(commonStatisticalQueryParam);
            List<ThdDataVO> result = new ArrayList<>();
            List<CsLinePO> finalCsLinePOList = csLineFeignClient.queryLineById(Collections.singletonList(commonStatisticalQueryParam.getLineId())).getData();
            CsDataSet csDataSet = csDataSetMapper.selectOne(new LambdaQueryWrapper<CsDataSet>().eq(CsDataSet::getId, finalCsLinePOList.get(0).getDataSetId()));
            if (Objects.isNull(csDataSet) || StrUtil.isBlank(csDataSet.getDataLevel())) {
                throw new BusinessException("当前测点数据集主要信息缺失,请联系管理员排查(测点表里面数据集id缺失)");
                }
            Double ct = finalCsLinePOList.get(0).getCtRatio() / (Objects.isNull(finalCsLinePOList.get(0).getCt2Ratio()) ? 1.0 : finalCsLinePOList.get(0).getCt2Ratio());
            Double pt = finalCsLinePOList.get(0).getPtRatio() / (Objects.isNull(finalCsLinePOList.get(0).getPt2Ratio()) ? 1.0 : finalCsLinePOList.get(0).getPt2Ratio());
            if (CollectionUtil.isNotEmpty(commonStatisticalQueryParam.getList())) {
                for (CommonStatisticalQueryParam param : commonStatisticalQueryParam.getList()) {

                    List<EleEpdPqd> eleEpdPqds = csStatisticalSetFeignClient.queryStatisticalSelect(Collections.singletonList(param.getStatisticalId())).getData();
                    eleEpdPqds.forEach(epdPqd -> {
                        List<CommonQueryParam> commonQueryParams = finalCsLinePOList.stream().map(temp -> {
                            CommonQueryParam commonQueryParam = new CommonQueryParam();
                            commonQueryParam.setLineId(temp.getLineId());
                            commonQueryParam.setTableName(influxDbParamUtil.getTableNameByClassId(epdPqd.getClassId()));
                            if (epdPqd.getName() == null || epdPqd.getName().isEmpty()) {
                                commonQueryParam.setColumnName(epdPqd.getName() + (StringUtils.isEmpty(param.getFrequency()) ? "" : "_" + param.getFrequency()));
                            } else {
                                commonQueryParam.setColumnName(epdPqd.getOtherName() + (StringUtils.isEmpty(param.getFrequency()) ? "" : "_" + param.getFrequency()));
                            }
                            commonQueryParam.setPhasic(epdPqd.getPhase());

                            commonQueryParam.setStartTime(DateUtil.format(DateUtil.parse(commonStatisticalQueryParam.getStartTime(), DatePattern.NORM_DATE_PATTERN), DatePattern.NORM_DATETIME_PATTERN));
                            commonQueryParam.setEndTime(DateUtil.format(DateUtil.endOfDay(DateUtil.parse(commonStatisticalQueryParam.getEndTime(), DatePattern.NORM_DATE_PATTERN)), DatePattern.NORM_DATETIME_PATTERN));

                            commonQueryParam.setClDid(influxDbParamUtil.getClDidByLineId(temp.getLineId()));
                            return commonQueryParam;
                        }).collect(Collectors.toList());
                        List<StatisticalDataDTO> deviceRtData;
                        if (commonStatisticalQueryParam.getDataModel() == 0) {
                            deviceRtData = commonService.getDeviceRtDataByTime(commonQueryParams);
                        } else {
                            deviceRtData = commonService.getDianDuData(commonQueryParams);
                        }
                        List<ThdDataVO> collect1 = deviceRtData.stream().map(temp -> {
                            String unit;
                            ThdDataVO vo = new ThdDataVO();
                            vo.setLineId(temp.getLineId());
                            vo.setPhase(Objects.equals("T", temp.getPhaseType()) ? null : temp.getPhaseType());
                            String position = finalCsLinePOList.stream().filter(csLinePO -> Objects.equals(csLinePO.getLineId(), vo.getLineId())).collect(Collectors.toList()).get(0).getPosition();
                            vo.setPosition(position);
                            vo.setTime(temp.getTime());
                            vo.setStatMethod(temp.getValueType());
                            vo.setStatisticalData(Double.valueOf(df.format(temp.getValue())));
                            if (temp.getValue() != null) {
                                double re = 0;
                                if (Objects.equals("Primary", commonStatisticalQueryParam.getDataLevel())) {
                                    if (Objects.equals("Primary", csDataSet.getDataLevel())) {
                                        if (HarmonicConstant.POWER_LIST.contains(epdPqd.getShowName())) {
                                            re = Objects.isNull(temp.getValue()) ? 3.14159 : Double.parseDouble(df.format(temp.getValue()));
                                            vo.setStatisticalData(re);
                                            unit = epdPqd.getUnit();
                                        } else {
                                            vo.setStatisticalData(Objects.isNull(temp.getValue()) ? 3.14159 : Double.parseDouble(df.format(temp.getValue())));
                                            unit = epdPqd.getUnit();
                                        }
                                    } else {
                                        if (Objects.nonNull(epdPqd.getPrimaryFormula())) {
                                            switch (epdPqd.getPrimaryFormula()) {
                                                case "*PT":
                                                    re = temp.getValue() * pt;
                                                    unit = epdPqd.getUnit();
                                                    break;
                                                case "*CT":
                                                    re = temp.getValue() * ct;
                                                    unit = epdPqd.getUnit();
                                                    break;
                                                case "*PT*CT":
                                                    re = temp.getValue() * pt * ct;
                                                    unit = epdPqd.getUnit();
                                                    break;
                                                default:
                                                    re = temp.getValue();
                                                    unit = epdPqd.getUnit();
                                                    break;
                                            }
                                            vo.setStatisticalData(Double.valueOf(df.format(re)));
                                        } else {
                                            re = temp.getValue();
                                            unit = epdPqd.getUnit();
                                            vo.setStatisticalData(Double.valueOf(df.format(re)));
                                        }

                                    }
                                } else {
                                    if (Objects.equals("Primary", csDataSet.getDataLevel())) {
                                        if (Objects.nonNull(epdPqd.getPrimaryFormula())) {
                                            switch (epdPqd.getPrimaryFormula()) {
                                                case "*PT":
                                                    re = temp.getValue() / pt;
                                                    break;
                                                case "*CT":
                                                    re = temp.getValue() / ct;
                                                    break;
                                                case "*PT*CT":
                                                    re = temp.getValue() / pt / ct;
                                                    break;
                                                default:
                                                    re = temp.getValue();
                                                    break;
                                            }
                                            vo.setStatisticalData(Double.valueOf(df.format(re)));
                                        } else {
                                            re = temp.getValue();
                                            vo.setStatisticalData(Double.valueOf(df.format(re)));
                                        }
                                    } else {
                                        vo.setStatisticalData(Double.valueOf(df.format(temp.getValue())));
                                    }
                                    unit = epdPqd.getUnit();
                                }
                            } else {
                                vo.setStatisticalData(null);
                                if (Objects.equals("Primary", commonStatisticalQueryParam.getDataLevel())) {
                                    if (Objects.equals("Primary", csDataSet.getDataLevel())) {
                                        unit = epdPqd.getUnit();
                                    } else {
                                        if (Objects.nonNull(epdPqd.getPrimaryFormula())) {
                                            switch (epdPqd.getPrimaryFormula()) {
                                                case "*PT":
                                                    unit = epdPqd.getUnit();
                                                    break;
                                                case "*CT":
                                                    unit = epdPqd.getUnit();
                                                    break;
                                                case "*PT*CT":
                                                    unit = epdPqd.getUnit();
                                                    break;
                                                default:
                                                    unit = epdPqd.getUnit();
                                                    break;
                                            }
                                        } else {
                                            unit = epdPqd.getUnit();
                                        }
                                    }
                                } else {
                                    unit = epdPqd.getUnit();
                                }
                            }
                            vo.setUnit(unit);
                            vo.setStatisticalIndex(epdPqd.getId());
                            vo.setStatisticalName(epdPqd.getName());
                            vo.setAnotherName(epdPqd.getShowName());
                            return vo;
                        }).collect(Collectors.toList());
                        result.addAll(collect1);
                    });
                }
            }
            return result;
        }
        return null;
    }

    private void formatQueryParamList(CommonStatisticalQueryParam commonStatisticalQueryParam){
        List<CommonStatisticalQueryParam> list = new ArrayList<>();
        if(commonStatisticalQueryParam.getList() != null && commonStatisticalQueryParam.getList().size() > 0){
            for(CommonStatisticalQueryParam param : commonStatisticalQueryParam.getList()){
                if(param.getFrequencys() != null && param.getFrequencys().size() > 0){
                    for (String frequency : param.getFrequencys()){
                        CommonStatisticalQueryParam cp = new CommonStatisticalQueryParam();
                        cp.setStatisticalId(param.getStatisticalId());
                        cp.setFrequency(frequency);
                        list.add(cp);
                    }
                }else{
                    CommonStatisticalQueryParam cp = new CommonStatisticalQueryParam();
                    cp.setStatisticalId(param.getStatisticalId());
                    list.add(cp);
                }
            }
            commonStatisticalQueryParam.setList(list);
        }
    }

    @Override
    public List<ThdDataTdVO> getDeviceTrendData(String devId, String lineId,String groupId) {
        List<ThdDataTdVO> data = new ArrayList();
        List<Overlimit> overlimits = overLimitWlMapper.selectBatchIds(Arrays.asList(lineId));
        List<CsLinePO> finalCsLinePOList = csLineFeignClient.queryLineById(Arrays.asList(lineId)).getData();
        List<CsEquipmentDeliveryDTO> data1 = equipmentFeignClient.queryDeviceById(Stream.of(devId).collect(Collectors.toList())).getData();
        //便携式设备-稳态指标-实时数据-指标
        CsStatisticalSetVO csStatisticalSetVO = csStatisticalSetFeignClient.queryStatistical(DataParam.portableDevStatisticaTrendlId).getData();
        csStatisticalSetVO.getSelectedList().forEach(css->{
            if(groupId != null && !groupId.equals(css.getDataType())){

            }else{
                ThdDataTdVO thdDataTdVO = new ThdDataTdVO();
                thdDataTdVO.setId(css.getDataType());
                thdDataTdVO.setGroupName(css.getDataTypeName());
                List<Map<String,Object>> thdDataVOS = new ArrayList<>();
                List<ThdDataTdVO.ThdDataTdVOData> thdDataTdVODatas = new ArrayList<>();
                for(EleEpdPqd epd : css.getEleEpdPqdVOS()){
                    if(epd.getHarmStart() != null && epd.getHarmEnd() != null){
                        Map<String,Object> map = new HashMap<>();
                        List<ThdDataVO> result = new ArrayList();
                        List<EleEpdPqd> eleEpdPqds = new ArrayList<>();
                        eleEpdPqds.add(epd);
                        eleEpdPqds.forEach(epdPqd->{
                            for (int i = epdPqd.getHarmStart().intValue(); i < epdPqd.getHarmEnd().intValue(); i++) {
                                String index = i+"";
                                List<CommonQueryParam> commonQueryParams = finalCsLinePOList.stream().map(temp -> {
                                    CommonQueryParam commonQueryParam = new CommonQueryParam();
                                    commonQueryParam.setLineId(temp.getLineId());
                                    commonQueryParam.setTableName(influxDbParamUtil.getTableNameByClassId(epdPqd.getClassId()));
                                    commonQueryParam.setColumnName(epdPqd.getName()+"_"+index);
                                    commonQueryParam.setPhasic(epdPqd.getPhase());
                                    commonQueryParam.setDataType(DataParam.portableDevStatisticalMethods);
                                    commonQueryParam.setProcess(data1.get(0).getProcess()+"");
                                    commonQueryParam.setClDid(influxDbParamUtil.getClDidByLineId(temp.getLineId()));
                                    return commonQueryParam;
                                }).collect(Collectors.toList());
                                List<StatisticalDataDTO> deviceRtData = commonService.getDeviceRtData(commonQueryParams);
                                List<ThdDataVO> collect1 = deviceRtData.stream().map(temp -> {
                                    ThdDataVO vo = new ThdDataVO();
                                    vo.setLineId(temp.getLineId());
                                    vo.setPhase(Objects.equals("T",temp.getPhaseType())?null:temp.getPhaseType());
                                    String position = finalCsLinePOList.stream().filter(csLinePO -> Objects.equals(csLinePO.getLineId(), vo.getLineId())).collect(Collectors.toList()).get(0).getPosition();
                                    vo.setPosition(position);
                                    vo.setTime(temp.getTime());
                                    vo.setStatMethod(temp.getValueType());
                                    vo.setStatisticalData(Double.valueOf(df.format(temp.getValue())));
                                    vo.setStatisticalIndex(epdPqd.getId());
                                    vo.setUnit(epdPqd.getUnit());
                                    vo.setStatisticalName(epdPqd.getName());
                                    vo.setAnotherName(epdPqd.getShowName());
                                    vo.setFrequency(index);
                                    return vo;
                                }).collect(Collectors.toList());
                                result.addAll(collect1);
                            }
                        });

                        map.put(DataParam.dataStr,result);
                        map.put(DataParam.nameStr,epd.getPhase()+epd.getShowName());
                        map.put(DataParam.phaseStr,epd.getPhase());
                        thdDataVOS.add(map);

                        for(ThdDataVO thdDataVO : result){
                            ThdDataTdVO.ThdDataTdVOData thdDataTdVOData = new ThdDataTdVO.ThdDataTdVOData();
                            BeanUtils.copyProperties(thdDataVO,thdDataTdVOData);
                            if(!overlimits.isEmpty()){
                                thdDataTdVOData.setInternationalValue(getOverlimitsByGroup(overlimits.get(0).getClass(),css.getDataType(),thdDataVO.getFrequency(),overlimits.get(0)));
                            }
                            thdDataTdVODatas.add(thdDataTdVOData);
                        }
                    }
                }
                thdDataTdVO.setThdDataVOS(thdDataVOS);
                thdDataTdVO.setThdDataTdVODatas(thdDataTdVODatas);
                data.add(thdDataTdVO);
            }
        });
        return data;
    }

    //根据指标分组获取对应的国标幅值
    private Object getOverlimitsByGroup(Class clazz,String groupId,String frequency,Overlimit overlimit){
        try {
            String name = DataParam.overlimitsGroup.get(groupId);
            if(name == null){
                return null;
            }
            Field field = clazz.getDeclaredField(name+frequency);
            field.setAccessible(true);
            return field.get(overlimit);
        } catch (Exception e) {
            return null;
        }
    }

    @Override
    public List<ThdDataTdVO> getDeviceTrendDataGroup() {
        List<ThdDataTdVO> data = new ArrayList();
        //便携式设备-稳态指标-实时数据-指标
        CsStatisticalSetVO csStatisticalSetVO = csStatisticalSetFeignClient.queryStatistical(DataParam.portableDevStatisticaTrendlId).getData();
        csStatisticalSetVO.getSelectedList().forEach(css->{
            ThdDataTdVO thdDataTdVO = new ThdDataTdVO();
            thdDataTdVO.setId(css.getDataType());
            thdDataTdVO.setGroupName(css.getDataTypeName());
            data.add(thdDataTdVO);
        });
        return data;
    }

    @Override
    public List<ThdDataTdVO.ThdDataSpectrumVOData> getDeviceHarmonicSpectrumData(CommonStatisticalQueryParam commonStatisticalQueryParam) {
        formatQueryParamList(commonStatisticalQueryParam);
        List<ThdDataTdVO.ThdDataSpectrumVOData> thdDataSpectrumVODatas = new ArrayList<>();
        List<CsEquipmentDeliveryDTO> data1 = equipmentFeignClient.queryDeviceById(Stream.of(commonStatisticalQueryParam.getDevId()).collect(Collectors.toList())).getData();
        List<CsLinePO> finalCsLinePOList = csLineFeignClient.queryLineById(Arrays.asList(commonStatisticalQueryParam.getLineId())).getData();
        if(commonStatisticalQueryParam.getList() != null && commonStatisticalQueryParam.getList().size() > 0){
            for (CommonStatisticalQueryParam param : commonStatisticalQueryParam.getList()){
                List<EleEpdPqd> eleEpdPqds = csStatisticalSetFeignClient.queryStatisticalSelect(Collections.singletonList(param.getStatisticalId())).getData();
                ThdDataTdVO.ThdDataSpectrumVOData thdDataSpectrumVOData = new ThdDataTdVO.ThdDataSpectrumVOData();
                List<ThdDataVO> result = new ArrayList();
                eleEpdPqds.forEach(epdPqd->{
                    if(epdPqd.getHarmStart() != null && epdPqd.getHarmEnd() != null){
                        thdDataSpectrumVOData.setShowName(getShowName(param.getStatisticalId()));
                        for (int i = epdPqd.getHarmStart().intValue(); i < epdPqd.getHarmEnd().intValue(); i++) {
                            String index = i+"";
                            List<CommonQueryParam> commonQueryParams = finalCsLinePOList.stream().map(temp -> {
                                CommonQueryParam commonQueryParam = new CommonQueryParam();
                                commonQueryParam.setLineId(temp.getLineId());
                                commonQueryParam.setTableName(influxDbParamUtil.getTableNameByClassId(epdPqd.getClassId()));
                                commonQueryParam.setColumnName(epdPqd.getName()+"_"+index);
                                commonQueryParam.setPhasic(epdPqd.getPhase());
                                commonQueryParam.setDataType(DataParam.portableDevStatisticalMethods);
                                commonQueryParam.setProcess(data1.get(0).getProcess()+"");
                                commonQueryParam.setClDid(influxDbParamUtil.getClDidByLineId(temp.getLineId()));
                                return commonQueryParam;
                            }).collect(Collectors.toList());
                            List<StatisticalDataDTO> deviceRtData = commonService.getDeviceRtData(commonQueryParams);
                            List<ThdDataVO> collect1 = deviceRtData.stream().map(temp -> {
                                ThdDataVO vo = new ThdDataVO();
                                vo.setLineId(temp.getLineId());
                                vo.setPhase(Objects.equals("T",temp.getPhaseType())?null:temp.getPhaseType());
                                String position = finalCsLinePOList.stream().filter(csLinePO -> Objects.equals(csLinePO.getLineId(), vo.getLineId())).collect(Collectors.toList()).get(0).getPosition();
                                vo.setPosition(position);
                                vo.setTime(temp.getTime());
                                vo.setStatMethod(temp.getValueType());
                                vo.setStatisticalData(Double.valueOf(df.format(temp.getValue())));
                                vo.setStatisticalIndex(epdPqd.getId());
                                vo.setUnit(epdPqd.getUnit());
                                vo.setStatisticalName(epdPqd.getName());
                                vo.setAnotherName(epdPqd.getShowName());
                                vo.setFrequency(index);
                                return vo;
                            }).collect(Collectors.toList());
                            result.addAll(collect1);
                        }
                    }
                });
                thdDataSpectrumVOData.setThdDataVOS(result);
                thdDataSpectrumVODatas.add(thdDataSpectrumVOData);
            }
        }
        return thdDataSpectrumVODatas;
    }

    private String getShowName(String statisticalId){
        CsStatisticalSetVO csStatisticalSetVO = csStatisticalSetFeignClient.queryStatistical(DataParam.portableDevStatisticaTrendlId).getData();
        for(EleEpdPqdListVO eleEpdPqdListVO : csStatisticalSetVO.getSelectedList()){
            if(statisticalId.equals(eleEpdPqdListVO.getDataType())){
                return eleEpdPqdListVO.getDataTypeName();
            }
        }
        csStatisticalSetVO = csStatisticalSetFeignClient.queryStatistical(DataParam.portableDevStatisticalId).getData();
        for(EleEpdPqdListVO eleEpdPqdListVO : csStatisticalSetVO.getSelectedList()){
            if(statisticalId.equals(eleEpdPqdListVO.getDataType())){
                return eleEpdPqdListVO.getDataTypeName();
            }
        }
        return null;
    }

    @Override
    public List<List<EleEpdPqd>> getGroupPortableStatistical() {
        List<List<EleEpdPqd>> data = new ArrayList<>();
        CsStatisticalSetVO csStatisticalSetVO = csStatisticalSetFeignClient.queryStatistical(DataParam.portableDevStatisticalId).getData();
        List<EleEpdPqd> eleEpdPqds = new ArrayList<>();
        csStatisticalSetVO.getSelectedList().forEach(css->{
            for(EleEpdPqd epdPqd : css.getEleEpdPqdVOS()){
                eleEpdPqds.add(epdPqd);
            }
        });
        Map<String,List<EleEpdPqd>> map = eleEpdPqds.stream().collect(Collectors.groupingBy(EleEpdPqd::getName,LinkedHashMap::new,Collectors.toList()));
        map.forEach((k,v)->{
            data.add(v);
        });
        return data;
    }

    @Override
    public void deleteGroup(String groupId) {
        LambdaQueryWrapper<CsGroArr> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(CsGroArr::getGroupId,groupId);
        List<CsGroArr> list = csGroArrMapper.selectList(lambdaQueryWrapper);
        if (CollectionUtil.isNotEmpty(list)){
            throw new BusinessException(AlgorithmResponseEnum.DATA_EXIST);
        } else {
            LambdaQueryWrapper<CsGroup> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(CsGroup::getId,groupId);
            this.baseMapper.delete(wrapper);
        }
    }

    @Override
    public List<ThdDataVO> trendData(TrendDataQueryParam trendDataQueryParam) {
        List<ThdDataVO> result = new ArrayList<>();
        CsLinePO finalCsLinePO = csLineFeignClient.getById(trendDataQueryParam.getLineId()).getData();
        CsDataSet csDataSet = csDataSetMapper.selectOne(new LambdaQueryWrapper<CsDataSet>().eq(CsDataSet::getId,finalCsLinePO.getDataSetId()));
        if(Objects.isNull(csDataSet) || StrUtil.isBlank(csDataSet.getDataLevel())) {
            throw new BusinessException("当前测点数据集主要信息缺失,请联系管理员排查(测点表里面数据集id缺失)");
        }
        Double ct = finalCsLinePO.getCtRatio() / (Objects.isNull(finalCsLinePO.getCt2Ratio())?1.0:finalCsLinePO.getCt2Ratio());
        Double pt = finalCsLinePO.getPtRatio() / (Objects.isNull(finalCsLinePO.getPt2Ratio())?1.0:finalCsLinePO.getPt2Ratio());
        if(CollectionUtil.isNotEmpty(trendDataQueryParam.getList())) {
            for (TrendDataQueryParam param : trendDataQueryParam.getList()) {
                List<EleEpdPqd> eleEpdPqds = csStatisticalSetFeignClient.queryStatisticalSelect(Collections.singletonList(param.getStatisticalId())).getData();
                for (EleEpdPqd epdPqd : eleEpdPqds) {
                    CommonQueryParam commonQueryParam = new CommonQueryParam();
                    commonQueryParam.setLineId(finalCsLinePO.getLineId());
                    commonQueryParam.setTableName(influxDbParamUtil.getTableNameByClassId(epdPqd.getClassId()));
                    if (epdPqd.getName() == null || epdPqd.getName().isEmpty()) {
                        commonQueryParam.setColumnName(epdPqd.getName()+ (StringUtils.isEmpty(param.getFrequency()) ? "":"_"+param.getFrequency()));
                    } else {
                        commonQueryParam.setColumnName(epdPqd.getOtherName()+ (StringUtils.isEmpty(param.getFrequency()) ? "":"_"+param.getFrequency()));
                    }
                    commonQueryParam.setPhasic(epdPqd.getPhase());

                    commonQueryParam.setStartTime(DateUtil.format(DateUtil.parse(trendDataQueryParam.getSearchBeginTime(), DatePattern.NORM_DATE_PATTERN), DatePattern.NORM_DATETIME_PATTERN));
                    commonQueryParam.setEndTime(DateUtil.format(DateUtil.endOfDay(DateUtil.parse(trendDataQueryParam.getSearchEndTime(), DatePattern.NORM_DATE_PATTERN)), DatePattern.NORM_DATETIME_PATTERN));
                    commonQueryParam.setDataType(trendDataQueryParam.getValueType().toUpperCase());
                    commonQueryParam.setClDid(influxDbParamUtil.getClDidByLineId(finalCsLinePO.getLineId()));

                    List<StatisticalDataDTO> deviceRtData = commonService.getNewDeviceRtDataByTime(Collections.singletonList(commonQueryParam));
                    List<ThdDataVO> collect1 = deviceRtData.stream().map(temp -> {
                        String unit;
                        ThdDataVO vo = new ThdDataVO();
                        vo.setLineId(temp.getLineId());
                        vo.setPhase(Objects.equals("T", temp.getPhaseType()) ? null : temp.getPhaseType());
                        String position = finalCsLinePO.getPosition();
                        vo.setPosition(position);
                        vo.setTime(temp.getTime());
                        vo.setStatMethod(temp.getValueType());
                        vo.setStatisticalData(Double.valueOf(df.format(temp.getValue())));
                        if (temp.getValue() != null) {
                            double re = 0;
                            if (Objects.equals("Primary", trendDataQueryParam.getDataLevel())) {
                                if (Objects.equals("Primary", csDataSet.getDataLevel())) {
                                    if (HarmonicConstant.POWER_LIST.contains(epdPqd.getShowName())) {
                                        re = Objects.isNull(temp.getValue()) ? 3.14159 : Double.parseDouble(df.format(temp.getValue() / 1000));
                                        vo.setStatisticalData(re);
                                        unit = "k" + epdPqd.getUnit();
                                    } else {
                                        vo.setStatisticalData(Objects.isNull(temp.getValue()) ? 3.14159 : Double.parseDouble(df.format(temp.getValue())));
                                        unit = epdPqd.getUnit();
                                    }
                                } else {
                                    if (Objects.nonNull(epdPqd.getPrimaryFormula())) {
                                        switch (epdPqd.getPrimaryFormula()) {
                                            case "*PT":
                                                re = temp.getValue() * pt / 1000;
                                                unit = "k" + epdPqd.getUnit();
                                                break;
                                            case "*CT":
                                                re = temp.getValue() * ct;
                                                unit = epdPqd.getUnit();
                                                break;
                                            case "*PT*CT":
                                                re = temp.getValue() * pt * ct / 1000;
                                                unit = "k" + epdPqd.getUnit();
                                                break;
                                            default:
                                                re = temp.getValue();
                                                unit = epdPqd.getUnit();
                                                break;
                                        }
                                        vo.setStatisticalData(Double.valueOf(df.format(re)));
                                    } else {
                                        re = temp.getValue();
                                        unit = epdPqd.getUnit();
                                        vo.setStatisticalData(Double.valueOf(df.format(re)));
                                    }

                                }
                            } else {
                                if (Objects.equals("Primary", csDataSet.getDataLevel())) {
                                    if (Objects.nonNull(epdPqd.getPrimaryFormula())) {
                                        switch (epdPqd.getPrimaryFormula()) {
                                            case "*PT":
                                                re = temp.getValue() / pt;
                                                break;
                                            case "*CT":
                                                re = temp.getValue() / ct;
                                                break;
                                            case "*PT*CT":
                                                re = temp.getValue() / pt / ct;
                                                break;
                                            default:
                                                re = temp.getValue();
                                                break;
                                        }
                                        vo.setStatisticalData(Double.valueOf(df.format(re)));
                                    } else {
                                        re = temp.getValue();
                                        vo.setStatisticalData(Double.valueOf(df.format(re)));
                                    }
                                } else {
                                    vo.setStatisticalData(Double.valueOf(df.format(temp.getValue())));
                                }
                                unit = epdPqd.getUnit();
                            }
                        } else {
                            vo.setStatisticalData(null);
                            if (Objects.equals("Primary", trendDataQueryParam.getDataLevel())) {
                                if (Objects.equals("Primary", csDataSet.getDataLevel())) {
                                    unit = epdPqd.getUnit();
                                } else {
                                    if (Objects.nonNull(epdPqd.getPrimaryFormula())) {
                                        switch (epdPqd.getPrimaryFormula()) {
                                            case "*PT":
                                                unit = "k" + epdPqd.getUnit();
                                                break;
                                            case "*CT":
                                                unit = epdPqd.getUnit();
                                                break;
                                            case "*PT*CT":
                                                unit = "k" + epdPqd.getUnit();
                                                break;
                                            default:
                                                unit = epdPqd.getUnit();
                                                break;
                                        }
                                    } else {
                                        unit = epdPqd.getUnit();
                                    }
                                }
                            } else {
                                unit = epdPqd.getUnit();
                            }
                        }
                        vo.setUnit(unit);
                        vo.setStatisticalIndex(epdPqd.getId());
                        vo.setStatisticalName(epdPqd.getName());
                        vo.setAnotherName(epdPqd.getShowName());
                        return vo;
                    }).collect(Collectors.toList());
                    result.addAll(collect1);
                }
            }
        }
        return result;
    }

    @Override
    public List<ThdDataVO> fittingData(FittingDataQueryParam fittingDataQueryParam) {
        List<ThdDataVO> result = new ArrayList<>();
        CsLinePO finalCsLinePO = csLineFeignClient.getById(fittingDataQueryParam.getLineId()).getData();
        CsDataSet csDataSet = csDataSetMapper.selectOne(new LambdaQueryWrapper<CsDataSet>().eq(CsDataSet::getId,finalCsLinePO.getDataSetId()));
        if(Objects.isNull(csDataSet) || StrUtil.isBlank(csDataSet.getDataLevel())){
            throw new BusinessException("当前测点数据集主要信息缺失，请联系管理员排查(测点表里面数据集id缺失)");
        }
        Double ct = finalCsLinePO.getCtRatio() / (Objects.isNull(finalCsLinePO.getCt2Ratio())?1.0:finalCsLinePO.getCt2Ratio());
        Double pt = finalCsLinePO.getPtRatio() / (Objects.isNull(finalCsLinePO.getPt2Ratio())?1.0:finalCsLinePO.getPt2Ratio());

        // String position = finalCsLinePO.getPosition();
        Overlimit overlimit = overLimitWlMapper.selectById(finalCsLinePO.getLineId());
        if (Objects.isNull(overlimit)) {
            throw new BusinessException("当前测点限值信息缺失，请联系管理员排查");
        }
        JSONObject entries = JSONUtil.parseObj(overlimit, new JSONConfig().setIgnoreNullValue(false));
        if(CollectionUtil.isNotEmpty(fittingDataQueryParam.getList())) {
            for (FittingDataQueryParam param : fittingDataQueryParam.getList()) {
                String dictCode = dictTreeFeignClient.queryById(param.getStatisticalId()).getData().getCode();
                List<EleEpdPqd> eleEpdPqds = csStatisticalSetFeignClient.queryStatisticalSelect(Collections.singletonList(param.getStatisticalId())).getData();
                List<ThdDataVO> dataList = new ArrayList<>();
                for (EleEpdPqd epdPqd : eleEpdPqds) {
                    CommonQueryParam commonQueryParam = new CommonQueryParam();
                    commonQueryParam.setLineId(finalCsLinePO.getLineId());
                    commonQueryParam.setTableName(influxDbParamUtil.getTableNameByClassId(epdPqd.getClassId()));
                    commonQueryParam.setColumnName(epdPqd.getOtherName() + (StringUtils.isEmpty(param.getFrequency()) ? "" : "_" + param.getFrequency()));
                    commonQueryParam.setPhasic(epdPqd.getPhase());

                    commonQueryParam.setStartTime(DateUtil.format(DateUtil.parse(fittingDataQueryParam.getSearchBeginTime(), DatePattern.NORM_DATE_PATTERN), DatePattern.NORM_DATETIME_PATTERN));
                    commonQueryParam.setEndTime(DateUtil.format(DateUtil.endOfDay(DateUtil.parse(fittingDataQueryParam.getSearchEndTime(), DatePattern.NORM_DATE_PATTERN)), DatePattern.NORM_DATETIME_PATTERN));
                    // 兼容用户功率需要该参数过滤
                    String dataType = param.getValueType();
                    if (StrUtil.isEmpty(dataType)) {
                        // 电能质量指标，取限值计算类型，判断是否越限
                        dataType = epdPqd.getFormula().toUpperCase();
                    } else {
                        dataType = dataType.toUpperCase();
                    }
                    commonQueryParam.setDataType(dataType);

                    commonQueryParam.setClDid(influxDbParamUtil.getClDidByLineId(finalCsLinePO.getLineId()));

                    List<StatisticalDataDTO> deviceRtData = commonService.getNewDeviceRtDataByTime(Collections.singletonList(commonQueryParam));
                    dataList = deviceRtData.stream().map(temp -> {
                        String unit;
                        ThdDataVO vo = new ThdDataVO();
                        vo.setLineId(temp.getLineId());
                       // vo.setLineName(finalCsLinePO.getName());
                        vo.setPhase(Objects.equals("T", temp.getPhaseType()) ? null : temp.getPhaseType());
                       // vo.setPosition(position);
                        vo.setTime(temp.getTime());
                        vo.setStatMethod(commonQueryParam.getDataType());
                        vo.setStatisticalData(Double.valueOf(df.format(temp.getValue())));
                        if (temp.getValue() != null) {
                            double re;
                            if (Objects.equals("Primary", fittingDataQueryParam.getDataLevel())) {
                                if (Objects.equals("Primary", csDataSet.getDataLevel())) {
                                    if (HarmonicConstant.POWER_LIST.contains(epdPqd.getShowName())) {
                                        re = Objects.isNull(temp.getValue()) ? 3.14159 : Double.parseDouble(df.format(temp.getValue() / 1000));
                                        vo.setStatisticalData(re);
                                        unit = "k" + epdPqd.getUnit();
                                    } else {
                                        vo.setStatisticalData(Objects.isNull(temp.getValue()) ? 3.14159 : Double.parseDouble(df.format(temp.getValue())));
                                        unit = epdPqd.getUnit();
                                    }
                                } else {
                                    if (Objects.nonNull(epdPqd.getPrimaryFormula())) {
                                        switch (epdPqd.getPrimaryFormula()) {
                                            case "*PT":
                                                re = temp.getValue() * pt / 1000;
                                                unit = "k" + epdPqd.getUnit();
                                                break;
                                            case "*CT":
                                                re = temp.getValue() * ct;
                                                unit = epdPqd.getUnit();
                                                break;
                                            case "*PT*CT":
                                                re = temp.getValue() * pt * ct / 1000;
                                                unit = "k" + epdPqd.getUnit();
                                                break;
                                            default:
                                                re = temp.getValue();
                                                unit = epdPqd.getUnit();
                                                break;
                                        }
                                        vo.setStatisticalData(Double.valueOf(df.format(re)));
                                    } else {
                                        re = temp.getValue();
                                        unit = epdPqd.getUnit();
                                        vo.setStatisticalData(Double.valueOf(df.format(re)));
                                    }

                                }
                            } else {
                                if (Objects.equals("Primary", csDataSet.getDataLevel())) {
                                    if (Objects.nonNull(epdPqd.getPrimaryFormula())) {
                                        switch (epdPqd.getPrimaryFormula()) {
                                            case "*PT":
                                                re = temp.getValue() / pt;
                                                break;
                                            case "*CT":
                                                re = temp.getValue() / ct;
                                                break;
                                            case "*PT*CT":
                                                re = temp.getValue() / pt / ct;
                                                break;
                                            default:
                                                re = temp.getValue();
                                                break;
                                        }
                                        vo.setStatisticalData(Double.valueOf(df.format(re)));
                                    } else {
                                        re = temp.getValue();
                                        vo.setStatisticalData(Double.valueOf(df.format(re)));
                                    }
                                } else {
                                    vo.setStatisticalData(Double.valueOf(df.format(temp.getValue())));
                                }
                                unit = epdPqd.getUnit();
                            }
                        } else {
                            vo.setStatisticalData(null);
                            if (Objects.equals("Primary", fittingDataQueryParam.getDataLevel())) {
                                if (Objects.equals("Primary", csDataSet.getDataLevel())) {
                                    unit = epdPqd.getUnit();
                                } else {
                                    if (Objects.nonNull(epdPqd.getPrimaryFormula())) {
                                        switch (epdPqd.getPrimaryFormula()) {
                                            case "*PT":
                                                unit = "k" + epdPqd.getUnit();
                                                break;
                                            case "*CT":
                                                unit = epdPqd.getUnit();
                                                break;
                                            case "*PT*CT":
                                                unit = "k" + epdPqd.getUnit();
                                                break;
                                            default:
                                                unit = epdPqd.getUnit();
                                                break;
                                        }
                                    } else {
                                        unit = epdPqd.getUnit();
                                    }
                                }
                            } else {
                                unit = epdPqd.getUnit();
                            }
                        }
                        vo.setUnit(unit);
                       // vo.setStatisticalIndex(epdPqd.getId());
                       // vo.setStatisticalName(epdPqd.getName());
                        vo.setStatisticalIndex(param.getStatisticalId());
                        vo.setAnotherName(epdPqd.getShowName());
                        return vo;
                    }).collect(Collectors.toList());
                }
                // 电能质量指标（越限为1，不越限为0）
                List<String> hasKeys = entries.keySet().stream().filter(key -> key.startsWith(dictCode)).collect(Collectors.toList());
                if (CollUtil.isNotEmpty(hasKeys)) {
                    List<ThdDataVO> limitDataList = new ArrayList<>();
                    Map<Instant, List<ThdDataVO>> timeMap = dataList.stream().collect(Collectors.groupingBy(ThdDataVO::getTime));
                    // 限值
                    ThdDataVO data;
                    for (Map.Entry<Instant, List<ThdDataVO>> entry: timeMap.entrySet()) {
                        data = new ThdDataVO();
                        List<ThdDataVO> list = entry.getValue();
                        if (CollUtil.isNotEmpty(list)) {
                            ThdDataVO thdDataVO = list.get(0);
                            //  data.setPosition(thdDataVO.getPosition());
                            data.setLineId(thdDataVO.getLineId());
                            //  data.setLineName(thdDataVO.getLineName());
                            data.setFrequency(param.getFrequency());
                            data.setStatMethod(thdDataVO.getStatMethod());
                            data.setUnit(thdDataVO.getUnit());
                            data.setAnotherName(thdDataVO.getAnotherName());
                            data.setStatisticalIndex(param.getStatisticalId());
                        }
                        Instant time = entry.getKey();
                        data.setTime(time);

                        double limitValue = entries.getDouble(dictCode + (StringUtils.isEmpty(param.getFrequency()) ? "" : param.getFrequency()));
                        double maxValue = list.stream().filter(v -> ObjectUtil.isNotEmpty(v.getStatisticalData())).mapToDouble(ThdDataVO::getStatisticalData).max().orElse(0.0);
                        // 越限为1，不越限为0
                        data.setStatisticalData(maxValue > limitValue ? 1.0 : 0.0);
                        limitDataList.add(data);
                    }
                    limitDataList.sort(Comparator.comparing(ThdDataVO::getTime));
                    result.addAll(limitDataList);
                } else {
                    result.addAll(dataList);
                }

            }
        }
        return result;
    }

    @Override
    public Map<String, List<ThdDataVO>> sensitiveUserTrendData(SensitiveUserTrendDataQueryParam param) {
        Map<String, List<ThdDataVO>> result = new HashMap<>();
        if (Objects.isNull(param.getSensitiveUserId())) {
            return result;
        }
        result.put("before", new ArrayList<>());
        result.put("after", new ArrayList<>());
        PqGovernPlan plan = pqGovernPlanFeignClient.getById(param.getSensitiveUserId()).getData();
        if (Objects.isNull(plan)) {
            return result;
        }
        TrendDataQueryParam trendDataQueryParam = new TrendDataQueryParam();
        trendDataQueryParam.setSearchBeginTime(param.getSearchBeginTime());
        trendDataQueryParam.setSearchEndTime(param.getSearchEndTime());
        trendDataQueryParam.setValueType(param.getValueType().toUpperCase());
        trendDataQueryParam.setDataLevel(param.getDataLevel());
        List<SensitiveUserTrendDataQueryParam> paramList = param.getList();
        List<TrendDataQueryParam> indexList = paramList.stream().map(item -> {
            TrendDataQueryParam queryParam = new TrendDataQueryParam();
            if (ObjectUtil.isNotNull(param.getHarmonicCount())) {
                queryParam.setFrequency(String.valueOf(param.getHarmonicCount()));
            }
            queryParam.setStatisticalId(item.getStatisticalId());
            return queryParam;
        }).collect(Collectors.toList());
        trendDataQueryParam.setList(indexList);
        //治理前
        trendDataQueryParam.setLineId(plan.getGovernBefore());
        List<ThdDataVO> thdDataList1 = this.trendData(trendDataQueryParam);
        result.put("before", thdDataList1);
        //治理后
        trendDataQueryParam.setLineId(plan.getGovernAfter());
        List<ThdDataVO> thdDataList2 = this.trendData(trendDataQueryParam);
        result.put("after", thdDataList2);
        return result;
    }

    private List<EnergyTemplateVO> getChildren(String tabId, List<EnergyTemplateVO> all) {
        return all.stream().filter(item -> item.getPid().equals(tabId)).collect(Collectors.toList());
    }

    private List<CsGroupVO> getChildrenes(String tabId, List<CsGroupVO> all) {
        return all.stream().filter(item -> item.getPid().equals(tabId)).collect(Collectors.toList());
    }
    //如果未做分组，则先分组
    public List<CsGroupVO> insertGroupData(String dataSet) {
        AtomicReference<Integer> sort = new AtomicReference<>(0);
        List<CsGroup> ls = new ArrayList<>();
        List<CsGroupVO> result = new ArrayList<>();
        List<CsGroArr> groArrList = new ArrayList<>();
        //取平均值
        List<CsDataArray> arrayList = csDataArrayService.getGroupData(dataSet);
        Map<String,List<CsDataArray>> map = arrayList.stream().collect(Collectors.groupingBy(CsDataArray::getAnotherName,LinkedHashMap::new,Collectors.toList()));
        map.forEach((k,v)->{
            //录入组数据
            String groupId = IdUtil.simpleUUID();
            CsGroup csGroup = new CsGroup();
            csGroup.setId(groupId);
            csGroup.setDataSetId(dataSet);
            csGroup.setGroupName(k);
            csGroup.setSort(sort.getAndSet(sort.get() + 1));
            csGroup.setIsShow(1);
            ls.add(csGroup);
            //录入组和指标关系
            v.forEach(item->{
                CsGroArr csGroArr = new CsGroArr();
                csGroArr.setGroupId(groupId);
                csGroArr.setArrayId(item.getId());
                groArrList.add(csGroArr);
            });
            //展示组和指标关系
            List<CsGroupVO> vo2 = new ArrayList<>();
            CsGroupVO csGroupVo = new CsGroupVO();
            csGroupVo.setId(groupId);
            csGroupVo.setPid("0");
            csGroupVo.setName(k);
            csGroupVo.setIsShow(1);
            v.forEach(item->{
                CsGroupVO csGroupVo2 = new CsGroupVO();
                csGroupVo2.setId(item.getDataId());
                csGroupVo2.setPid(groupId);
                if(Objects.equals(item.getPhase(),"M") || Objects.equals(item.getPhase(),"T") ) {
                    csGroupVo2.setName(item.getAnotherName());
                } else {
                    csGroupVo2.setName(item.getPhase() + "相" +item.getAnotherName());
                }
                vo2.add(csGroupVo2);
            });
            csGroupVo.setChildren(vo2);
            result.add(csGroupVo);
        });
        csGroArrMapper.insertList(groArrList);
        this.saveBatch(ls,1000);
        return result;
    }

    //单位处理
    public void getUnit(List<EnergyTemplateVO> energyTemplates, List<EleEpdPqd> eleEpdPqds, List<DataGroupTemplateVO> dataGroupTemplates, String type) {
        // 使用Map来存储EleEpdPqd的ID和Unit，以便快速查找
        Map<String, String> unitMap = new HashMap<>();
        for (EleEpdPqd item : eleEpdPqds) {
            unitMap.put(item.getId(), item.getUnit());
        }

        // 遍历EnergyTemplateVO，设置Unit
        for (EnergyTemplateVO energyTemplate : energyTemplates) {
            String unit = unitMap.get(energyTemplate.getDataId());
            if (unit != null) {
                energyTemplate.setUnit(unit);
            }
        }

        // 使用Map来存储DataGroupTemplateVO的ID和对应的EnergyTemplateVO（如果存在）
        Map<String, EnergyTemplateVO> energyTemplateMap = new HashMap<>();
        for (EnergyTemplateVO energyTemplate : energyTemplates) {
            energyTemplateMap.put(energyTemplate.getPid(), energyTemplate);
        }

        // 遍历DataGroupTemplateVO，更新Name
        for (DataGroupTemplateVO dataGroupTemplate : dataGroupTemplates) {
            EnergyTemplateVO energyTemplate = energyTemplateMap.get(dataGroupTemplate.getId());
            if (energyTemplate != null && energyTemplate.getUnit() != null) {
                if (changePower(dataGroupTemplate.getName()) && Objects.equals("Primary",type)) {
                    dataGroupTemplate.setName(dataGroupTemplate.getName() + "(k" + energyTemplate.getUnit() + ")");
                } else {
                    dataGroupTemplate.setName(dataGroupTemplate.getName() + "(" + energyTemplate.getUnit() + ")");
                }
            }
            dataGroupTemplate.setName(dataGroupTemplate.getName().replace("序列",""));;
        }
    }

    //判断指标是否需要转换
    public boolean changePower(String name) {
        if(name.contains("相角")) {
            return false;
        }
        return HarmonicConstant.POWER_LIST.stream()
                .anyMatch(name::contains);
    }

}
