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

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.pms.api.PmsGeneralDeviceInfoClient;
import com.njcn.device.pms.mapper.distribution.PwMonitorMapper;
import com.njcn.device.pms.mapper.distribution.RStatPwAlarmCountWMapper;
import com.njcn.device.pms.mapper.majornetwork.DistributionMonitorMapper;
import com.njcn.device.pms.pojo.dto.PmsMonitorDTO;
import com.njcn.device.pms.pojo.dto.PwPmsMonitorDTO;
import com.njcn.device.pms.pojo.param.PmsMonitorParam;
import com.njcn.device.pms.pojo.param.PwPmsMonitorParam;
import com.njcn.device.pms.pojo.param.RStatPwAlarmCountWParam;
import com.njcn.device.pms.pojo.param.RStatPwAlarmDetailParam;
import com.njcn.device.pms.pojo.po.RMpPwAlarmDetailD;
import com.njcn.device.pms.pojo.po.RStatPwAlarmCountW;
import com.njcn.device.pms.pojo.vo.RStatPwAlarmCountWVO;
import com.njcn.device.pms.pojo.vo.RStatPwAlarmDetailVO;
import com.njcn.device.pms.service.distribution.IPwMonitorService;
import com.njcn.device.pms.service.distribution.RMpPwAlarmDetailDService;
import com.njcn.device.pms.service.distribution.RStatPwAlarmCountWService;
import com.njcn.device.pms.service.majornetwork.IMonitorService;
import com.njcn.device.pms.service.majornetwork.IPmsGeneralDeviceService;
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.web.factory.PageFactory;
import com.njcn.web.utils.WebUtil;
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.function.Function;
import java.util.stream.Collectors;

/**
* @author jianghf
* @description 针对表【r_stat_pw_alarm_count_w】的数据库操作Service实现
* @createDate 2022-11-02 15:42:29
*/
@Service
@RequiredArgsConstructor
public class RStatPwAlarmCountWServiceImpl extends ServiceImpl<RStatPwAlarmCountWMapper, RStatPwAlarmCountW>
    implements RStatPwAlarmCountWService {

    private final DeptFeignClient deptFeignClient;

    private final DicDataFeignClient dicDataFeignClient;

    private final IPwMonitorService iPwMonitorService;

    private final PwMonitorMapper pwMonitorMapper;

    private final RMpPwAlarmDetailDService rMpPwAlarmDetailDService;

    private final DistributionMonitorMapper distributionMonitorMapper;

    private final IPmsGeneralDeviceService iPmsGeneralDeviceService;

    /***
     * 查询各单位告警监测点总数、占比、占比同比信息
     * @author jianghaifei
     * @date 2022-11-03 09:06
     * @param rStatPwAlarmCountWParam
     * @return java.util.List<com.njcn.device.pms.pojo.vo.RStatPwAlarmCountWVO>
     */
    @Override
    public List<RStatPwAlarmCountWVO> getAllRStatPwAlarmCountList(RStatPwAlarmCountWParam rStatPwAlarmCountWParam) {
        //提取查询条件
        String id = rStatPwAlarmCountWParam.getId(); //单位id
        if (StringUtils.isBlank(id)) {
            throw new BusinessException(CommonResponseEnum.NO_DATA, "单位id不可为空");
        }
        String startTime = rStatPwAlarmCountWParam.getStartTime(); //开始时间
        String endTime = rStatPwAlarmCountWParam.getEndTime(); //结束时间


        /*获取下级子部门信息*/
        List<DeptDTO> deptDTOList = deptFeignClient.getDepSonDetailByDeptId (id).getData ( );
        if (CollUtil.isEmpty(deptDTOList)) {
            return Collections.emptyList();
        }
        List<String> orgCodeList = deptDTOList.stream().map(DeptDTO::getCode).collect(Collectors.toList());
        Map<String, String> deptNameMap = deptDTOList.stream().collect(Collectors.toMap(DeptDTO::getCode, DeptDTO::getName));

        //设置数据库查询条件
        Map<String, Object> condMap = new HashMap<>();
        condMap.put("orgIdList", orgCodeList);
        condMap.put("startTime", startTime);
        condMap.put("endTime", endTime);
        List<RStatPwAlarmCountWVO> list = this.baseMapper.getRStatPwAlarmCountVOList(condMap);

        //封装返回结果
        List<RStatPwAlarmCountWVO> resultList = list.stream().map(item -> {
            item.setOrgName(deptNameMap.get(item.getOrgNo()));
            return item;
        }).collect(Collectors.toList());
        return resultList;
    }

    /***
     * 告警明细查看
     * @author jianghaifei
     * @date 2022-11-03 13:56
     * @param rStatPwAlarmDetailParam
     * @return java.util.List<com.njcn.device.pms.pojo.vo.RStatPwAlarmDetailVO>
     */
    @Override
    public Page<RStatPwAlarmDetailVO> getAlarmDetailList(RStatPwAlarmDetailParam rStatPwAlarmDetailParam) {
        //提取查询条件
        String id = rStatPwAlarmDetailParam.getId(); //单位id
        if (StringUtils.isBlank(id)) {
            throw new BusinessException(CommonResponseEnum.NO_DATA, "单位id不可为空");
        }
        String startTime = rStatPwAlarmDetailParam.getStartTime(); //开始时间
        String endTime = rStatPwAlarmDetailParam.getEndTime(); //结束时间
        String monitorName = rStatPwAlarmDetailParam.getMonitorName(); //监测点名称
        Integer pageNum = rStatPwAlarmDetailParam.getPageNum() != null && rStatPwAlarmDetailParam.getPageNum() != 0 ? rStatPwAlarmDetailParam.getPageNum() : 1; //页码
        Integer pageSize = rStatPwAlarmDetailParam.getPageSize() != null && rStatPwAlarmDetailParam.getPageSize() != 0 ? rStatPwAlarmDetailParam.getPageSize() : 10; //页面尺寸
        //告警类型
        List<String> alarmTypeList = StringUtils.isNotBlank(rStatPwAlarmDetailParam.getAlarmType()) ? Arrays.asList(rStatPwAlarmDetailParam.getAlarmType().split(",")) : null;
        //监测点类型
        List<String> monitorSortList = StringUtils.isNotBlank(rStatPwAlarmDetailParam.getMonitorSort()) ? Arrays.asList(rStatPwAlarmDetailParam.getMonitorSort().split(",")) : null;

        //获取监测点类别字典
        List<DictData> lineSortDict = dicDataFeignClient.getDicDataByTypeCode(DicDataTypeEnum.LINE_SORT.getCode()).getData();
        Map<String, String> lineSortIdMap = lineSortDict.stream().collect(Collectors.toMap(DictData::getCode, DictData::getId));

        //根据条件查询单位下面的所有配网监测点
        PwPmsMonitorParam pwPmsMonitorParam = new PwPmsMonitorParam();
        pwPmsMonitorParam.setOrgId(id); //单位id
        pwPmsMonitorParam.setMonitorName(monitorName); //监测点名称
        pwPmsMonitorParam.setMonitorSort(monitorSortList); //监测点类别
        List<String> pwMonitorIds= iPmsGeneralDeviceService.getPwPmsMonitorIds(id,pwPmsMonitorParam.getMonitorSort());

        if(CollUtil.isEmpty(pwMonitorIds)){
            return new Page<>();
        }

        //查询监测点的告警明细
        LambdaQueryWrapper<RMpPwAlarmDetailD> alarmDetailWrapper = new LambdaQueryWrapper<>();
        alarmDetailWrapper.in(RMpPwAlarmDetailD::getMeasurementPointId, pwMonitorIds)
                .in(CollUtil.isNotEmpty(alarmTypeList), RMpPwAlarmDetailD::getAlarmType, alarmTypeList)
                .ge(StringUtils.isNotBlank(startTime), RMpPwAlarmDetailD::getDataDate, startTime)
                .le(StringUtils.isNotBlank(endTime), RMpPwAlarmDetailD::getDataDate, endTime);
        Page<RMpPwAlarmDetailD> alarmDetailListPage = rMpPwAlarmDetailDService.page(new Page<>(pageNum, pageSize), alarmDetailWrapper);

        List<RMpPwAlarmDetailD> temList = alarmDetailListPage.getRecords();
        List<String> monitorIds = new ArrayList<>();
        if(CollUtil.isEmpty(temList)){
            return new Page<>();
        }
        monitorIds = temList.stream().map(RMpPwAlarmDetailD::getMeasurementPointId).distinct().collect(Collectors.toList());

        //配网监测点id集合

        List<PwPmsMonitorDTO> pwMonitorDataList = distributionMonitorMapper.pwMonitorAreaDetailInfo(monitorIds);

        //监测点map  key:监测点id  value:监测点实体
        Map<String, PwPmsMonitorDTO> monitorMap = pwMonitorDataList.stream().collect(Collectors.toMap(PwPmsMonitorDTO::getMonitorId, Function.identity(),(key1,key2)->key1));

        List<RStatPwAlarmDetailVO> resultList = alarmDetailListPage.getRecords().stream().map(item -> {
            RStatPwAlarmDetailVO rStatPwAlarmDetailVO = new RStatPwAlarmDetailVO();
            rStatPwAlarmDetailVO.setAlarmType(item.getAlarmType()); //告警类型
            rStatPwAlarmDetailVO.setAlarmInfo(item.getAlarmInfo()); //告警描述
            rStatPwAlarmDetailVO.setDataDate(item.getDataDate()); //告警时间

            rStatPwAlarmDetailVO.setMeasurementPointId(item.getMeasurementPointId()); //监测点id
            rStatPwAlarmDetailVO.setMeasurementPointName(monitorMap.get(item.getMeasurementPointId()).getMonitorName()); //监测点名称
            rStatPwAlarmDetailVO.setOrgId(monitorMap.get(item.getMeasurementPointId()).getOrgId()); //单位id
            rStatPwAlarmDetailVO.setOrgName(monitorMap.get(item.getMeasurementPointId()).getOrgName());//单位名称
            rStatPwAlarmDetailVO.setMonitorSort(monitorMap.get(item.getMeasurementPointId()).getMonitorSort());//监测点类别
            rStatPwAlarmDetailVO.setVoltageLevel(monitorMap.get(item.getMeasurementPointId()).getVoltageLevel()); //电压等级

            //监测点类别信息(I类监测点)
            if (lineSortIdMap.get(DicDataEnum.ONE_LINE.getCode()).equals(monitorMap.get(item.getMeasurementPointId()).getMonitorSort())) {
                //变电站信息
                rStatPwAlarmDetailVO.setPowerId(monitorMap.get(item.getMeasurementPointId()).getPowerId());
                rStatPwAlarmDetailVO.setPowerName(monitorMap.get(item.getMeasurementPointId()).getPowerName());

                rStatPwAlarmDetailVO.setPowerDistributionAreaId("/"); //台区
                rStatPwAlarmDetailVO.setPowerDistributionAreaName("/");

                rStatPwAlarmDetailVO.setPowerClientId("/"); //用户
                rStatPwAlarmDetailVO.setPowerClientName("/");
            }
            //监测点类别信息(II类监测点)
            if (lineSortIdMap.get(DicDataEnum.TWO_LINE.getCode()).equals(monitorMap.get(item.getMeasurementPointId()).getMonitorSort())) {
                //变电站信息
                rStatPwAlarmDetailVO.setPowerId(monitorMap.get(item.getMeasurementPointId()).getPowerId());
                rStatPwAlarmDetailVO.setPowerName(monitorMap.get(item.getMeasurementPointId()).getPowerName());
                //台区
                rStatPwAlarmDetailVO.setPowerDistributionAreaId(monitorMap.get(item.getMeasurementPointId()).getMonitorId());
                rStatPwAlarmDetailVO.setPowerDistributionAreaName(monitorMap.get(item.getMeasurementPointId()).getMonitorName());
                //用户
                rStatPwAlarmDetailVO.setPowerClientId("/");
                rStatPwAlarmDetailVO.setPowerClientName("/");
            }
            //监测点类别信息(III类监测点)
            if (lineSortIdMap.get(DicDataEnum.THREE_LINE.getCode()).equals(monitorMap.get(item.getMeasurementPointId()).getMonitorSort())) {
                //变电站信息
                rStatPwAlarmDetailVO.setPowerId(monitorMap.get(item.getMeasurementPointId()).getPowerId());
                rStatPwAlarmDetailVO.setPowerName(monitorMap.get(item.getMeasurementPointId()).getPowerName());
                //台区
                rStatPwAlarmDetailVO.setPowerDistributionAreaId("/");
                rStatPwAlarmDetailVO.setPowerDistributionAreaName("/");
                //用户
                rStatPwAlarmDetailVO.setPowerClientId(monitorMap.get(item.getMeasurementPointId()).getMonitorId());
                rStatPwAlarmDetailVO.setPowerClientName(monitorMap.get(item.getMeasurementPointId()).getMonitorName());

            }

            return rStatPwAlarmDetailVO;
        }).collect(Collectors.toList());

        Page<RStatPwAlarmDetailVO> resultPage = new Page<>();
        BeanUtils.copyProperties(alarmDetailListPage, resultPage);
        resultPage.setRecords(resultList);

        return resultPage;
    }
}




