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.RStatEventYMapper;
import com.njcn.event.pojo.param.StatSubstationBizBaseParam;
import com.njcn.event.pojo.po.RStatEventY;
import com.njcn.event.pojo.vo.RArrayVO;
import com.njcn.event.pojo.vo.RStatEventMVO;
import com.njcn.event.service.majornetwork.RStatEventYService;
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.user.pojo.po.Dept;
import com.njcn.web.utils.WebUtil;
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 RStatEventYServiceImpl extends ServiceImpl<RStatEventYMapper, RStatEventY> implements RStatEventYService {

    private final RStatEventYMapper rStatEventYMapper;
    private final DicDataFeignClient dicDataFeignClient;
    private final DeptFeignClient deptFeignClient;

    @Override
    public List<RArrayVO> getRStatEventYAll(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<RStatEventY> list = rStatEventYMapper.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<RStatEventY>> MeasurementTypeClassMap = list.stream().collect(Collectors.groupingBy(RStatEventY::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 (RStatEventY rStatEventY : value) {
                    if(interferenceMap.containsKey(rStatEventY.getMeasurementTypeClass())){
                        RStatEventMVO r = BeanUtil.copyProperties(rStatEventY, RStatEventMVO.class);
                        DictData data1 = interferenceMap.get(rStatEventY.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> getPwRStatEventYAll(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<RStatEventY> list = rStatEventYMapper.selectInfoList(baseParam,distributionData.getId());

        //根据暂态指标分组
        Map<String, List<RStatEventY>> measurementMap = list.stream().collect(Collectors.groupingBy(RStatEventY::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 (RStatEventY rStatEventY : value) {
                        if(lineMap.containsKey(rStatEventY.getMeasurementTypeClass())){
                            RStatEventMVO r = BeanUtil.copyProperties(rStatEventY, RStatEventMVO.class);
                            DictData data1 = lineMap.get(rStatEventY.getMeasurementTypeClass());
                            r.setEventName(data1.getName());
                            r.setSort(data1.getSort());
                            eventVO.add(r);
                        }

                    }
                    //根据监测点类别获取差集
                    Map<String, List<RStatEventY>> listMap = value.stream().collect(Collectors.groupingBy(RStatEventY::getMeasurementTypeClass));
                    List<DictData> differenceList = lineData.stream().filter(r -> !listMap.containsKey(r.getId()))
                            .collect(Collectors.toList());
                    this.assignDict(differenceList, eventVO, arrayVO);
                    arrayVO.setColumns(eventVO);
                    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;
    }

    @Override
    public List<RStatEventMVO.Vo> getEventBenchmarkLevelList(StatSubstationBizBaseParam param) {
        //获取暂态信息
        Map<String, String> map = new HashMap<>(3);
        //获取主网监测点
        DictData data = dicDataFeignClient.getDicDataByCode(DicDataEnum.MAINNET_POINT.getCode()).getData();
        List<DictData> dictDataList = dicDataFeignClient.getDicDataByTypeCode(DicDataTypeEnum.EVENT_STATIS.getCode()).getData();
        //获取所有子部门信息
        List<DeptDTO> deptDTOList = deptFeignClient.getDeptDescendantIndexes(param.getId(), WebUtil.filterDeptType()).getData();
        List<String> ids = deptDTOList.stream().map(DeptDTO::getCode).collect(Collectors.toList());
        //根据字典Code，取出字典id，拼入sql中
        dictDataList.stream().forEach(dictData -> {
            if (DicDataEnum.VOLTAGE_DIP.getCode().equals(dictData.getCode())) {
                map.put("dip", dictData.getId());
            }
            if (DicDataEnum.VOLTAGE_RISE.getCode().equals(dictData.getCode())) {
                map.put("rise", dictData.getId());
            }
            if (DicDataEnum.SHORT_INTERRUPTIONS.getCode().equals(dictData.getCode())) {
                map.put("interrupt", dictData.getId());
            }
        });
        //数据分页查询
        List<RStatEventMVO.Vo> vos = this.baseMapper.selectEventBenchmarkLevel(ids, param, map, data.getId());
        if(CollUtil.isNotEmpty(vos)){
            Map<String, DeptDTO> deptDTOMap = deptDTOList.stream().collect(Collectors.toMap(DeptDTO::getCode, Function.identity()));
            vos.forEach(vo -> {
                if (deptDTOMap.containsKey(vo.getOrgId())) {
                    DeptDTO deptDTO = deptDTOMap.get(vo.getOrgId());
                    vo.setOrgName(deptDTO.getName());
                    vo.setSort(deptDTO.getSort());
                }
            });
            vos.sort(Comparator.comparing(RStatEventMVO.Vo::getSort).reversed());
        }
        return vos;
    }

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