package com.njcn.event.service.majornetwork.Impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
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.dto.SimpleDTO;
import com.njcn.common.pojo.exception.BusinessException;
import com.njcn.device.pms.api.DistributionMonitorClient;
import com.njcn.device.pms.api.MonitorClient;
import com.njcn.device.pms.api.PmsGeneralDeviceInfoClient;
import com.njcn.device.pms.pojo.dto.PmsGeneralDeviceDTO;
import com.njcn.device.pms.pojo.dto.PmsMonitorDTO;
import com.njcn.device.pms.pojo.dto.PwPmsMonitorDTO;
import com.njcn.device.pms.pojo.param.PmsDeviceInfoParam;
import com.njcn.device.pms.pojo.param.PmsMonitorParam;
import com.njcn.device.pms.pojo.po.Monitor;
import com.njcn.device.pq.api.GeneralDeviceInfoClient;
import com.njcn.device.pq.api.LineFeignClient;
import com.njcn.device.pq.pojo.vo.AreaLineInfoVO;
import com.njcn.event.mapper.majornetwork.RmpEventDetailMapper;
import com.njcn.event.pojo.param.UniversalFrontEndParam;
import com.njcn.event.pojo.po.RmpEventDetailPO;
import com.njcn.event.pojo.vo.AdvanceEventDetailVO;
import com.njcn.event.pojo.vo.AreaLineVO;
import com.njcn.event.pojo.vo.RmpEventDetailVO;
import com.njcn.event.pojo.vo.TransientVO;
import com.njcn.event.service.majornetwork.RmpEventDetailService;
import com.njcn.system.api.DicDataFeignClient;
import com.njcn.system.enums.DicDataTypeEnum;
import com.njcn.event.enums.EventResponseEnum;
import com.njcn.system.pojo.po.DictData;
import com.njcn.user.api.DeptFeignClient;
import com.njcn.web.factory.PageFactory;
import com.njcn.web.pojo.param.BaseParam;
import com.njcn.web.utils.RequestUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * 暂态事件明细
 *
 * @author yzh
 * @date 2022/10/12
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class RmpEventDetailServiceImpl extends ServiceImpl<RmpEventDetailMapper, RmpEventDetailPO> implements RmpEventDetailService {

    private final RmpEventDetailMapper rmpEventDetailMapper;

    private final DeptFeignClient deptFeignClient;

    private final DicDataFeignClient dicDataFeignClient;

    private final PmsGeneralDeviceInfoClient pmsGeneralDeviceInfoClient;

    private final MonitorClient monitorClient;

    private final LineFeignClient lineFeignClient;

    private final DistributionMonitorClient distributionMonitorClient;

    private final GeneralDeviceInfoClient generalDeviceInfoClient;

    /**
     * 获取暂态事件明细
     *
     * @param param 条件参数
     * @return 暂态事件明细
     */
    @Override
    public List<RmpEventDetailVO> getRmpEventDetail(UniversalFrontEndParam param) {
        // 获取当前用户的部门的子部门信息
        PmsDeviceInfoParam pmsDeviceInfoParam = new PmsDeviceInfoParam();
        pmsDeviceInfoParam.setDeptIndex(param.getId());
        pmsDeviceInfoParam.setStatisticalType(new SimpleDTO());
        List<PmsGeneralDeviceDTO> data = pmsGeneralDeviceInfoClient.getPmsDeviceInfoWithInOrg(pmsDeviceInfoParam).getData();

        if (CollectionUtil.isEmpty(data)) {
            return Collections.emptyList();
        }

        // 查询事件类型字典表
        List<DictData> eventStatisData = dicDataFeignClient.getDicDataByTypeCode(DicDataTypeEnum.EVENT_STATIS.getCode()).getData();

        // 查询监测点类别
        String monitorSort = dicDataFeignClient.getDicDataById(param.getMonitorSort().get(0)).getData().getName();

        // 取出所有监测点
        List<String> monitorIds = data.stream().flatMap(pmsGeneralDeviceDTO -> pmsGeneralDeviceDTO.getMonitorIdList().stream()).collect(Collectors.toList());
        if (CollUtil.isEmpty(monitorIds)) {
            return Collections.emptyList();
        }
        // 查询监测点信息
        PmsMonitorParam pmsMonitorParam = new PmsMonitorParam();
        if (!StringUtils.isEmpty(param.getMonitorName())) {
            pmsMonitorParam.setMonitorName(param.getMonitorName());
        }
        pmsMonitorParam.setMonitorIds(monitorIds);
        List<PmsMonitorDTO> monitorInfo = monitorClient.getMonitorInfoListByCond(pmsMonitorParam).getData();
        if (CollectionUtil.isEmpty(monitorInfo)) {
            return Collections.emptyList();
        }
        // 取出所有监测点
        List<String> monitorList = monitorInfo.stream().map(PmsMonitorDTO::getId).collect(Collectors.toList());
        // 获取暂态事件明细
        List<RmpEventDetailPO> detailsOfTransientEvents = rmpEventDetailMapper.getDetailsOfTransientEvents(monitorList, param.getEventType(), param.getStartTime(), param.getEndTime());
        if (CollectionUtil.isEmpty(detailsOfTransientEvents)) {
            return Collections.emptyList();
        }

        // 蒋监测点信息转换成map集合
        //Map<String, String> monitorInfoMap = monitorInfo.stream().collect(Collectors.toMap(PmsMonitorDTO::getId, PmsMonitorDTO::getName));
        // 将事件类型转换成map集合
        Map<String, String> eventStatisDataMap = eventStatisData.stream().collect(Collectors.toMap(DictData::getId, DictData::getName));

        // 属性赋值
        return detailsOfTransientEvents.stream().map(po -> {
            RmpEventDetailVO vo = new RmpEventDetailVO();
            BeanUtils.copyProperties(po, vo);
            for (PmsMonitorDTO dto : monitorInfo) {
                if (dto.getId().equals(po.getMeasurementPointId())) {
                    vo.setDeptName(dto.getOrgName());
                    vo.setMonitorSort(monitorSort);
                    vo.setMeasurementPointName(dto.getName());
                    vo.setEventType(eventStatisDataMap.get(po.getEventType()));
                    vo.setPowerStationName(dto.getPowerrName());
                }
            }
            return vo;
        }).collect(Collectors.toList());

    }

    /**
     * 获取暂态指标类型列表
     *
     * @return 暂态指标类型列表
     */
    @Override
    public List<DictData> getEventStatisList() {
        return dicDataFeignClient.getDicDataByTypeCode(DicDataTypeEnum.EVENT_STATIS.getCode()).getData();
    }


    @Override
    public RmpEventDetailVO getTransientDetailById(String eventId, String sysType, Integer smallType) {
        RmpEventDetailVO rmpEventDetailVO = new RmpEventDetailVO();
        RmpEventDetailPO rmpEventDetailPO = this.getById(eventId);
        if (Objects.isNull(rmpEventDetailPO)) {
            throw new BusinessException(EventResponseEnum.EVENT_NOT_FOUND);
        }
        List<String> monitorIds  = Stream.of(rmpEventDetailPO.getLineId()).collect(Collectors.toList());
        BeanUtils.copyProperties(rmpEventDetailPO, rmpEventDetailVO);
        if ("pms".equals(sysType)) {

            if(Objects.isNull(smallType) || smallType == 0){
                List<Monitor> monitorList = monitorClient.getMonitorList(monitorIds).getData();
                if (CollectionUtil.isNotEmpty(monitorList)) {
                    rmpEventDetailVO.setMeasurementPointName(monitorList.get(0).getName());
                    rmpEventDetailVO.setPowerStationName(monitorList.get(0).getPowerrName());
                }

            }else {
                //配网
                List<PwPmsMonitorDTO> pwPmsMonitorDTOList = distributionMonitorClient.pwMonitorAreaDetailInfo(monitorIds).getData();
                if (CollectionUtil.isNotEmpty(pwPmsMonitorDTOList)) {
                    rmpEventDetailVO.setMeasurementPointName(pwPmsMonitorDTOList.get(0).getMonitorName());
                    rmpEventDetailVO.setPowerStationName(pwPmsMonitorDTOList.get(0).getPowerName());
                }
            }

        } else {
            List<AreaLineInfoVO> lineRes = lineFeignClient.getBaseLineAreaInfo(monitorIds).getData();
            if (CollectionUtil.isNotEmpty(lineRes)) {
                rmpEventDetailVO.setMeasurementPointName(lineRes.get(0).getLineName());
                rmpEventDetailVO.setPowerStationName(lineRes.get(0).getSubName());
            }
        }
        return rmpEventDetailVO;
    }

    @Override
    public Page<AdvanceEventDetailVO> querySagEvents(BaseParam baseParam) {
        Page<AdvanceEventDetailVO> pageResult = new Page<>(PageFactory.getPageNum(baseParam),PageFactory.getPageSize(baseParam));
        List<String> lineIds = generalDeviceInfoClient.deptGetRunLineEvent(RequestUtil.getDeptIndex()).getData();
        if(CollUtil.isNotEmpty(lineIds)){
            LambdaQueryWrapper<RmpEventDetailPO> lambdaQueryWrapper =new LambdaQueryWrapper<>();
            lambdaQueryWrapper.isNull(RmpEventDetailPO::getEventassIndex);
            Page<RmpEventDetailPO> poPage = this.page(new Page<>(PageFactory.getPageNum(baseParam),PageFactory.getPageSize(baseParam)),lambdaQueryWrapper);

            List<String> tempLineIds = poPage.getRecords().stream().map(RmpEventDetailPO::getLineId).distinct().collect(Collectors.toList());

            List<AreaLineInfoVO> temLine = lineFeignClient.getBaseLineAreaInfo(tempLineIds).getData();
            Map<String, AreaLineInfoVO> map = temLine.stream().collect(Collectors.toMap(AreaLineInfoVO::getLineId, Function.identity()));

            List<AdvanceEventDetailVO> advanceEventDetailVOList = BeanUtil.copyToList(poPage.getRecords(),AdvanceEventDetailVO.class);
            advanceEventDetailVOList = advanceEventDetailVOList.stream().peek(item->{
                if(map.containsKey(item.getLineId())){
                    item.setGdName(map.get(item.getLineId()).getGdName());
                    item.setSubName(map.get(item.getLineId()).getSubName());
                    switch (item.getDealFlag()) {
                        case 0:
                            item.setFeatureAmplitudeFlag(EnumFlag.UNTREATED.getDescription());
                            break;
                        case 1:
                            item.setFeatureAmplitudeFlag(EnumFlag.PROCESSED.getDescription());
                            break;
                        case 2:
                            item.setFeatureAmplitudeFlag(EnumFlag.NODATA.getDescription());
                            break;
                        case 3:
                            item.setFeatureAmplitudeFlag(EnumFlag.PROCESSFAIL.getDescription());
                            break;
                        default:
                            throw new IllegalStateException("未发现的类型: " + item.getDealFlag());
                    }
                    //录波文件
                    if(Objects.nonNull(item.getFileFlag()) && item.getFileFlag() == 1){
                        item.setBoFileFlag(EnumFlag.EXIST.description);
                    }else {
                        item.setBoFileFlag(EnumFlag.ABSENCE.description);
                    }

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

            pageResult.setRecords(advanceEventDetailVOList);
            pageResult.setTotal(poPage.getTotal());
            pageResult.setPages(poPage.getPages());
            pageResult.setSize(poPage.getSize());
            pageResult.setCurrent(poPage.getCurrent());
            return pageResult;
        }
        return pageResult;
    }



    @Override
    public RmpEventDetailPO queryEventDetailByEventId(String eventId) {
        return this.getById(eventId);
    }

    /**
     *  内部枚举类：高级算法处理事件的标识描述
     */
    enum EnumFlag {
        PROCESSED(1, "计算成功"), UNTREATED(0, "未计算"), EXIST(1, "存在"), ABSENCE(0, "不存在"), NODATA(2, "无结果"), PROCESSFAIL(3, "计算失败");

        private final Integer code;
        private final String description;

        EnumFlag(Integer code, String description) {
            this.code = code;
            this.description = description;
        }

        public Integer getCode() {
            return code;
        }

        public String getDescription() {
            return description;
        }
    }

}


