package com.njcn.event.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.event.mapper.majornetwork.RStatEventQMapper;
import com.njcn.event.pojo.param.StatSubstationBizBaseParam;
import com.njcn.event.pojo.po.RStatEventQ;
import com.njcn.event.pojo.vo.RArrayVO;
import com.njcn.event.pojo.vo.RStatEventMVO;
import com.njcn.event.service.majornetwork.RStatEventQService;
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 RStatEventQServiceImpl extends ServiceImpl<RStatEventQMapper, RStatEventQ> implements RStatEventQService {

    private final RStatEventQMapper rStatEventQMapper;
    private final DicDataFeignClient dicDataFeignClient;
    private final DeptFeignClient deptFeignClient;

    @Override
    public List<RArrayVO> getRStatEventQAll(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.EVENT_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<RStatEventQ> list = rStatEventQMapper.selectInfoList(baseParam,mainnetData.getId());

        //初始化指标类型（横向）
        List<RArrayVO> arrayVOList = new ArrayList<>();
        List<RStatEventMVO> rm = new ArrayList<>();
        for (DictData lineTypeDatum : interferenceSourceTypeData) {
            RStatEventMVO r = new RStatEventMVO();
            r.setEventName(lineTypeDatum.getName());
            r.setSort(lineTypeDatum.getSort());
            r.setEventMeasurementAverage(0.0F);
            r.setEventMeasurementAccrued(0);
            r.setEventFreq(0.0F);
            r.setEventCount(0);
            r.setEventMeasurementRatioAverage(0.0F);
            r.setEventMeasurementRatioAccrued(0.0F);
            rm.add(r);
        }
        for (DictData lineTypeDatum : lineTypeData) {
            RArrayVO r = new RArrayVO();
            r.setRowName(lineTypeDatum.getName());
            r.setColumns(rm);
            r.setSort(lineTypeDatum.getSort());
            arrayVOList.add(r);
        }
        //根据暂态指标分组
        Map<String, List<RStatEventQ>> MeasurementTypeClassMap = list.stream().collect(Collectors.groupingBy(RStatEventQ::getEventType));
        //重新生成数据结构
        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<RStatEventMVO> b = new ArrayList<>();
                b.addAll(rm);
                for (RStatEventQ rStatEventQ : value) {
                    if(interferenceMap.containsKey(rStatEventQ.getMeasurementTypeClass())){
                        RStatEventMVO r = BeanUtil.copyProperties(rStatEventQ, RStatEventMVO.class);
                        DictData data1 = interferenceMap.get(rStatEventQ.getMeasurementTypeClass());
                        r.setEventName(data1.getName());
                        r.setSort(data1.getSort());
                        b.add(r);
                    }

                }
                Map<String, RStatEventMVO> linkedHashMap = new LinkedHashMap<>();
                for (RStatEventMVO harmonicMVO : b) {
                    linkedHashMap.put(harmonicMVO.getEventName(), harmonicMVO);
                }
                List<RStatEventMVO> aa = new ArrayList<>(linkedHashMap.values());
                aa.sort(Comparator.comparing(rStatEventMVO -> rStatEventMVO.getSort()));
                arrayVO.setColumns(aa);
                arrayVOList.add(arrayVO);
            }

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

    @Override
    public List<RArrayVO> getPwRStatEventQAll(StatisticsBizBaseParam param) {
        //对象主节点 获取所有得暂降类型
        List<DictData> eventData = dicDataFeignClient.getDicDataByTypeCode(
                DicDataTypeEnum.EVENT_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<RStatEventQ> list = rStatEventQMapper.selectInfoList(baseParam,distributionData.getId());

        //根据暂态指标分组
        Map<String, List<RStatEventQ>> measurementMap = list.stream().collect(Collectors.groupingBy(RStatEventQ::getEventType));
        //判断对象是否为空
        if (CollUtil.isNotEmpty(list)) {
            //重新生成数据结构
            measurementMap.forEach((key, value) -> {
                List<RStatEventMVO> 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 (RStatEventQ rStatEvent : value) {
                        if(lineMap.containsKey(rStatEvent.getMeasurementTypeClass())){
                            RStatEventMVO r = BeanUtil.copyProperties(rStatEvent, RStatEventMVO.class);
                            DictData data1 = lineMap.get(rStatEvent.getMeasurementTypeClass());
                            r.setEventName(data1.getName());
                            r.setSort(data1.getSort());
                            eventVO.add(r);
                        }

                    }
                    //根据监测点类别获取差集
                    Map<String, List<RStatEventQ>> listMap = value.stream().collect(Collectors.groupingBy(RStatEventQ::getMeasurementTypeClass));
                    List<DictData> differenceList = lineData.stream().filter(r -> !listMap.containsKey(r.getId()))
                            .collect(Collectors.toList());
                    this.assignDict(differenceList, eventVO, arrayVO);
                    eventVO.sort(Comparator.comparing(rStatEventMVO -> rStatEventMVO.getSort()));
                    arrayVOList.add(arrayVO);
                }
            });
        }

        //处理主节点不存在的集合
        List<DictData> notMeasurementList = eventData.stream().filter(r -> !measurementMap.containsKey(r.getId()))
                .collect(Collectors.toList());
        for (DictData notData : notMeasurementList) {
            List<RStatEventMVO> eventVO = new ArrayList<>();
            RArrayVO arrayVO = new RArrayVO();
            arrayVO.setRowName(notData.getName());
            arrayVO.setSort(notData.getSort());
            this.assignDict(lineData, eventVO, arrayVO);
            eventVO.sort(Comparator.comparing(rStatEventMVO -> rStatEventMVO.getSort()));
            arrayVOList.add(arrayVO);
        }
        arrayVOList.sort(Comparator.comparing(rArrayVO -> rArrayVO.getSort()));
        return arrayVOList;
    }

    /**
     * 便利赋值
     *
     * @param DictDataList 暂态类型集合
     * @param eventVO      暂态监测点
     * @param arrayVO      初始化对象
     */
    private void assignDict(List<DictData> DictDataList, List<RStatEventMVO> eventVO, RArrayVO arrayVO) {
        for (DictData dictData : DictDataList) {
            RStatEventMVO notEventVO = new RStatEventMVO();
            notEventVO.setEventName(dictData.getName());
            notEventVO.setSort(dictData.getSort());
            notEventVO.setEventMeasurementAverage(0.0F);
            notEventVO.setEventMeasurementAccrued(0);
            notEventVO.setEventFreq(0.0F);
            notEventVO.setEventCount(0);
            notEventVO.setEventMeasurementRatioAverage(0.0F);
            notEventVO.setEventMeasurementRatioAccrued(0.0F);
            eventVO.add(notEventVO);
        }
        arrayVO.setColumns(eventVO);
    }
}
