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

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.njcn.common.pojo.param.StatisticsBizBaseParam;
import com.njcn.harmonic.mapper.majornetwork.RStatHarmonicQMapper;
import com.njcn.harmonic.pojo.param.StatSubstationBizBaseParam;
import com.njcn.harmonic.pojo.po.RStatHarmonicQ;
import com.njcn.harmonic.pojo.vo.RArrayVO;
import com.njcn.harmonic.pojo.vo.RStatHarmonicMVO;
import com.njcn.harmonic.service.majornetwork.RStatHarmonicQService;
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.po.Dept;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author rui.wu
 * @since 2022-10-12
 */
@Service
@RequiredArgsConstructor
public class RStatHarmonicQServiceImpl extends ServiceImpl<RStatHarmonicQMapper, RStatHarmonicQ> implements RStatHarmonicQService {

    private final RStatHarmonicQMapper rStatHarmonicQMapper;
    private final DicDataFeignClient dicDataFeignClient;
    private final DeptFeignClient deptFeignClient;

    @Override
    public List<RArrayVO> getRStatHarmonicQAll(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();

        //获取当前部门下所有部门信息
        Dept dept = deptFeignClient.getDeptById(param.getId()).getData();
        StatSubstationBizBaseParam baseParam = BeanUtil.copyProperties(param, StatSubstationBizBaseParam.class);
        baseParam.setIds(Collections.singletonList(dept.getCode()));
        //数据库查询
        List<RStatHarmonicQ> list = rStatHarmonicQMapper.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<RStatHarmonicQ>> MeasurementTypeClassMap = list.stream().collect(Collectors.groupingBy(RStatHarmonicQ::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 (RStatHarmonicQ rStatHarmonicQ : value) {
                    if (interferenceMap.containsKey(rStatHarmonicQ.getMeasurementTypeClass())) {
                        RStatHarmonicMVO r = BeanUtil.copyProperties(rStatHarmonicQ, RStatHarmonicMVO.class);
                        DictData data1 = interferenceMap.get(rStatHarmonicQ.getMeasurementTypeClass());
                        r.setHarmonicName(data1.getName());
                        r.setSort(data1.getSort());
                        r.setOverDay(0);
                        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());
        arrayVOList.sort(Comparator.comparing(rArrayVO -> rArrayVO.getSort()));
        return aa;
    }

    @Override
    public List<RArrayVO> getPwRStatHarmonicQAll(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<>();
        //获取当前部门
        Dept dept = deptFeignClient.getDeptById(param.getId()).getData();
        StatSubstationBizBaseParam baseParam = BeanUtil.copyProperties(param, StatSubstationBizBaseParam.class);
        baseParam.setIds(Collections.singletonList(dept.getCode()));
        //数据库查询
        List<RStatHarmonicQ> list = rStatHarmonicQMapper.selectInfoList(baseParam, distributionData.getId());

        //根据稳态指标分组
        Map<String, List<RStatHarmonicQ>> measurementMap = list.stream().collect(Collectors.groupingBy(RStatHarmonicQ::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 (RStatHarmonicQ 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());
                            eventVO.add(r);
                        }

                    }
                    //根据监测点类别获取差集
                    Map<String, List<RStatHarmonicQ>> listMap = value.stream().collect(Collectors.groupingBy(RStatHarmonicQ::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;
    }

    /**
     * 便利赋值
     *
     * @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);
    }
}
