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

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.njcn.common.pojo.constant.BizParamConstant;
import com.njcn.common.pojo.param.StatisticsBizBaseParam;
import com.njcn.harmonic.mapper.majornetwork.RStatLoadTypeMMapper;
import com.njcn.harmonic.mapper.majornetwork.RStatLoadTypeQMapper;
import com.njcn.harmonic.mapper.majornetwork.RStatLoadTypeYMapper;
import com.njcn.harmonic.pojo.param.StatSubstationBizBaseParam;
import com.njcn.harmonic.pojo.po.*;
import com.njcn.harmonic.pojo.vo.RArrayVO;
import com.njcn.harmonic.pojo.vo.RStatHarmonicMVO;
import com.njcn.harmonic.pojo.vo.RStatLoadTypeVO;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.njcn.harmonic.service.majornetwork.RStatLoadTypeService;
import com.njcn.harmonic.utils.DeptUtil;
import com.njcn.system.api.DicDataFeignClient;
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 org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author rui.wu
 * @since 2022-10-19
 */
@Service
@RequiredArgsConstructor
public class RStatLoadTypeServiceImpl extends ServiceImpl<RStatLoadTypeMMapper, RStatLoadTypeM> implements RStatLoadTypeService {

    private final DeptFeignClient deptFeignClient;
    private final DicDataFeignClient dicDataFeignClient;
    private final RStatLoadTypeYMapper rStatLoadTypeYMapper;
    private final RStatLoadTypeQMapper rStatLoadTypeQMapper;
    private final RStatLoadTypeMMapper rStatLoadTypeMMapper;

    @Override
    public List<RArrayVO> getRStatLoadType(StatisticsBizBaseParam param) {
        //获取部门信息
        List<DeptDTO> deptList = deptFeignClient.getDeptDescendantIndexes(param.getId(), WebUtil.filterDeptType()).getData();
        List<DeptDTO> data = DeptUtil.getDeptSubsetVOList(deptList, param.getId());


        List<String> deptIds = data.stream().map(DeptDTO::getCode).collect(Collectors.toList());
        //获取字典信息
        List<DictData> data1 = dicDataFeignClient.getDicDataByTypeCode(
                DicDataTypeEnum.MONITORING_LABELS.getCode()).getData();
        List<DictData> dictData = data1.stream().filter(labels -> labels.getLevel() == 1).collect(Collectors.toList());

        dictData.sort(Comparator.comparing(r -> r.getSort()));
        //初始化对象
        List<RArrayVO> info = new ArrayList<>();
        List<RStatLoadTypeVO> temp = new ArrayList<>();
        //根据部门进行筛选
        StatSubstationBizBaseParam baseParam = BeanUtil.copyProperties(param, StatSubstationBizBaseParam.class);
        baseParam.setIds(deptIds);
        if (CollectionUtil.isNotEmpty(data)) {
            // 类型（1年 2季度 3月份
            switch (param.getType().toString()) {
                case BizParamConstant.STAT_BIZ_YEAR:
                    // 获取年区域暂态指标分类统计表
                    temp = rStatLoadTypeYMapper.getYearStatLoadType(baseParam);
                    break;
                case BizParamConstant.STAT_BIZ_QUARTER:
                    // 获取季区域暂态指标分类统计表
                    temp = rStatLoadTypeQMapper.getQuarterStatLoadType(baseParam);
                    break;
                case BizParamConstant.STAT_BIZ_MONTH:
                    // 获取月区域暂态指标分类统计表
                    temp = rStatLoadTypeMMapper.getMonthStatLoadType(baseParam);
                    break;
                default:
                    break;

            }
            //根据部门id进行分组
            Map<String, List<RStatLoadTypeVO>> map = temp
                    .stream().collect(Collectors.groupingBy(RStatLoadTypeVO::getOrgNo));
            if (CollectionUtil.isNotEmpty(temp)) {
                // 匹配单位名称
                for (DeptDTO dto : data) {
                    for (RStatLoadTypeVO vo : temp) {
                        if (dto.getCode().equals(vo.getOrgNo())) {
                            vo.setOrgName(dto.getName());
                            vo.setSort(dto.getSort());
                        }
                    }
                }

                map.forEach((key, value) -> {
                    RArrayVO arrayVO = new RArrayVO();
                    arrayVO.setRowName(value.get(0).getOrgName());
                    arrayVO.setSort(value.get(0).getSort());
                    //属性赋值监测点名称
                    for (DictData dictDatum : dictData) {
                        for (RStatLoadTypeVO rStatLoadTypeVO : value) {
                            if (dictDatum.getId().equals(rStatLoadTypeVO.getLoadType())) {
                                rStatLoadTypeVO.setLoadName(dictDatum.getName());
                                rStatLoadTypeVO.setSort(dictDatum.getSort());

                            }
                        }
                    }
                    //获取差集（数据在字典里面没有的集合）
                    Map<String, List<RStatLoadTypeVO>> listMap = value.stream().collect(Collectors.groupingBy(RStatLoadTypeVO::getLoadType));
                    List<DictData> differenceList = dictData.stream().filter(r -> !listMap.containsKey(r.getId()))
                            .collect(Collectors.toList());
                    for (DictData data4 : differenceList) {
                        RStatLoadTypeVO vo = new RStatLoadTypeVO();
                        vo.setSort(data4.getSort());
                        vo.setOrgNo(key);
                        vo.setOrgName(value.get(0).getOrgName());
                        set(value, data4, vo);
                    }
                    value.sort(Comparator.comparing(r -> r.getSort()));
                    arrayVO.setColumns(value);
                    info.add(arrayVO);
                });
            }
            //处理主节点不存在的集合
            List<DeptDTO> notMeasurementList = data.stream().filter(r -> !map.containsKey(r.getCode()))
                    .collect(Collectors.toList());
            RArrayVO arrayVO;
            List<RStatLoadTypeVO> loadTypeVOS;
            for (DeptDTO deptDTO : notMeasurementList) {
                arrayVO= new RArrayVO();
                arrayVO.setRowName(deptDTO.getName());
                arrayVO.setSort(deptDTO.getSort());
                loadTypeVOS=new ArrayList<>();
                for (DictData dict : dictData) {
                    RStatLoadTypeVO vo = new RStatLoadTypeVO();
                    vo.setSort(dict.getSort());
                    vo.setOrgNo(deptDTO.getCode());
                    vo.setOrgName(deptDTO.getName());
                    set(loadTypeVOS, dict, vo);
                }
                loadTypeVOS.sort(Comparator.comparing(r -> r.getSort()));
                arrayVO.setColumns(loadTypeVOS);
                info.add(arrayVO);
            }
            info.sort(Comparator.comparing(r -> r.getSort()));
        }
        return info;
    }

    /**
     * 属性赋值
     * @param value
     * @param data4
     * @param vo
     */
    private void set(List<RStatLoadTypeVO> value, DictData data4, RStatLoadTypeVO vo) {
        vo.setLoadType(data4.getId());
        vo.setLoadName(data4.getName());
        vo.setVAverage(0.0f);
        vo.setVAccrued(0.0f);
        vo.setIAverage(0.0f);
        vo.setIAccrued(0.0f);
        vo.setUnbalanceAverage(0.0f);
        vo.setUnbalanceAccrued(0.0f);
        vo.setINegAverage(0.0f);
        vo.setINegAccrued(0.0f);
        vo.setFlickerAverage(0.0f);
        vo.setFlickerAccrued(0.0f);
        value.add(vo);
    }
}
