package com.njcn.device.pms.service.majornetwork.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.njcn.common.pojo.enums.response.CommonResponseEnum;
import com.njcn.common.pojo.exception.BusinessException;
import com.njcn.device.biz.pojo.dto.DeptGetChildrenMoreDTO;
import com.njcn.device.biz.pojo.dto.LineDevGetDTO;
import com.njcn.device.biz.pojo.param.DeptGetLineParam;
import com.njcn.device.pms.mapper.majornetwork.RMpMonitorAlarmCountMMapper;
import com.njcn.device.pms.pojo.param.RMpMonitorAlarmCountMParam;
import com.njcn.device.pms.pojo.po.RMpMonitorAlarmCountM;
import com.njcn.device.pms.pojo.vo.RMpMonitorAlarmCountMVO;
import com.njcn.device.pms.service.ledgerManger.CommTerminalService;
import com.njcn.device.pms.service.majornetwork.IMonitorService;
import com.njcn.device.pms.service.majornetwork.RMpMonitorAlarmCountMService;
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 lombok.RequiredArgsConstructor;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

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

/**
 * 监测点告警统计service
* @author jianghf
* @description 针对表【r_mp_monitor_alarm_count_m】的数据库操作Service实现
* @createDate 2022-10-12 20:08:33
*/
@Service
@RequiredArgsConstructor
public class RMpMonitorAlarmCountMServiceImpl extends ServiceImpl<RMpMonitorAlarmCountMMapper, RMpMonitorAlarmCountM>
implements RMpMonitorAlarmCountMService {

    private final DeptFeignClient deptFeignClient;

    private final DicDataFeignClient dicDataFeignClient;

    private final IMonitorService iMonitorService; //【主网监测点】服务类

    private final CommTerminalService commTerminalService;

    /***
     * 根据条件查询监测点告警统计(月)(主网)
     * @author jianghaifei
     * @date 2022-11-01 15:21
     * @param rMpMonitorAlarmCountMParam
     * @return java.util.List<com.njcn.device.pms.pojo.vo.RMpMonitorAlarmCountMVO>
     */
    @Override
    public Page<RMpMonitorAlarmCountMVO> getRMpMonitorAlarmCountMList(RMpMonitorAlarmCountMParam rMpMonitorAlarmCountMParam) {
        Page<RMpMonitorAlarmCountMVO> resultPage = new Page<>();
        List<RMpMonitorAlarmCountMVO> resultList = new ArrayList<>();
        //提取查询条件
        String id = rMpMonitorAlarmCountMParam.getId(); //单位id
        if (StringUtils.isBlank(id)) {
            throw new BusinessException(CommonResponseEnum.NO_DATA, "单位id不可为空");
        }
        String startTime = rMpMonitorAlarmCountMParam.getStartTime(); //开始时间
        String endTime = rMpMonitorAlarmCountMParam.getEndTime(); //结束时间
        //监测对象类型
        if (StringUtils.isBlank(rMpMonitorAlarmCountMParam.getMonitorObjectType())){
            return resultPage;
        }
        List<String> monitorObjectType = StringUtils.isNotBlank(rMpMonitorAlarmCountMParam.getMonitorObjectType()) ? Arrays.asList(rMpMonitorAlarmCountMParam.getMonitorObjectType().split(",")) : null;
        //电压等级
        if (StringUtils.isBlank(rMpMonitorAlarmCountMParam.getVoltageLevel())){
            return resultPage;
        }
        List<String> voltageLevelParamList = StringUtils.isNotBlank(rMpMonitorAlarmCountMParam.getVoltageLevel()) ? Arrays.asList(rMpMonitorAlarmCountMParam.getVoltageLevel().split(",")) : null; //电压等级
        String monitorName = rMpMonitorAlarmCountMParam.getMeasurementPointName(); //监测点名称
        //获取电压等级的字典
        List<DictData> voltageLevelList = dicDataFeignClient.getDicDataByTypeCode(DicDataTypeEnum.DEV_VOLTAGE.getCode()).getData();
        //将电压等级信息转成map，key：id  value：name
        Map<String, String> voltageLevelMap = voltageLevelList.stream().collect(Collectors.toMap(DictData::getId, DictData::getName));
        //获取监测点标签字典
        List<DictData> monitorTypeList = dicDataFeignClient.getDicDataByTypeCode(DicDataTypeEnum.MONITORING_LABELS.getCode()).getData();
        //将监测点类型字典信息转为map集合 key: 字典id  value: 字典名称
        Map<String, String> monitorTypeMap = monitorTypeList.stream().collect(Collectors.toMap(DictData::getId, DictData::getName));
        //根据部门id获取监测点
        DeptGetLineParam deptGetLineParam = new DeptGetLineParam();
        deptGetLineParam.setDeptId(id);
        List<DeptGetChildrenMoreDTO> dept = commTerminalService.deptGetLine(deptGetLineParam);
        List<LineDevGetDTO> lineDto = new ArrayList<>();

        if (CollUtil.isNotEmpty(dept)){
            for (DeptGetChildrenMoreDTO item : dept) {
                lineDto.addAll(item.getLineBaseList());
            }
            //获取监测点集合(去重、根据前端传递的参数)
            if (CollUtil.isNotEmpty(lineDto)){
                lineDto = lineDto.stream().collect(
                        Collectors.collectingAndThen(
                                Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(LineDevGetDTO::getPointId))), ArrayList::new));
                //根据前端传递的条件筛选监测点
                lineDto = lineDto.stream().filter(pojo-> monitorObjectType.contains(pojo.getLineTag()) && voltageLevelParamList.contains(pojo.getVoltageLevel())).collect(Collectors.toList());
                if (!Objects.isNull(monitorName)){
                    lineDto = lineDto.stream().filter(pojo->pojo.getPointName().contains(monitorName)).collect(Collectors.toList());
                }
                if (CollUtil.isNotEmpty(lineDto)){
                    List<String> lineList = lineDto.stream().map(LineDevGetDTO::getPointId).collect(Collectors.toList());
                    LambdaQueryWrapper<RMpMonitorAlarmCountM> lambdaQueryWrapper = new LambdaQueryWrapper<>();
                    lambdaQueryWrapper.in(RMpMonitorAlarmCountM::getMeasurementPointId, lineList)
                            .ge(RMpMonitorAlarmCountM::getDataDate, startTime)
                            .le(RMpMonitorAlarmCountM::getDataDate, endTime);
                    Page<RMpMonitorAlarmCountM> page = this.page(new Page<>(rMpMonitorAlarmCountMParam.getPageNum(), rMpMonitorAlarmCountMParam.getPageSize()), lambdaQueryWrapper);
                    BeanUtil.copyProperties(page,resultPage);
                    Map<String,List<RMpMonitorAlarmCountM>> map = page.getRecords().stream().collect(Collectors.groupingBy(RMpMonitorAlarmCountM::getMeasurementPointId));
                    for (LineDevGetDTO item2 : lineDto) {
                        RMpMonitorAlarmCountMVO vo = new RMpMonitorAlarmCountMVO();
                        if (map.containsKey(item2.getPointId())){
                            BeanUtils.copyProperties(map.get(item2.getPointId()).get(0), vo);
                            //所属单位名称
                            vo.setOrgName(item2.getUnitName());
                            vo.setOrgNo(item2.getUnitId());
                            vo.setMeasurementPointId(item2.getPointId());
                            vo.setMeasurementPointName(item2.getPointName());
                            //监测点类型id
                            vo.setMonitorType(item2.getLineTag());
                            //监测点类型名称
                            vo.setMonitorTypeName(monitorTypeMap.get(item2.getLineTag()));
                            //电压等级id
                            vo.setVoltageLevel(item2.getVoltageLevel());
                            //电压等级
                            vo.setVoltageLevelName(voltageLevelMap.get(item2.getVoltageLevel()));
                            resultList.add(vo);
                        }
                    }
                }
            }
        }
        if (CollUtil.isNotEmpty(resultList)){
            resultList = resultList.stream().sorted(Comparator.comparing(RMpMonitorAlarmCountMVO::getOrgName).reversed()).collect(Collectors.toList());
        }
        resultPage.setRecords(resultList);
        return resultPage;
    }

}
