package com.njcn.harmonic.service.majornetwork.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.njcn.common.pojo.param.StatisticsBizBaseParam;
import com.njcn.harmonic.mapper.majornetwork.RStatHarmonicDMapper;
import com.njcn.harmonic.mapper.majornetwork.RStatHarmonicMMapper;
import com.njcn.harmonic.mapper.majornetwork.RStatHarmonicVoltageMMapper;
import com.njcn.harmonic.pojo.param.RStatHarmonicMParam;
import com.njcn.harmonic.pojo.param.StatSubstationBizBaseParam;
import com.njcn.harmonic.pojo.po.RStatHarmonicD;
import com.njcn.harmonic.pojo.po.RStatHarmonicM;
import com.njcn.harmonic.pojo.po.RStatHarmonicVoltageM;
import com.njcn.harmonic.pojo.vo.RArrayVO;
import com.njcn.harmonic.pojo.vo.RHarmonicPolylineVO;
import com.njcn.harmonic.pojo.vo.RIconVO;
import com.njcn.harmonic.pojo.vo.RStatHarmonicMVO;
import com.njcn.harmonic.service.majornetwork.RStatHarmonicMService;
import com.njcn.device.pq.utils.PublicDateUtil;
import com.njcn.harmonic.utils.DeptUtil;
import com.njcn.system.api.DicDataFeignClient;
import com.njcn.system.enums.DicDataEnum;
import com.njcn.system.enums.DicDataTypeEnum;
import com.njcn.system.pojo.po.DictData;
import com.njcn.user.api.DeptFeignClient;
import com.njcn.user.pojo.dto.DeptDTO;
import com.njcn.web.utils.WebUtil;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import org.springframework.stereotype.Service;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author rui.wu
 * @since 2022-10-09
 */
@Service
@RequiredArgsConstructor
public class RStatHarmonicMServiceImpl extends ServiceImpl<RStatHarmonicMMapper, RStatHarmonicM> implements RStatHarmonicMService {

    private final RStatHarmonicMMapper rStatHarmonicMMapper;
    private final DicDataFeignClient dicDataFeignClient;
    private final RStatHarmonicVoltageMMapper rStatHarmonicVoltageMMapper;
    private final RStatHarmonicDMapper rStatHarmonicDMapper;
    private final DeptFeignClient deptFeignClient;

    @Override
    public List<RArrayVO> getRStatHarmonicMAll(StatisticsBizBaseParam param) {

        //子节点 获取所有得干扰源类型（监测点类型）
        List<DictData> interferenceSourceTypeData = dicDataFeignClient.getDicDataByTypeCode(
                DicDataTypeEnum.MONITORING_LABELS.getCode()).getData();
        Map<String, DictData> interferenceMap = interferenceSourceTypeData.stream().collect(Collectors.toMap(DictData::getId, Function.identity()));

        //对象主节点 获取所有得指标类型
        List<DictData> lineTypeData = dicDataFeignClient.getDicDataByTypeCode(
                DicDataTypeEnum.STEADY_STATIS.getCode()).getData();
        Map<String, DictData> lineTypeMap = lineTypeData.stream()
                .collect(Collectors.toMap(DictData::getId, Function.identity()));

        //获取主网id信息
        DictData mainnetData = dicDataFeignClient.getDicDataByCode(DicDataEnum.MAINNET_POINT.getCode()).getData();


        //获取当前部门下所有部门信息
        List<DeptDTO> deptList = deptFeignClient.getDeptDescendantIndexes(param.getId(), WebUtil.filterDeptType()).getData();
        List<DeptDTO> deptDTOList = DeptUtil.getDeptSubsetVOList(deptList, param.getId());
        List<String> deptIds = deptDTOList.stream().map(DeptDTO::getCode).collect(Collectors.toList());

        StatSubstationBizBaseParam baseParam = BeanUtil.copyProperties(param, StatSubstationBizBaseParam.class);
        baseParam.setIds(deptIds);
        //数据库查询
        List<RStatHarmonicM> list = rStatHarmonicMMapper.selectInfoList(baseParam, mainnetData.getId());

        //初始化指标类型（横向）
        List<RArrayVO> arrayVOList = new ArrayList<>();
        List<RStatHarmonicMVO> rm = new ArrayList<>();
        for (DictData lineTypeDatum : interferenceSourceTypeData) {
            RStatHarmonicMVO r = new RStatHarmonicMVO();
            r.setHarmonicName(lineTypeDatum.getName());
            r.setSort(lineTypeDatum.getSort());
            r.setOverLimitMeasurementAverage(0.0F);
            r.setOverLimitMeasurementAccrued(0);
            r.setAverageOverDay(0.0F);
            r.setOverDay(0);
            r.setOverLimitMeasurementRatioAverage(0.0F);
            r.setOverLimitMeasurementRatioAccrued(0.0F);
            rm.add(r);
        }
        for (DictData lineTypeDatum : lineTypeData) {
            RArrayVO r = new RArrayVO();
            r.setRowName(lineTypeDatum.getName());
            r.setSort(lineTypeDatum.getSort());
            r.setColumns(rm);
            arrayVOList.add(r);
        }
        //根据稳态指标分组
        Map<String, List<RStatHarmonicM>> MeasurementTypeClassMap = list.stream().collect(Collectors.groupingBy(RStatHarmonicM::getHarmonicType));
        //重新生成数据结构
        MeasurementTypeClassMap.forEach((key, value) -> {
            if (lineTypeMap.containsKey(key)) {
                RArrayVO arrayVO = new RArrayVO();
                DictData data = lineTypeMap.get(key);
                arrayVO.setRowName(data.getName());
                arrayVO.setSort(data.getSort());
                List<RStatHarmonicMVO> b = new ArrayList<>();
                b.addAll(rm);
                for (RStatHarmonicM rStatHarmonicM : value) {
                    if (interferenceMap.containsKey(rStatHarmonicM.getMeasurementTypeClass())) {
                        RStatHarmonicMVO r = BeanUtil.copyProperties(rStatHarmonicM, RStatHarmonicMVO.class);
                        DictData data1 = interferenceMap.get(rStatHarmonicM.getMeasurementTypeClass());
                        r.setHarmonicName(data1.getName());
                        r.setSort(data1.getSort());
                        DecimalFormat df = new DecimalFormat("###.00");
                        if(r.getOverLimitMeasurementAccrued() != 0) {
                            Double aa = r.getOverDay() / (r.getOverLimitMeasurementAccrued() * 1.0);
                            Float averageOverDay = Float.parseFloat(df.format(aa));
                            r.setAverageOverDay(averageOverDay);
                        }else {
                            r.setAverageOverDay(0f);
                        }
                        b.add(r);
                    }

                }
                Map<String, RStatHarmonicMVO> linkedHashMap = new LinkedHashMap<>();
                for (RStatHarmonicMVO harmonicMVO : b) {
                    linkedHashMap.put(harmonicMVO.getHarmonicName(), harmonicMVO);
                }
                List<RStatHarmonicMVO> aa = new ArrayList<>(linkedHashMap.values());
                aa.sort(Comparator.comparing(rStatHarmonicMVO -> rStatHarmonicMVO.getSort()));
                arrayVO.setColumns(aa);
                arrayVOList.add(arrayVO);
            }
        });
        Map<String, RArrayVO> linkedHashMap = new LinkedHashMap<>();
        for (RArrayVO rStatHarmonicMVO : arrayVOList) {
            linkedHashMap.put(rStatHarmonicMVO.getRowName(), rStatHarmonicMVO);
        }
        List<RArrayVO> aa = new ArrayList<>(linkedHashMap.values());
        aa.sort(Comparator.comparing(rArrayVO -> rArrayVO.getSort()));
        return aa;
    }

    @Override
    public List<RIconVO> getRStatHarmonicIconVoltage(RStatHarmonicMParam param) {
        //干扰数据类型（监测对象）
        DictData measurementDate;
        //指标对象类型属性
        DictData harmonicDate;
        //判断是是否传入检测点信息值（电压）
        if (StrUtil.isBlank(param.getStasisID()) && StrUtil.isBlank(param.getMonitorID())) {
            //干扰数据类型（监测对象）
            List<DictData> interferenceSourceTypeData = dicDataFeignClient.getDicDataByTypeCode(
                    DicDataTypeEnum.MONITORING_LABELS.getCode()).getData();
            interferenceSourceTypeData.sort(Comparator.comparing(data -> data.getSort()));
            measurementDate = interferenceSourceTypeData.get(0);
            //指标对象类型
            List<DictData> indicatorTypeDate = dicDataFeignClient.getDicDataByTypeCode(
                    DicDataTypeEnum.STEADY_STATIS.getCode()).getData();
            indicatorTypeDate.sort(Comparator.comparing(data -> data.getSort()));
            harmonicDate = indicatorTypeDate.get(0);
        } else {
            //获取检测点对象（电压）
            measurementDate = dicDataFeignClient.getDicDataById(
                    param.getMonitorID()).getData();
            //获取指标对象（频率偏差）
            harmonicDate = dicDataFeignClient.getDicDataById(
                    param.getStasisID()).getData();
        }
        //反防止参数查询数据报错
        Assert.isTrue(
                ObjectUtil.isNotNull(measurementDate) || ObjectUtil.isNotNull(harmonicDate)
                , "干扰源类型或者指标类型为空,请检查入参是否准确");
        //获取电压字典
        List<DictData> devVoltageData = dicDataFeignClient.getDicDataByTypeCode(
                DicDataTypeEnum.DEV_VOLTAGE.getCode()).getData();
        Map<String, DictData> devVoltageMap = devVoltageData.stream()
                .collect(Collectors.toMap(DictData::getId, Function.identity()));
        //获取主网id信息
        DictData mainnetData = dicDataFeignClient.getDicDataByCode(DicDataEnum.MAINNET_POINT.getCode()).getData();

        //初始化对象
        List<RIconVO> arrayVOList = new ArrayList<>();

        //获取当前部门下所有部门信息
        List<DeptDTO> deptList = deptFeignClient.getDeptDescendantIndexes(param.getId(), WebUtil.filterDeptType()).getData();
        List<DeptDTO> deptDTOList = DeptUtil.getDeptSubsetVOList(deptList, param.getId());
        List<String> deptIds = deptDTOList.stream().map(DeptDTO::getCode).collect(Collectors.toList());

        StatSubstationBizBaseParam baseParam = BeanUtil.copyProperties(param, StatSubstationBizBaseParam.class);
        baseParam.setIds(deptIds);
        //数据库查询
        List<RStatHarmonicVoltageM> rStatHarmonicVoltageMS = rStatHarmonicVoltageMMapper
                .selectInfoList(baseParam, mainnetData.getId(), measurementDate.getId(), harmonicDate.getId());

        //将数据转换为map进行便利
        Map<String, RStatHarmonicVoltageM> voltageMMap = rStatHarmonicVoltageMS.stream()
                .collect(Collectors.toMap(RStatHarmonicVoltageM::getVoltageType, Function.identity()));
        //对象
        if (CollUtil.isNotEmpty(rStatHarmonicVoltageMS)) {
            voltageMMap.forEach((key, value) -> {
                if (devVoltageMap.containsKey(key)) {
                    DictData data = devVoltageMap.get(key);
                    RIconVO rIconVO = new RIconVO();
                    rIconVO.setRowName(data.getName());
                    rIconVO.setSort(data.getSort());
                    rIconVO.setOverLimitMeasurementAccrued(value.getOverLimitMeasurementAccrued());
                    rIconVO.setOverLimitMeasurementAverage(value.getOverLimitMeasurementAverage());
                    rIconVO.setOverLimitMeasurementRatioAccrued(value.getOverLimitMeasurementRatioAccrued());
                    rIconVO.setOverLimitMeasurementRatioAverage(value.getOverLimitMeasurementRatioAverage());
//                    DecimalFormat df = new DecimalFormat("###.00");
//                    Float averageOverDay = Float.parseFloat(
//                            df.format(value.getOverDay() / (value.getOverLimitMeasurementAccrued() * 1.0)));
                    Float averageOverDay = (float)value.getOverDay()/value.getOverLimitMeasurementAccrued();
                    if(Double.isNaN(averageOverDay)){
                        rIconVO.setAverageOverDay(0.0F);
                    }else{
                        rIconVO.setAverageOverDay(Float.parseFloat(String.format("%.2f", averageOverDay)));
                    }
                    arrayVOList.add(rIconVO);
                }
            });
        }
        //处理主节点不存在的集合
        List<DictData> notMeasurementList = devVoltageData.stream().filter(r -> !voltageMMap.containsKey(r.getId()))
                .collect(Collectors.toList());
        for (DictData notData : notMeasurementList) {
            RIconVO iconVO = new RIconVO();
            iconVO.setRowName(notData.getName());
            iconVO.setSort(notData.getSort());
            iconVO.setOverLimitMeasurementAverage(0.0F);
            iconVO.setOverLimitMeasurementAccrued(0);
            iconVO.setOverLimitMeasurementRatioAverage(0f);
            iconVO.setOverLimitMeasurementRatioAccrued(0f);
            iconVO.setAverageOverDay(0f);
            arrayVOList.add(iconVO);
        }
        arrayVOList.sort(Comparator.comparing(rIconVO -> rIconVO.getSort()));
        return arrayVOList;
    }

    @SneakyThrows
    @Override
    public List<RHarmonicPolylineVO> getRStatHarmonicIconDate(RStatHarmonicMParam param) {
        //初始化对象
        List<RHarmonicPolylineVO> iconList = new ArrayList<>();
        DictData measurementDate;
        //指标对象类型属性
        DictData harmonicDate;
        //判断是是否传入检测点信息值（电压）
        if (StrUtil.isBlank(param.getStasisID()) && StrUtil.isBlank(param.getMonitorID())) {
            //干扰数据类型（监测对象）
            List<DictData> interferenceSourceTypeData = dicDataFeignClient.getDicDataByTypeCode(
                    DicDataTypeEnum.MONITORING_LABELS.getCode()).getData();
            interferenceSourceTypeData.sort(Comparator.comparing(data -> data.getSort()));
            measurementDate = interferenceSourceTypeData.get(0);
            //指标对象类型
            List<DictData> indicatorTypeDate = dicDataFeignClient.getDicDataByTypeCode(
                    DicDataTypeEnum.STEADY_STATIS.getCode()).getData();
            indicatorTypeDate.sort(Comparator.comparing(data -> data.getSort()));
            harmonicDate = indicatorTypeDate.get(0);
        } else {
            //获取检测点对象（电压）
            measurementDate = dicDataFeignClient.getDicDataById(
                    param.getMonitorID()).getData();
            //获取指标对象（频率偏差）
            harmonicDate = dicDataFeignClient.getDicDataById(
                    param.getStasisID()).getData();
        }
        //反防止参数查询数据报错
        Assert.isTrue(
                ObjectUtil.isNotNull(measurementDate) || ObjectUtil.isNotNull(harmonicDate)
                , "干扰源类型或者指标类型为空,请检查入参是否准确");

        //获取主网id信息
        DictData mainnetData = dicDataFeignClient.getDicDataByCode(DicDataEnum.MAINNET_POINT.getCode()).getData();

        //获取当前部门下所有部门信息
        List<DeptDTO> deptList = deptFeignClient.getDeptDescendantIndexes(param.getId(), WebUtil.filterDeptType()).getData();
        List<DeptDTO> deptDTOList = DeptUtil.getDeptSubsetVOList(deptList, param.getId());
        List<String> deptIds = deptDTOList.stream().map(DeptDTO::getCode).collect(Collectors.toList());

        StatSubstationBizBaseParam baseParam = BeanUtil.copyProperties(param, StatSubstationBizBaseParam.class);
        baseParam.setIds(deptIds);
        //数据库查询
        List<RStatHarmonicD> rStatHarmonicVoltageMS = rStatHarmonicDMapper
                .selectInfoList(baseParam, mainnetData.getId(), measurementDate.getId(), harmonicDate.getId());

        Map<LocalDate, List<RStatHarmonicD>> collect =
                rStatHarmonicVoltageMS.stream().collect(Collectors.groupingBy(RStatHarmonicD::getDataDate));

        //获取月份
        List<String> intervalTime = this.getIntervalTime(param.getStartTime(), param.getEndTime());
        for (String interTime : intervalTime) {
            //生成初始时间
            String startTime = PublicDateUtil.getFisrtDayOfMonth(Integer.parseInt(interTime.substring(0, 4)), Integer.parseInt(interTime.substring(5)));
            String endTime = PublicDateUtil.getLastDayOfMonth(Integer.parseInt(interTime.substring(0, 4)), Integer.parseInt(interTime.substring(5)));
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
            Date dt = simpleDateFormat.parse(startTime);
            Date dtDate = simpleDateFormat.parse(endTime);
            Integer year = Integer.valueOf(String.format("%tY", dt));
            Integer mon = Integer.valueOf(String.format("%tm", dt));
            Integer day = Integer.valueOf(String.format("%td", dtDate));
            //生成月份数据
            List<String> dayTime = this.getIntervalDateTime(year, mon, day);
            for (String s : dayTime) {
                RHarmonicPolylineVO rPolylineVO = new RHarmonicPolylineVO();
                rPolylineVO.setDate(s);
                if (collect.containsKey(LocalDateTimeUtil.parseDate(s, "yyyy-MM-dd"))) {
                    List<RStatHarmonicD> rSd = collect.get(LocalDateTimeUtil.parseDate(s, "yyyy-MM-dd"));
                    rPolylineVO.setNum(rSd.get(0).getOverLimitMeasurement());
                    rPolylineVO.setOverLimitMeasurementRatioAverage(rSd.get(0).getOverLimitMeasurementRatio());
                    rPolylineVO.setAverageOverDay(1);
                } else {
                    rPolylineVO.setNum(0);
                    rPolylineVO.setAverageOverDay(0);
                    rPolylineVO.setOverLimitMeasurementRatioAverage(0.0f);
                }
                iconList.add(rPolylineVO);
            }

        }
        return iconList;
    }

    @Override
    public List<RArrayVO> getPwRStatHarmonicMAll(StatisticsBizBaseParam param) {
        //对象主节点 获取所有的稳态类型
        List<DictData> eventData = dicDataFeignClient.getDicDataByTypeCode(
                DicDataTypeEnum.STEADY_STATIS.getCode()).getData();
        Map<String, DictData> eventMap = eventData.stream()
                .collect(Collectors.toMap(DictData::getId, Function.identity()));

        //子节点获取监测点类别
        List<DictData> lineData = dicDataFeignClient.getDicDataByTypeCode(
                DicDataTypeEnum.LINE_SORT.getCode()).getData();
        Map<String, DictData> lineMap = lineData.stream()
                .collect(Collectors.toMap(DictData::getId, Function.identity()));

        //获取配网id信息
        DictData distributionData = dicDataFeignClient.getDicDataByCode(DicDataEnum.DISTRIBUTION_POINT.getCode()).getData();
        //初始化指标类型（横向）
        List<RArrayVO> arrayVOList = new ArrayList<>();

        //获取当前部门下所有部门信息
        List<DeptDTO> deptList = deptFeignClient.getDeptDescendantIndexes(param.getId(), WebUtil.filterDeptType()).getData();
        List<DeptDTO> deptDTOList = DeptUtil.getDeptSubsetVOList(deptList, param.getId());
        List<String> deptIds = deptDTOList.stream().map(DeptDTO::getCode).collect(Collectors.toList());

        StatSubstationBizBaseParam baseParam = BeanUtil.copyProperties(param, StatSubstationBizBaseParam.class);
        baseParam.setIds(deptIds);
        //数据库查询
        List<RStatHarmonicM> list = rStatHarmonicMMapper.selectInfoList(baseParam, distributionData.getId());

        //根据稳态指标分组
        Map<String, List<RStatHarmonicM>> measurementMap = list.stream().collect(Collectors.groupingBy(RStatHarmonicM::getHarmonicType));

        //判断对象是否为空
        if (CollUtil.isNotEmpty(list)) {
            //重新生成数据结构
            measurementMap.forEach((key, value) -> {
                List<RStatHarmonicMVO> eventVO = new ArrayList<>();
                if (eventMap.containsKey(key)) {
                    RArrayVO arrayVO = new RArrayVO();
                    DictData data = eventMap.get(key);
                    arrayVO.setRowName(data.getName());
                    arrayVO.setSort(data.getSort());
                    for (RStatHarmonicM statHarmonic : value) {
                        if (lineMap.containsKey(statHarmonic.getMeasurementTypeClass())) {
                            RStatHarmonicMVO r = BeanUtil.copyProperties(statHarmonic, RStatHarmonicMVO.class);
                            DictData data1 = lineMap.get(statHarmonic.getMeasurementTypeClass());
                            r.setHarmonicName(data1.getName());
                            r.setSort(data1.getSort());
                            DecimalFormat df = new DecimalFormat("###.00");
                            Float averageOverDay = Float.parseFloat(
                                    df.format(r.getOverDay() / (r.getOverLimitMeasurementAccrued() * 1.0)));
                            r.setAverageOverDay(averageOverDay);
                            eventVO.add(r);
                        }
                    }
                    //根据监测点类别获取差集
                    Map<String, List<RStatHarmonicM>> listMap = value.stream().collect(Collectors.groupingBy(RStatHarmonicM::getMeasurementTypeClass));
                    List<DictData> differenceList = lineData.stream().filter(r -> !listMap.containsKey(r.getId()))
                            .collect(Collectors.toList());
                    this.assignDict(differenceList, eventVO, arrayVO);
                    eventVO.sort(Comparator.comparing(statHarmonic -> statHarmonic.getSort()));
                    arrayVOList.add(arrayVO);
                }
            });
        }
        //处理主节点不存在的集合
        List<DictData> notMeasurementList = eventData.stream().filter(r -> !measurementMap.containsKey(r.getId()))
                .collect(Collectors.toList());
        for (DictData notData : notMeasurementList) {
            List<RStatHarmonicMVO> statharmonicVO = new ArrayList<>();
            RArrayVO arrayVO = new RArrayVO();
            arrayVO.setRowName(notData.getName());
            arrayVO.setSort(notData.getSort());
            this.assignDict(lineData, statharmonicVO, arrayVO);
            statharmonicVO.sort(Comparator.comparing(statHarmonic -> statHarmonic.getSort()));
            arrayVOList.add(arrayVO);
        }
        arrayVOList.sort(Comparator.comparing(rArrayVO -> rArrayVO.getSort()));
        return arrayVOList;
    }

    @SneakyThrows
    @Override
    public List<RHarmonicPolylineVO> getPwRStatHarmonicIconDate(RStatHarmonicMParam param) {
        //初始化对象
        List<RHarmonicPolylineVO> iconList = new ArrayList<>();
        DictData measurementDate;
        //指标对象类型属性
        DictData harmonicDate;
        //判断是是否传入检测点信息值（电压）
        if (StrUtil.isBlank(param.getStasisID()) && StrUtil.isBlank(param.getMonitorID())) {
            //干扰数据类型（监测对象）
            List<DictData> interferenceSourceTypeData = dicDataFeignClient.getDicDataByTypeCode(
                    DicDataTypeEnum.LINE_SORT.getCode()).getData();
            interferenceSourceTypeData.sort(Comparator.comparing(data -> data.getSort()));
            measurementDate = interferenceSourceTypeData.get(0);
            //指标对象类型
            List<DictData> indicatorTypeDate = dicDataFeignClient.getDicDataByTypeCode(
                    DicDataTypeEnum.STEADY_STATIS.getCode()).getData();
            indicatorTypeDate.sort(Comparator.comparing(data -> data.getSort()));
            harmonicDate = indicatorTypeDate.get(0);
        } else {
            //获取检测点对象（电压）
            measurementDate = dicDataFeignClient.getDicDataById(
                    param.getMonitorID()).getData();
            //获取指标对象（频率偏差）
            harmonicDate = dicDataFeignClient.getDicDataById(
                    param.getStasisID()).getData();
        }
        //反防止参数查询数据报错
        Assert.isTrue(
                ObjectUtil.isNotNull(measurementDate) || ObjectUtil.isNotNull(harmonicDate)
                , "监测点类别或者指标类型为空,请检查入参是否准确");
        //获取配网信息
        DictData distributionData = dicDataFeignClient.getDicDataByCode(DicDataEnum.DISTRIBUTION_POINT.getCode()).getData();

        //获取当前部门下所有部门信息
        List<DeptDTO> deptList = deptFeignClient.getDeptDescendantIndexes(param.getId(), WebUtil.filterDeptType()).getData();
        List<DeptDTO> deptDTOList = DeptUtil.getDeptSubsetVOList(deptList, param.getId());
        List<String> deptIds = deptDTOList.stream().map(DeptDTO::getCode).collect(Collectors.toList());

        StatSubstationBizBaseParam baseParam = BeanUtil.copyProperties(param, StatSubstationBizBaseParam.class);
        baseParam.setIds(deptIds);
        //数据库查询
        List<RStatHarmonicD> rStatHarmonicVoltageMS = rStatHarmonicDMapper
                .selectInfoList(baseParam, distributionData.getId(), measurementDate.getId(), harmonicDate.getId());

        Map<LocalDate, List<RStatHarmonicD>> collect =
                rStatHarmonicVoltageMS.stream().collect(Collectors.groupingBy(RStatHarmonicD::getDataDate));

        //获取月份
        List<String> intervalTime = this.getIntervalTime(param.getStartTime(), param.getEndTime());
        for (String interTime : intervalTime) {
            //生成初始时间
            String startTime = PublicDateUtil.getFisrtDayOfMonth(Integer.parseInt(interTime.substring(0, 4)), Integer.parseInt(interTime.substring(5)));
            String endTime = PublicDateUtil.getLastDayOfMonth(Integer.parseInt(interTime.substring(0, 4)), Integer.parseInt(interTime.substring(5)));
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
            Date dt = simpleDateFormat.parse(startTime);
            Date dtDate = simpleDateFormat.parse(endTime);
            Integer year = Integer.valueOf(String.format("%tY", dt));
            Integer mon = Integer.valueOf(String.format("%tm", dt));
            Integer day = Integer.valueOf(String.format("%td", dtDate));
            //生成月份数据
            List<String> dayTime = this.getIntervalDateTime(year, mon, day);
            for (String s : dayTime) {
                RHarmonicPolylineVO rPolylineVO = new RHarmonicPolylineVO();
                rPolylineVO.setDate(s);
                if (collect.containsKey(LocalDateTimeUtil.parseDate(s, "yyyy-MM-dd"))) {
                    List<RStatHarmonicD> rSd = collect.get(LocalDateTimeUtil.parseDate(s, "yyyy-MM-dd"));
                    rPolylineVO.setNum(rSd.get(0).getOverLimitMeasurement());
                    rPolylineVO.setOverLimitMeasurementRatioAverage(rSd.get(0).getOverLimitMeasurementRatio());
                    rPolylineVO.setAverageOverDay(1);
                } else {
                    rPolylineVO.setNum(0);
                    rPolylineVO.setAverageOverDay(0);
                    rPolylineVO.setOverLimitMeasurementRatioAverage(0.0f);
                }
                iconList.add(rPolylineVO);
            }

        }
        return iconList;
    }

    /**
     * 便利赋值
     *
     * @param DictDataList   稳态指标类型集合
     * @param statharmonicVO 暂态监测点
     * @param arrayVO        初始化对象
     */
    private void assignDict(List<DictData> DictDataList, List<RStatHarmonicMVO> statharmonicVO, RArrayVO arrayVO) {
        for (DictData dictData : DictDataList) {
            RStatHarmonicMVO notStatHarmonicVO = new RStatHarmonicMVO();
            notStatHarmonicVO.setHarmonicName(dictData.getName());
            notStatHarmonicVO.setSort(dictData.getSort());
            notStatHarmonicVO.setOverLimitMeasurementAverage(0.0F);
            notStatHarmonicVO.setOverLimitMeasurementAccrued(0);
            notStatHarmonicVO.setOverDay(0);
            notStatHarmonicVO.setOverLimitMeasurementRatioAverage(0.0F);
            notStatHarmonicVO.setOverLimitMeasurementRatioAccrued(0.0F);
            notStatHarmonicVO.setAverageOverDay(0.0F);
            statharmonicVO.add(notStatHarmonicVO);
        }
        arrayVO.setColumns(statharmonicVO);
    }

    /**
     * 根据用户选择的时间区间返回月份日期
     */
    @SneakyThrows
    private List<String> getIntervalTime(String startTime, String endTime) {
        List<String> times = new ArrayList<>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
        Date start = sdf.parse(startTime);
        Date end = sdf.parse(endTime);
        // 同月
        if (start.getTime() == end.getTime()) {
            String time = startTime.substring(0, 7);
            times.add(time);
        } else if (start.getYear() == end.getYear()) {
            // 同年
            int startM = start.getMonth() + 1;
            int endM = end.getMonth() + 1;
            int temp = endM - startM;
            for (int i = 0; i <= temp; i++) {
                String time = start.getYear() + 1900 + "";
                int month = startM + i;
                if (month < 10) {
                    time = time + "-0" + month;
                } else {
                    time = time + "-" + month;
                }
                times.add(time);
            }
        } else {
            // 不同年!!!!这里忽略了年份之间跨年的情况
            int startY = start.getYear() + 1900;
            int startM = start.getMonth() + 1;
            int endY = end.getYear() + 1900;
            int endM = end.getMonth() + 1;
            int tempS = 12 - startM;
            // 连续的年份
            if (endY - startY == 1) {
                // 第一年的时间获取
                for (int i = 0; i <= tempS; i++) {
                    int month = startM + i;
                    String time = startY + "-";
                    if (month < 10) {
                        time = time + "0" + month;
                    } else {
                        time = time + month;
                    }
                    times.add(time);
                }
                // 第二年的时间获取

                for (int i = 1; i <= endM; i++) {
                    String time = endY + "-";
                    if (i < 10) {
                        time = time + "0" + i;
                    } else {
                        time = time + i;
                    }
                    times.add(time);
                }
            } else {
                // 不连续的年份
                // 第一年的时间获取
                for (int i = 0; i <= tempS; i++) {
                    int month = startM + i;
                    String time = startY + "-";
                    if (month < 10) {
                        time = time + "0" + month;
                    } else {
                        time = time + month;
                    }
                    times.add(time);
                }
                int tempY = endY - startY;
                // 中间年份的时间
                for (int i = 1; i < tempY; i++) {
                    for (int j = 1; j <= 12; j++) {
                        String time = startY + i + "-";
                        if (j < 10) {
                            time = time + "0" + j;
                        } else {
                            time = time + j;
                        }
                        times.add(time);
                    }
                }
                // 最后一年的时间获取
                for (int i = 1; i <= endM; i++) {
                    String time = endY + "-";
                    if (i < 10) {
                        time = time + "0" + i;
                    } else {
                        time = time + i;
                    }
                    times.add(time);
                }
            }

        }
        return times;
    }

    @SneakyThrows
    private List<String> getIntervalDateTime(Integer startTime, Integer endTime, Integer dd) {
        List<String> list = new ArrayList<>();
        Calendar calendar = Calendar.getInstance(Locale.CHINA);
        calendar.set(startTime, endTime - 1, 1);
        //年份
        int year = calendar.get(Calendar.YEAR);
        //月份
        int month = calendar.get(Calendar.MONTH) + 1;
        for (int i = 1; i <= dd; i++) {
            String date = null;
            if (month < 10 && i < 10) {
                date = year + "-0" + month + "-0" + i;
            }
            if (month < 10 && i >= 10) {
                date = year + "-0" + month + "-" + i;
            }
            if (month >= 10 && i < 10) {
                date = year + "-" + month + "-0" + i;
            }
            if (month >= 10 && i >= 10) {
                date = year + "-" + month + "-" + i;
            }

            list.add(date);
        }
        return list;
    }

}
