package com.yuchen.saas.park.service.service.impl;

import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.yuchen.saas.park.api.dto.park.WarningDetailListQueryDTO;
import com.yuchen.saas.park.api.entity.park.PmgBatWarningInfo;
import com.yuchen.saas.park.api.entity.park.PmgBatWarningLevel;
import com.yuchen.saas.park.api.vo.park.*;
import com.yuchen.saas.park.api.vo.park.alarm.AlarmBasicInformationVO;
import com.yuchen.saas.park.api.vo.park.alarm.AlarmDetailsVO;
import com.yuchen.saas.park.api.vo.park.alarm.AlarmInformationVO;
import com.yuchen.saas.park.api.vo.park.alarm.AlarmListVO;
import com.yuchen.saas.park.service.constant.EnergyConstant;
import com.yuchen.saas.park.service.mapper.WarningLevelMapper;
import com.yuchen.saas.park.service.service.IPeopleCountService;
import com.yuchen.saas.park.service.service.IWarningInfoService;
import com.yuchen.saas.park.service.mapper.WarningInfoMapper;
import com.yuchen.saas.park.service.service.PmgBatPointLocationInfoService;
import com.yuchen.saas.park.service.util.EnergyDateUtils;
import com.yuchen.saas.park.service.util.WsDateUtil;
import org.nest.springwrap.core.mp.base.BaseServiceImpl;
import org.nest.springwrap.core.tool.utils.Func;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.support.PropertyComparator;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 *
 */
@Service
public class WarningInfoServiceImpl extends BaseServiceImpl<WarningInfoMapper, PmgBatWarningInfo> implements IWarningInfoService {

    @Resource
    private IPeopleCountService iPeopleCountService;

    @Resource
    private PmgBatPointLocationInfoService locationInfoService;

    @Autowired
    private WarningLevelMapper warningLevelMapper;

    @Override
    public Map<String, Object> getTotal() {


        Map<String, Object> returnMap = new HashMap<String, Object>();
        List<WarningEveryDayStatistics> returnR = baseMapper.getTotal();

        if (Func.isNotEmpty(returnR) && returnR.size() > 0) {
            List<String> countArr = new ArrayList<String>();
            List<String> timeArr = new ArrayList<String>();
            for (WarningEveryDayStatistics getVo : returnR) {
                countArr.add(getVo.getCount());
                timeArr.add(getVo.getTotalData());
            }
            returnMap.put("countArr", countArr);
            returnMap.put("timeArr", timeArr);
        }
        return returnMap;
    }

    @Override
    public Map<String, Long> getWarningHandlerResult() {

        // 不应该查询记录，再用size() ,  应该直接查询 count
//        List<PmgBatWarningInfo> pmgBatWarningInfosIsHandling = baseMapper.selectList(Wrappers.<PmgBatWarningInfo>query().lambda().eq(PmgBatWarningInfo::getIsHandling, "1"));
//        List<PmgBatWarningInfo> pmgBatWarningInfos = baseMapper.selectList(Wrappers.<PmgBatWarningInfo>query().lambda().eq(PmgBatWarningInfo::getIsHandling, "0"));
//        List<PmgBatWarningInfo> pmgBatWarningInfos1 = baseMapper.selectList(Wrappers.<PmgBatWarningInfo>query().lambda().eq(PmgBatWarningInfo::getProductKey, "384rQ13KlTUvrx3q"));
        AbnormalPeopleVo abnormalPeopleVo = iPeopleCountService.getAbnormalPeople();
        Map<String, Long> map = new HashMap<>();
        map.put("isHandling", Long.valueOf(baseMapper.selectCount(Wrappers.<PmgBatWarningInfo>query().lambda().eq(PmgBatWarningInfo::getIsHandling, "1"))));
        map.put("unHandling", Long.valueOf(baseMapper.selectCount(Wrappers.<PmgBatWarningInfo>query().lambda().eq(PmgBatWarningInfo::getIsHandling, "0"))));
        map.put("abnormalPeople", abnormalPeopleVo.getCount());
        map.put("monitorWarning", Long.valueOf(baseMapper.selectCount(Wrappers.<PmgBatWarningInfo>query().lambda().eq(PmgBatWarningInfo::getProductKey, "384rQ13KlTUvrx3q"))));
        return map;
    }

    @Override
    public Map<String, Long> getWarningHandlerResult(String parkId) {
        List<PmgBatWarningInfo> pmgBatWarningInfosIsHandling = baseMapper.selectList(Wrappers.<PmgBatWarningInfo>query().lambda().eq(PmgBatWarningInfo::getIsHandling, "1").eq(PmgBatWarningInfo::getParkId, parkId));
        List<PmgBatWarningInfo> pmgBatWarningInfos = baseMapper.selectList(Wrappers.<PmgBatWarningInfo>query().lambda().eq(PmgBatWarningInfo::getIsHandling, "0").eq(PmgBatWarningInfo::getParkId, parkId));
        List<PmgBatWarningInfo> pmgBatWarningInfos1 = baseMapper.selectList(Wrappers.<PmgBatWarningInfo>query().lambda().eq(PmgBatWarningInfo::getProductKey, "384rQ13KlTUvrx3q").eq(PmgBatWarningInfo::getParkId, parkId));
        AbnormalPeopleVo abnormalPeopleVo = iPeopleCountService.getAbnormalPeopleByParkId(parkId);
        Map<String, Long> map = new HashMap<>();
        map.put("isHandling", (long) pmgBatWarningInfosIsHandling.size());
        map.put("unHandling", (long) pmgBatWarningInfos.size());
        map.put("abnormalPeople", abnormalPeopleVo.getCount());
        map.put("monitorWarning", (long) pmgBatWarningInfos1.size());
        return map;
    }

    @Override
    public List<WarningDeviceVo> getWarningDevice() {
        List<WarningDeviceVo> warningDeviceVos = baseMapper.getWarningDevice();
        return warningDeviceVos;
    }


    @Override
    public Map<String, Object> getWarningByLevel() {

        // 定义警告级别集合
        List<Integer> level1 = new ArrayList<Integer>();
        List<Integer> level2 = new ArrayList<Integer>();
        List<Integer> level3 = new ArrayList<Integer>();
        List<Integer> level4 = new ArrayList<Integer>();

        List<Object> countList = new ArrayList<Object>();
        // leve 1
        List<WarningLevelCountVo> warningLeve1 = baseMapper.getWarningByLevel("1");
        if (Func.isNotEmpty(warningLeve1) && warningLeve1.size() > 0) {
            for (WarningLevelCountVo levelCountVo : warningLeve1) {
                level1.add(levelCountVo.getCount());
            }
        }
        countList.add(level1);
        // leve 2
        List<WarningLevelCountVo> warningLeve2 = baseMapper.getWarningByLevel("2");
        if (Func.isNotEmpty(warningLeve2) && warningLeve2.size() > 0) {
            for (WarningLevelCountVo levelCountVo : warningLeve2) {
                level2.add(levelCountVo.getCount());
            }
        }
        countList.add(level2);
        // leve 3
        List<WarningLevelCountVo> warningLeve3 = baseMapper.getWarningByLevel("3");
        if (Func.isNotEmpty(warningLeve3) && warningLeve3.size() > 0) {
            for (WarningLevelCountVo levelCountVo : warningLeve3) {
                level3.add(levelCountVo.getCount());
            }
        }
        countList.add(level3);
        // leve 4
        List<WarningLevelCountVo> warningLeve4 = baseMapper.getWarningByLevel("4");
        if (Func.isNotEmpty(warningLeve4) && warningLeve4.size() > 0) {
            for (WarningLevelCountVo levelCountVo : warningLeve4) {
                level4.add(levelCountVo.getCount());
            }
        }
        countList.add(level4);
        Map<String, Object> map1 = new HashMap<String, Object>();
        map1.put("countList", countList);
        return map1;
    }

    @Override
    public Map<String, Object> getWarningByLevel(String parkId) {
        // 定义警告级别集合
        List<Integer> level1 = new ArrayList<Integer>();
        List<Integer> level2 = new ArrayList<Integer>();
        List<Integer> level3 = new ArrayList<Integer>();
        List<Integer> level4 = new ArrayList<Integer>();

        List<Object> countList = new ArrayList<Object>();
        // leve 1
        List<WarningLevelCountVo> warningLeve1 = baseMapper.getWarningByLevelAndParkId("1", parkId);
        if (Func.isNotEmpty(warningLeve1) && warningLeve1.size() > 0) {
            for (WarningLevelCountVo levelCountVo : warningLeve1) {
                level1.add(levelCountVo.getCount());
            }
        }
        countList.add(level1);
        // leve 2
        List<WarningLevelCountVo> warningLeve2 = baseMapper.getWarningByLevelAndParkId("2", parkId);
        if (Func.isNotEmpty(warningLeve2) && warningLeve2.size() > 0) {
            for (WarningLevelCountVo levelCountVo : warningLeve2) {
                level2.add(levelCountVo.getCount());
            }
        }
        countList.add(level2);
        // leve 3
        List<WarningLevelCountVo> warningLeve3 = baseMapper.getWarningByLevelAndParkId("3", parkId);
        if (Func.isNotEmpty(warningLeve3) && warningLeve3.size() > 0) {
            for (WarningLevelCountVo levelCountVo : warningLeve3) {
                level3.add(levelCountVo.getCount());
            }
        }
        countList.add(level3);
        // leve 4
        List<WarningLevelCountVo> warningLeve4 = baseMapper.getWarningByLevelAndParkId("4", parkId);
        if (Func.isNotEmpty(warningLeve4) && warningLeve4.size() > 0) {
            for (WarningLevelCountVo levelCountVo : warningLeve4) {
                level4.add(levelCountVo.getCount());
            }
        }
        countList.add(level4);
        Map<String, Object> map1 = new HashMap<String, Object>();
        map1.put("countList", countList);
        return map1;
    }

    @Override
    public List<PmgBatWarningInfo> getAllMonitorWarning() {
        List<PmgBatWarningInfo> pmgBatWarningInfos = baseMapper.selectList(Wrappers.<PmgBatWarningInfo>query().lambda().eq(PmgBatWarningInfo::getProductKey, "384rQ13KlTUvrx3q"));
        return pmgBatWarningInfos;
    }

    @Override
    public AlarmBasicInformationVO getBasicInformation(Long parkId, Long buildingId, Long floorId) {

        AlarmBasicInformationVO alarmBasicInformationVO = new AlarmBasicInformationVO();
        alarmBasicInformationVO.setAlarmNumberNew(getWarningNumberNew(WsDateUtil.getBeginTimeMillisDay(System.currentTimeMillis(), 0),
                WsDateUtil.getEndTimeMillisDay(System.currentTimeMillis(), 0), parkId, buildingId, floorId));
        alarmBasicInformationVO.setAlarmNumberHandled(33);
        alarmBasicInformationVO.setAlarmNumberPending(10);
        alarmBasicInformationVO.setAlarmNumberInHand(0);
        return alarmBasicInformationVO;
    }

    @Override
    public AlarmInformationVO getAlarmInformationToday(Long parkId, Long buildingId, Long floorId) {

        AlarmInformationVO alarmInformationVO = new AlarmInformationVO();
        alarmInformationVO.setAlarmNumberNew(getWarningNumberNew(WsDateUtil.getBeginTimeMillisDay(System.currentTimeMillis(), 0),
                WsDateUtil.getEndTimeMillisDay(System.currentTimeMillis(), 0), parkId, buildingId, floorId));
        alarmInformationVO.setAlarmNumberHandled(6);
        // 获取现在几点
        int hourNow = EnergyDateUtils.getHourOfToday();
        List<GetEnvironmentInfo> listNew = new ArrayList<>();
        List<GetEnvironmentInfo> listHandled = new ArrayList<>();
        for (int i = 1; i <= hourNow + 1; i++) {
            // 小时新增告警数
            GetEnvironmentInfo infoNew = new GetEnvironmentInfo();
            infoNew.setKey(String.valueOf(i));
            infoNew.setValue(String.valueOf(i + 3));
            listNew.add(infoNew);
            // 小时已处理告警数
            GetEnvironmentInfo infoHandled = new GetEnvironmentInfo();
            infoHandled.setKey(String.valueOf(i));
            infoHandled.setValue(String.valueOf(i + 2));
            listHandled.add(infoHandled);
        }
        alarmInformationVO.setAlarmNumberNewTrends(listNew);
        alarmInformationVO.setAlarmNumberHandledTrends(listHandled);
        return alarmInformationVO;
    }

    @Override
    public AlarmInformationVO getAlarmInformationMonth(Long parkId, Long buildingId, Long floorId) {

        AlarmInformationVO alarmInformationVO = new AlarmInformationVO();

        alarmInformationVO.setAlarmNumberNew(
                getWarningNumberNew(WsDateUtil.getBeginTimeMillisMonth(System.currentTimeMillis(), 0),
                        WsDateUtil.getEndTimeMillisMonth(System.currentTimeMillis(), 0), parkId, buildingId, floorId));
        alarmInformationVO.setAlarmNumberHandled(88);
        List<GetEnvironmentInfo> listNew = new ArrayList<>();
        List<GetEnvironmentInfo> listHandled = new ArrayList<>();

        //获取今日几号
        int nowDay = WsDateUtil.getDayOfCurrentMonth();
        //获取本月1号日期
        String beginDateMonth = WsDateUtil.getBeginDateOfMonth(0);
        for (int i = 0; i < nowDay; i++) {
            String offsetDate = WsDateUtil.offsetDay(beginDateMonth, i);
            //没有的天给0
            if (!listNew.stream().anyMatch(e -> offsetDate.equals(e.getKey()))) {
                GetEnvironmentInfo info = new GetEnvironmentInfo();
                info.setKey(offsetDate);
                info.setValue(String.valueOf(i + 5));
                listNew.add(info);
            }
            if (!listHandled.stream().anyMatch(e -> offsetDate.equals(e.getKey()))) {
                GetEnvironmentInfo info = new GetEnvironmentInfo();
                info.setKey(offsetDate);
                info.setValue(String.valueOf(i + 6));
                listHandled.add(info);
            }
        }

        alarmInformationVO.setAlarmNumberNewTrends(listNew);
        alarmInformationVO.setAlarmNumberHandledTrends(listHandled);
        return alarmInformationVO;
    }

    @Override
    public List<GetEnvironmentInfo> getAlarmStatusDistributionToday(Long parkId, Long buildingId, Long floorId) {

        List<GetEnvironmentInfo> list = new LinkedList<>();
        AlarmBasicInformationVO alarmBasicInformationVO = new AlarmBasicInformationVO();
        GetEnvironmentInfo info1 = new GetEnvironmentInfo();
        info1.setKey("待处理");
        info1.setValue("11");
        GetEnvironmentInfo info2 = new GetEnvironmentInfo();
        info2.setKey("处理中");
        info2.setValue("18");
        GetEnvironmentInfo info3 = new GetEnvironmentInfo();
        info3.setKey("新增");
        info3.setValue(String.valueOf(getWarningNumberNew(WsDateUtil.getBeginTimeMillisDay(System.currentTimeMillis(), 0),
                WsDateUtil.getEndTimeMillisDay(System.currentTimeMillis(), 0), parkId, buildingId, floorId)));
        GetEnvironmentInfo info4 = new GetEnvironmentInfo();
        info4.setKey("已处理");
        info4.setValue("11");

        list.add(info1);
        list.add(info2);
        list.add(info3);
        list.add(info4);

        return list;
    }

    @Override
    public List<GetEnvironmentInfo> getAlarmStatusDistributionMonth(Long parkId, Long buildingId, Long floorId) {

        List<GetEnvironmentInfo> list = new LinkedList<>();
        AlarmBasicInformationVO alarmBasicInformationVO = new AlarmBasicInformationVO();
        GetEnvironmentInfo info1 = new GetEnvironmentInfo();
        info1.setKey("待处理");
        info1.setValue("22");
        GetEnvironmentInfo info2 = new GetEnvironmentInfo();
        info2.setKey("处理中");
        info2.setValue("33");
        GetEnvironmentInfo info3 = new GetEnvironmentInfo();
        info3.setKey("新增");
        info3.setValue(String.valueOf(getWarningNumberNew(WsDateUtil.getBeginTimeMillisMonth(System.currentTimeMillis(),
                0), WsDateUtil.getEndTimeMillisMonth(System.currentTimeMillis(), 0), parkId, buildingId, floorId)));
        GetEnvironmentInfo info4 = new GetEnvironmentInfo();
        info4.setKey("已处理");
        info4.setValue("24");

        list.add(info1);
        list.add(info2);
        list.add(info3);
        list.add(info4);

        return list;
    }

    @Override
    public List<GetEnvironmentInfo> getAlarmDeviceTypeDistributionToday(Long parkId, Long buildingId, Long floorId) {
        List<GetEnvironmentInfo> list = new ArrayList<>();
        GetEnvironmentInfo info1 = new GetEnvironmentInfo();
        info1.setKey("监控");
        info1.setValue("22");
        GetEnvironmentInfo info2 = new GetEnvironmentInfo();
        info2.setKey("烟感");
        info2.setValue("8");
        GetEnvironmentInfo info3 = new GetEnvironmentInfo();
        info3.setKey("雷达");
        info3.setValue("46");
        GetEnvironmentInfo info4 = new GetEnvironmentInfo();
        info4.setKey("红外报警");
        info4.setValue("66");
        GetEnvironmentInfo info5 = new GetEnvironmentInfo();
        info5.setKey("门磁传感");
        info5.setValue("44");
        GetEnvironmentInfo info6 = new GetEnvironmentInfo();
        info6.setKey("位移传感");
        info6.setValue("88");

        list.add(info1);
        list.add(info2);
        list.add(info3);
        list.add(info4);
        list.add(info5);
        list.add(info6);
        return list;
    }

    @Override
    public List<GetEnvironmentInfo> getAlarmDeviceTypeDistributionMonth(Long parkId, Long buildingId, Long floorId) {

        List<GetEnvironmentInfo> list = new ArrayList<>();
        GetEnvironmentInfo info1 = new GetEnvironmentInfo();
        info1.setKey("监控");
        info1.setValue("22");
        GetEnvironmentInfo info2 = new GetEnvironmentInfo();
        info2.setKey("烟感");
        info2.setValue("8");
        GetEnvironmentInfo info3 = new GetEnvironmentInfo();
        info3.setKey("雷达");
        info3.setValue("46");
        GetEnvironmentInfo info4 = new GetEnvironmentInfo();
        info4.setKey("红外报警");
        info4.setValue("66");
        GetEnvironmentInfo info5 = new GetEnvironmentInfo();
        info5.setKey("门磁传感");
        info5.setValue("44");
        GetEnvironmentInfo info6 = new GetEnvironmentInfo();
        info6.setKey("位移传感");
        info6.setValue("88");

        list.add(info1);
        list.add(info2);
        list.add(info3);
        list.add(info4);
        list.add(info5);
        list.add(info6);
        return list;
    }

    @Override
    public List<GetEnvironmentInfo> getAlarmHandlingTimeDistributionToday(Long parkId, Long buildingId, Long floorId) {

        List<GetEnvironmentInfo> list = new ArrayList<>();
        GetEnvironmentInfo info1 = new GetEnvironmentInfo();
        info1.setKey("8h以内");
        info1.setValue("11");

        GetEnvironmentInfo info2 = new GetEnvironmentInfo();
        info2.setKey("24h以内");
        info2.setValue("22");

        GetEnvironmentInfo info3 = new GetEnvironmentInfo();
        info3.setKey("48h以内");
        info3.setValue("46");

        GetEnvironmentInfo info4 = new GetEnvironmentInfo();
        info4.setKey("48h以上");
        info4.setValue("110");

        list.add(info1);
        list.add(info2);
        list.add(info3);
        list.add(info4);

        return list;
    }

    @Override
    public List<GetEnvironmentInfo> getAlarmHandlingTimeDistributionMonth(Long parkId, Long buildingId, Long floorId) {
        List<GetEnvironmentInfo> list = new ArrayList<>();
        GetEnvironmentInfo info1 = new GetEnvironmentInfo();
        info1.setKey("8h以内");
        info1.setValue("11");

        GetEnvironmentInfo info2 = new GetEnvironmentInfo();
        info2.setKey("24h以内");
        info2.setValue("22");

        GetEnvironmentInfo info3 = new GetEnvironmentInfo();
        info3.setKey("48h以内");
        info3.setValue("46");

        GetEnvironmentInfo info4 = new GetEnvironmentInfo();
        info4.setKey("48h以上");
        info4.setValue("110");

        list.add(info1);
        list.add(info2);
        list.add(info3);
        list.add(info4);

        return list;
    }

    @Override
    public AlarmDetailsVO getAlarmDetails(Long parkId, Long buildingId, Long floorId) {

        AlarmDetailsVO alarmDetailsVO = new AlarmDetailsVO();
        AlarmInformationVO alarmInformationToday = getAlarmInformationToday(parkId, buildingId, floorId);
        // 今日新增告警数
        alarmDetailsVO.setAlarmNumberNewToday(alarmInformationToday.getAlarmNumberNew());
        // 今日已处理告警数
        alarmDetailsVO.setAlarmNumberHandledToday(alarmInformationToday.getAlarmNumberHandled());
        // 今日新增告警趋势
        alarmDetailsVO.setAlarmNumberNewTrendsToday(alarmInformationToday.getAlarmNumberNewTrends());
        // 今日已处理告警趋势
        alarmDetailsVO.setAlarmNumberHandledTrendsToday(alarmInformationToday.getAlarmNumberHandledTrends());

        AlarmInformationVO alarmInformationThisMonth = getAlarmInformationMonth(parkId, buildingId, floorId);
        // 本月新增告警数
        alarmDetailsVO.setAlarmNumberNewThisMonth(alarmInformationThisMonth.getAlarmNumberNew());
        // 本月已处理告警数
        alarmDetailsVO.setAlarmNumberHandledThisMonth(alarmInformationThisMonth.getAlarmNumberHandled());
        // 本月新增告警趋势
        alarmDetailsVO.setAlarmNumberNewTrendsThisMonth(alarmInformationThisMonth.getAlarmNumberNewTrends());
        // 本月已处理告警趋势
        alarmDetailsVO.setAlarmNumberHandledTrendsThisMonth(alarmInformationThisMonth.getAlarmNumberHandledTrends());

        List<GetEnvironmentInfo> alarmStatusDistributionToday = getAlarmStatusDistributionToday(parkId, buildingId, floorId);
        // 统计今日告警状态分布
        alarmDetailsVO.setAlarmStatusDistributionToday(alarmStatusDistributionToday);
        // 统计今日告警状态分布的总数
        int totalByStatusToday = Integer.parseInt(alarmStatusDistributionToday.stream()
                .reduce(
                        (x, y) -> new GetEnvironmentInfo(null,
                                String.valueOf(Integer.parseInt(x.getValue()) + Integer.parseInt(y.getValue())), null))
                .orElse(new GetEnvironmentInfo(null, "0", null)).getValue());
        alarmDetailsVO.setTotalByStatusToday(totalByStatusToday);

        List<GetEnvironmentInfo> alarmStatusDistributionThisMonth =
                getAlarmStatusDistributionMonth(parkId, buildingId, floorId);
        // 统计本月告警状态分布
        alarmDetailsVO.setAlarmStatusDistributionThisMonth(alarmStatusDistributionThisMonth);
        // 统计本月告警状态分布的总数
        int totalByStatusThisMonth = Integer.parseInt(alarmStatusDistributionThisMonth.stream()
                .reduce(
                        (x, y) -> new GetEnvironmentInfo(null,
                                String.valueOf(Integer.parseInt(x.getValue()) + Integer.parseInt(y.getValue())), null))
                .orElse(new GetEnvironmentInfo(null, "0", null)).getValue());
        alarmDetailsVO.setTotalByStatusThisMonth(totalByStatusThisMonth);

        List<GetEnvironmentInfo> alarmDeviceDistributionToday =
                getAlarmDeviceTypeDistributionToday(parkId, buildingId, floorId);
        // 统计今日告警设备类型分布
        alarmDetailsVO.setAlarmDeviceDistributionToday(alarmDeviceDistributionToday);
        // 统计今日告警设备类型分布的总数
        int totalByDeviceToday = Integer.parseInt(alarmDeviceDistributionToday.stream()
                .reduce(
                        (x, y) -> new GetEnvironmentInfo(null,
                                String.valueOf(Integer.parseInt(x.getValue()) + Integer.parseInt(y.getValue())), null))
                .orElse(new GetEnvironmentInfo(null, "0", null)).getValue());
        alarmDetailsVO.setTotalByDeviceToday(totalByDeviceToday);

        List<GetEnvironmentInfo> alarmDeviceDistributionThisMonth =
                getAlarmDeviceTypeDistributionMonth(parkId, buildingId, floorId);
        // 统计本月告警设备类型的分布
        alarmDetailsVO.setAlarmDeviceDistributionThisMonth(alarmDeviceDistributionThisMonth);
        // 统计本月告警设备类型分布的总数
        int totalByDeviceThisMonth = Integer.parseInt(alarmDeviceDistributionThisMonth.stream()
                .reduce(
                        (x, y) -> new GetEnvironmentInfo(null,
                                String.valueOf(Integer.parseInt(x.getValue()) + Integer.parseInt(y.getValue())), null))
                .orElse(new GetEnvironmentInfo(null, "0", null)).getValue());
        alarmDetailsVO.setTotalByDeviceThisMonth(totalByDeviceThisMonth);

        List<GetEnvironmentInfo> AlarmHandlingTimeDistributionToday =
                getAlarmHandlingTimeDistributionToday(parkId, buildingId, floorId);
        // 统计今日处理时长分布
        alarmDetailsVO.setAlarmHandlingTimeDistributionToday(AlarmHandlingTimeDistributionToday);
        // 统计今日处理时长分布的总数
        int totalByHandlingTimeToday = Integer.parseInt(AlarmHandlingTimeDistributionToday.stream()
                .reduce(
                        (x, y) -> new GetEnvironmentInfo(null,
                                String.valueOf(Integer.parseInt(x.getValue()) + Integer.parseInt(y.getValue())), null))
                .orElse(new GetEnvironmentInfo(null, "0", null)).getValue());
        alarmDetailsVO.setTotalByHandlingTimeToday(totalByHandlingTimeToday);

        List<GetEnvironmentInfo> AlarmHandlingTimeDistributionThisMonth =
                getAlarmHandlingTimeDistributionMonth(parkId, buildingId, floorId);
        // 统计本月告警时长分布
        alarmDetailsVO.setAlarmHandlingTimeDistributionThisMonth(AlarmHandlingTimeDistributionThisMonth);
        // 统计本月告警处理时长分布的总数
        int totalByHandlingTimeThisMonth = Integer.parseInt(AlarmHandlingTimeDistributionThisMonth.stream()
                .reduce(
                        (x, y) -> new GetEnvironmentInfo(null,
                                String.valueOf(Integer.parseInt(x.getValue()) + Integer.parseInt(y.getValue())), null))
                .orElse(new GetEnvironmentInfo(null, "0", null)).getValue());
        alarmDetailsVO.setTotalByHandlingTimeThisMonth(totalByHandlingTimeThisMonth);

        return alarmDetailsVO;
    }

    @Override
    public FireStatInfoVO getFireStatInfo(Long parkId, Long buildingId, Long floorId) {

        FireStatInfoVO fireStatInfoVO = new FireStatInfoVO();
        //获取安防所有设备productName
        List<String> productNameList = locationInfoService.getProductNameList(parkId, buildingId, floorId, null, "2");
        //目前直接给值
        productNameList.add("8gF31iKdiJe0NW31");
        //今日火警次数
        int numberToday = 0;
        //获取今日日期
        String dateToday = EnergyDateUtils.getDateToday();
        //获取本月月份
        String dateMonth = EnergyDateUtils.getDateMonth();
        //本月火警次数
        int numberMonth = 0;
        if (Func.isNotEmpty(productNameList)) {
            numberToday = baseMapper.getFireAlarmNumberTodayOrMonth(productNameList, EnergyConstant.TOP_TODAY);
            numberMonth = baseMapper.getFireAlarmNumberTodayOrMonth(productNameList, EnergyConstant.TOP_MONTH);
        }
        fireStatInfoVO.setNumberToday(numberToday);
        fireStatInfoVO.setNumberMonth(numberMonth);

        //今日火警发生趋势
        List<GetEnvironmentInfo> listToday = new ArrayList<>();
        //本月火警发生趋势
        List<GetEnvironmentInfo> listMonth = new ArrayList<>();
        //获取现在几点
        int nowHour = EnergyDateUtils.getHourOfToday();
        if (Func.isNotEmpty(productNameList)) {
            listToday = baseMapper.getFireAlarmTrendsDay(productNameList, dateToday);
            listMonth = baseMapper.getFireAlarmTrendsMonth(productNameList, dateMonth);
        }
        //今日火警发生趋势 没有的小时给0
        for (int i = 1; i <= nowHour + 1; i++) {
            String index = String.valueOf(i);
            if (!listToday.stream().anyMatch(e -> index.equals(e.getKey()))) {
                GetEnvironmentInfo info = new GetEnvironmentInfo();
                info.setKey(index);
                info.setValue("0");
                listToday.add(info);
            }
        }
        fireStatInfoVO.setFireTrendsToday(listToday);
        //本月火警发生趋势 没有的天给0
        //获取今日几号
        int nowDay = WsDateUtil.getDayOfCurrentMonth();
        //获取本月1号日期
        String beginDateMonth = WsDateUtil.getBeginDateOfMonth(0);
        for (int i = 0; i < nowDay; i++) {
            String offsetDate = WsDateUtil.offsetDay(beginDateMonth, i);
            if (!listMonth.stream().anyMatch(e -> offsetDate.equals(e.getKey()))) {
                GetEnvironmentInfo info = new GetEnvironmentInfo();
                info.setKey(offsetDate);
                info.setValue("0");
                listMonth.add(info);
            }
        }
        //升序排序
        listToday.sort((a, b) -> Integer.parseInt(a.getKey()) - Integer.parseInt(b.getKey()));
        listMonth.sort((a, b) -> DateUtil.parse(a.getKey()).compareTo(DateUtil.parse(b.getKey())));

        //排序
        listMonth.sort(Comparator.comparing(GetEnvironmentInfo::getKey));
        fireStatInfoVO.setFireTrendsMonth(listMonth);

        return fireStatInfoVO;
    }

    @Override
    public List<FireListVO> getFireList(Long parkId, Long buildingId, Long floorId) {

        List<FireListVO> rspList = new ArrayList<>();
        //获取安防所有设备productName
        List<String> productNameList = locationInfoService.getProductNameList(parkId, buildingId, floorId, null, "2");
        //目前直接给值
        productNameList.add("8gF31iKdiJe0NW31");
        if (Func.isNotEmpty(productNameList)) {
            rspList = baseMapper.getFireList(productNameList);
        }
        return rspList;
    }

    @Override
    public List<AlarmListVO> getAlarmListByCategoryCode(Long parkId, Long buildingId, Long floorId,
                                                        String categoryCode) {
        List<AlarmListVO> rspList = new LinkedList<>();
        // 根据categoryCode获取productKey集合
        //List<String> productKeyList = locationInfoService.getProductKeyList(parkId, buildingId, floorId, null,
        //        categoryCode);
        List<String> productNameList = locationInfoService.getProductNameList(parkId, buildingId, floorId, null,
                categoryCode);
        if (Func.isNotEmpty(productNameList)) {
            // 获取告警列表
            LambdaQueryWrapper<PmgBatWarningInfo> lambdaQueryWrapper = new LambdaQueryWrapper();
            lambdaQueryWrapper.in(PmgBatWarningInfo::getDeviceName, productNameList);
            lambdaQueryWrapper.orderByDesc(PmgBatWarningInfo::getCreateTime);
            lambdaQueryWrapper.last("limit 30");
            List<PmgBatWarningInfo> warningList = this.list(lambdaQueryWrapper);
            warningList.forEach(w -> {
                AlarmListVO alarmListVO = new AlarmListVO();
                alarmListVO.setId(w.getId());
                alarmListVO.setName(w.getName());
                alarmListVO.setCreateTime(DateUtil.format(w.getCreateTime(), "yyyy-MM-dd HH:mm:ss"));
                alarmListVO.setSetPosition(w.getSetPosition());
                alarmListVO.setLevel(w.getLevel());
                alarmListVO.setIsHandling(w.getIsHandling());
                alarmListVO.setIsDeleted(w.getIsDeleted());
                rspList.add(alarmListVO);
            });
        }

        return rspList;
    }

    public Integer getWarningNumberNew(Long beginTimestamp, Long endTimestamp,
                                       Long parkId, Long buildingId, Long floorId) {
        //获取所有设备信息
        List<PmgEquipmentPointVo> deviceList = locationInfoService.selectByAllEquipmentPoint(parkId, buildingId, floorId, null);
        //获取所有设备productName
        int alarmNumMonth = 0;
        List<String> productNameList =
                deviceList.stream().map(PmgEquipmentPointVo::getDeviceName).collect(Collectors.toList());
        if (Func.isNotEmpty(productNameList)) {
            alarmNumMonth = baseMapper.getWarningNumberBetweenTimestamp(productNameList, beginTimestamp, endTimestamp);
        }
        return alarmNumMonth;
    }

    /**
     * 告警信息详情查询
     * @param query
     * @return
     */
    @Override
    public IPage<WarningDetailListVo> getWarningDetailList(WarningDetailListQueryDTO query){
        PageHelper.startPage(query.getCurrent(), query.getSize());
        List<WarningDetailListVo> warningDetailList = getBaseMapper().getWarningDetailList(query);
        PageInfo<WarningDetailListVo> pageInfo=new PageInfo<WarningDetailListVo>(warningDetailList);
        IPage<WarningDetailListVo> iPage=new Page<WarningDetailListVo>();
        iPage.setRecords(pageInfo.getList());
        iPage.setCurrent(pageInfo.getPageNum());
        iPage.setSize(pageInfo.getPageSize());
        iPage.setTotal(pageInfo.getTotal());
        iPage.setPages(pageInfo.getPages());
        return iPage;
    }

    @Override
    public List<WarningDetailCountByLevelVo> countWarningDetailByLevel(WarningDetailListQueryDTO query){
        //根据告警等级分组统计
        QueryWrapper<PmgBatWarningInfo> queryWrapper=new QueryWrapper<>();
        queryWrapper.select("level,level_name,count(id) as count");
        queryWrapper.lambda()
                .eq(PmgBatWarningInfo::getParkId,query.getParkId())
                .eq(query.getLevel()!=null,PmgBatWarningInfo::getLevel,query.getLevel())
                .eq(query.getStatus()!=null,PmgBatWarningInfo::getStatus,query.getStatus())
                .eq(Func.isNotBlank(query.getIdentity()),PmgBatWarningInfo::getIdentity,query.getIdentity())
                .ge(query.getStartTime()!=null,PmgBatWarningInfo::getEventTime,query.getStartTime())
                .le(query.getEndTime()!=null,PmgBatWarningInfo::getEventTime,query.getEndTime())
                .orderByAsc(PmgBatWarningInfo::getLevel)
                .groupBy(PmgBatWarningInfo::getLevel,PmgBatWarningInfo::getLevelName);
        List<Map<String, Object>> maps = getBaseMapper().selectMaps(queryWrapper);

        //查询告警信息
        QueryWrapper<PmgBatWarningLevel> levelQueryWrapper=new QueryWrapper<>();
        levelQueryWrapper.lambda().eq(PmgBatWarningLevel::getParkId,query.getParkId())
                .orderByAsc(PmgBatWarningLevel::getLevel);
        List<PmgBatWarningLevel> levels=warningLevelMapper.selectList(levelQueryWrapper);

        //组装结果
        List<WarningDetailCountByLevelVo> counts=new ArrayList<>();
        if(maps!=null&&maps.size()>0){
            for(Map<String,Object> map:maps){
                WarningDetailCountByLevelVo levelVo=new WarningDetailCountByLevelVo();
                levelVo.setLevel(map.get("level")==null?-1:Integer.parseInt(map.get("level").toString()));
                levelVo.setLevelName(map.get("level_name")==null?"未定义":map.get("level_name").toString());
                levelVo.setCount(Integer.parseInt(map.get("count").toString()));
                counts.add(levelVo);
            }
            if(levels!=null&&levels.size()>0){
                for(PmgBatWarningLevel level:levels){
                    boolean flag=false;
                    for(WarningDetailCountByLevelVo levelVo:counts){
                        if(level.getLevel()==levelVo.getLevel()){
                            flag=true;
                            break;
                        }
                    }
                    if(!flag){
                        WarningDetailCountByLevelVo levelVo=new WarningDetailCountByLevelVo();
                        levelVo.setLevel(level.getLevel());
                        levelVo.setLevelName(level.getName());
                        levelVo.setCount(0);
                        counts.add(levelVo);
                    }
                }
                //列表重排序
//                ListUtil.sort(counts,new PropertyComparator<>())
                counts = ListUtil.sortByProperty(counts, "level");
            }
            return counts;
        }else {
            if(levels!=null&&levels.size()>0){
                for(PmgBatWarningLevel level:levels){
                    WarningDetailCountByLevelVo levelVo=new WarningDetailCountByLevelVo();
                    levelVo.setLevel(level.getLevel());
                    levelVo.setLevelName(level.getName());
                    levelVo.setCount(0);
                    counts.add(levelVo);
                }
            }
            return counts;
        }
    }

    @Override
    public List<WarningDetailCountByStatusVo> countTodayWarningDetailByStatus(Long parkId){
        DateTime beginOfDay = DateUtil.beginOfDay(DateTime.now());
        DateTime endOfDay = DateUtil.endOfDay(DateTime.now());
        //根据告警等级分组统计
        QueryWrapper<PmgBatWarningInfo> queryWrapper=new QueryWrapper<>();
        queryWrapper.select("status,count(id) as count");
        queryWrapper.lambda()
                .eq(PmgBatWarningInfo::getParkId,parkId)
                .ge(PmgBatWarningInfo::getEventTime,beginOfDay.getTime())
                .le(PmgBatWarningInfo::getEventTime,endOfDay.getTime())
                .groupBy(PmgBatWarningInfo::getStatus);
        List<Map<String, Object>> maps = getBaseMapper().selectMaps(queryWrapper);


        //组装结果
        List<WarningDetailCountByStatusVo> counts=new ArrayList<>();
        if(maps!=null&&maps.size()>0){
            for(Map<String,Object> map:maps){
                WarningDetailCountByStatusVo statusVo=new WarningDetailCountByStatusVo();
                statusVo.setStatus(Integer.parseInt(map.get("status").toString()));
                statusVo.setCount(Integer.parseInt(map.get("count").toString()));
                counts.add(statusVo);
            }
            return counts;
        }else {
            return new ArrayList<>();
        }
    }
}

