package com.gyee.alarm.controller;

import com.gyee.alarm.model.vo.*;
import com.gyee.alarm.service.AlarmHistoryService;

import com.gyee.alarm.util.StringUtils;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;


@Slf4j
@RestController
@RequestMapping("/alarm")
@CrossOrigin
public class AlarmHistoryNXFController {


    Logger logger = LogManager.getLogger(AlarmHistoryNXFController.class);

    @Resource
    private AlarmHistoryService alarmHistoryService;


    @PostMapping(value = "/history/updateAlarms")
    @ApiOperation(value = "确认报警", notes = "确认报警")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "tagLs", value = "需要确认的报警", required = true, dataType = "string", paramType = "query")
    })
    public AjaxResult updateAlarms(@RequestBody List<AlarmTag> tagLs) throws Exception {


        alarmHistoryService.updateAlarms(tagLs);
        return AjaxResult.successData(AjaxStatus.success.code, "ok");

    }

    @GetMapping(value = "/history/findAlarmlist")
    @ApiOperation(value = "报警信息查询", notes = "报警信息查询")
    @ApiImplicitParams({

            @ApiImplicitParam(name = "begin", value = "开始时间", required = true, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "end", value = "结束时间", required = true, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "alarmType", value = "报警类型 booststation:升压站报警,windturbine:设备报警,custom:自定义报警", required = true, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "stationid", value = "场站编号", required = true, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "deviceid", value = "设备编号", required = false, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "description", value = "描述", required = false, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "modelId", value = "型号", required = false, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "deviceType", value = "报警类型 booststation:升压站报警,windturbine:设备报警", required = false, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "components", value = "部件编号", required = false, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "alarmId", value = "报警编号", required = false, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "isclose", value = "是否完成 不传全查,true 完成的，false 没完成的", required = false, dataType = "Boolean", paramType = "query"),
            @ApiImplicitParam(name = "pageNum", value = "页号", required = true, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "pageSize", value = "每页显示行数", required = true, dataType = "string", paramType = "query")})
    public AjaxResult findAlarmlist(
            @RequestParam(value = "begin", required = true) String begin,
            @RequestParam(value = "end", required = true) String end,
            @RequestParam(value = "alarmType", required = false) String alarmType,
            @RequestParam(value = "stationid", required = false) String stationid,
            @RequestParam(value = "deviceid", required = false) String deviceid,
            @RequestParam(value = "description", required = false) String description,
            @RequestParam(value = "modelId", required = false) String modelId,
            @RequestParam(value = "deviceType", required = false) String deviceType,
            @RequestParam(value = "components", required = false) String components,
            @RequestParam(value = "alarmId", required = false) String alarmId,
            @RequestParam(value = "isclose", required = false) Boolean isclose,
            @RequestParam(value = "pageNum", required = true) Integer pageNum,
            @RequestParam(value = "pageSize", required = true) Integer pageSize

    ) throws Exception {

        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date beginDate = df.parse(begin);
        Date endDate = df.parse(end);
        pageNum=pageNum-1;
        Map<String,Object> map = alarmHistoryService.findAlarmlist(modelId,beginDate.getTime(), endDate.getTime(), alarmType, stationid,deviceid, description,deviceType,components,alarmId,isclose, pageNum, pageSize);
        return AjaxResult.successData(AjaxStatus.success.code, map);

    }

    @GetMapping(value = "/history/findAlarmByTypelist")
    @ApiOperation(value = "获取升压站、设备、自定义报警报警信息查询", notes = "报警信息查询")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "type", value = "报警类型 booststation:升压站报警,windturbine:设备报警,custom:自定义报警", required = true, dataType = "string", paramType = "query")
    })
    public AjaxResult findAlarmByTypelist(String type) throws Exception {


        List<AlarmVo> ls = alarmHistoryService.findAlarmByTypelist(type);
        return AjaxResult.successData(AjaxStatus.success.code, ls);

    }


    @GetMapping(value = "/history/findWtFeatureStat")
    @ApiOperation(value = "查询原始报警类型、报警时长、报警次数", notes = "查询报警类型、报警时长、报警次数")
    @ApiImplicitParams({

            @ApiImplicitParam(name = "begin", value = "开始时间", required = true, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "end", value = "结束时间", required = true, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "stationid", value = "场站编号", required = true, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "modelId", value = "型号编号", required = false, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "components", value = "部件编号", required = false, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "alarmIds", value = "报警编号集合", required = false, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "alarmType", value = "报警类型 booststation:升压站报警,windturbine:设备报警", required = true, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "timeType", value = "秒、分、时（s,m,h）", required = false, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "pageNum", value = "页号", required = true, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "pageSize", value = "每页显示行数", required = true, dataType = "string", paramType = "query")})


    public   Map<String,Object> findWtFeatureStat(

            @RequestParam(value = "begin", required = true) String begin,
            @RequestParam(value = "end", required = true) String end,
            @RequestParam(value = "stationid", required = true) String stId,
            @RequestParam(value = "modelId", required = false) String modelId,
            @RequestParam(value = "components", required = false) String components,
            @RequestParam(value = "alarmIds", required = false) String alarmIds,
            @RequestParam(value = "alarmType", required = false) String alarmType,
            @RequestParam(value = "timeType", required = false) String timeType,
            @RequestParam(value = "pageNum", required = true) Integer pageNum,
            @RequestParam(value = "pageSize", required = true) Integer pageSize
    ) throws ParseException {


        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date dtStart = sdf.parse(begin);
        Date dtEnd = sdf.parse(end);

        if(StringUtils.empty(modelId))
        {
            modelId=null;
        }
        if(StringUtils.empty(components))
        {
            components=null;
        }
        if(StringUtils.empty(alarmIds))
        {
            alarmIds=null;
        }
        if(StringUtils.empty(alarmType))
        {
            alarmType=null;
        }
        List<AlarmStatVo> pressureList = alarmHistoryService.findWtFeatureStat(stId,modelId, dtStart, dtEnd,components,alarmIds,alarmType,timeType);


        //根据风机编号分组
        Map<String, List<AlarmStatVo>> alarmStatMapGroupbyWindturbineId = pressureList.stream().collect(Collectors.groupingBy(AlarmStatVo::getWindturbineId));

        Map<String, List<AlarmStatVo>> resultMap = new TreeMap<>();
        int max=0;


        for (Map.Entry<String, List<AlarmStatVo>> entry : alarmStatMapGroupbyWindturbineId.entrySet()) {
            String windturbineId = entry.getKey();

            if(StringUtils.empty(pageNum))
            {
                pageNum=1;
            }
            if(StringUtils.empty(pageSize))
            {
                pageSize=15;
            }

            // 获取分页数据
            List<AlarmStatVo> pagedData = getPagedData(entry.getValue(), pageSize, pageNum);
            resultMap.put(windturbineId, pagedData);
            if(entry.getValue().size()>max)
            {
                max=entry.getValue().size();
            }
        }

        //根据风机编号进行排序
        List<Map.Entry<String, List<AlarmStatVo>>> list = new ArrayList<>(resultMap.entrySet());
        Collections.sort(list, new Comparator<Map.Entry<String, List<AlarmStatVo>>>() {
            @Override
            public int compare(Map.Entry<String, List<AlarmStatVo>> o1, Map.Entry<String, List<AlarmStatVo>> o2) {
                String key1=o1.getKey();
                String key2=o1.getKey();
                return key1.compareTo(key2);
            }
        });


        Map<String,Object> result =new HashMap<>();
        result.put("total",max);
        result.put("result",list);

//        return list;
        return result;

    }
    public  List<AlarmStatVo> getPagedData(List<AlarmStatVo> dataList, int pageSize, int pageNumber) {
        // 计算起始索引
        int fromIndex = (pageNumber - 1) * pageSize;
        // 计算结束索引
        int toIndex = Math.min(fromIndex + pageSize, dataList.size());

        // 检查起始索引是否超出范围
        if (fromIndex >= dataList.size() || fromIndex < 0) {
            return new ArrayList<>(); // 返回空列表
        }

        // 返回分页数据
        return dataList.subList(fromIndex, toIndex);
    }

    @GetMapping(value = "/history/findCtFeatureStat")
    @ApiOperation(value = "查询自定义报警类型、报警时长、报警次数", notes = "查询报警类型、报警时长、报警次数")
    @ApiImplicitParams({

            @ApiImplicitParam(name = "begin", value = "开始时间", required = true, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "end", value = "结束时间", required = true, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "stationid", value = "场站编号", required = true, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "modelId", value = "型号编号", required = false, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "components", value = "部件集合", required = true, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "deviceType", value = "报警类型 booststation:升压站报警,windturbine:设备报警,inverter:光伏", required = true, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "alarmIds", value = "报警编号集合", required = true, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "timeType", value = "秒、分、时（s,m,h）", required = false, dataType = "string", paramType = "query")
    })
    public List<Map.Entry<String, List<AlarmStatVo>>> findCtFeatureStat(

            @RequestParam(value = "begin", required = true) String begin,
            @RequestParam(value = "end", required = true) String end,
            @RequestParam(value = "stationid", required = true) String stId,
            @RequestParam(value = "modelId", required = false) String modelId,
            @RequestParam(value = "components", required = true) String components,
            @RequestParam(value = "deviceType", required = true) String deviceType,
            @RequestParam(value = "alarmIds", required = true) String alarmIds,
            @RequestParam(value = "timeType", required = false) String timeType
    ) throws ParseException {


        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date dtStart = sdf.parse(begin);
        Date dtEnd = sdf.parse(end);

        if(StringUtils.empty(modelId))
        {
            modelId=null;
        }
        List<AlarmStatVo> pressureList = alarmHistoryService.findCtFeatureStat(stId,modelId, dtStart, dtEnd,components,deviceType,alarmIds,timeType);
        //根据风机编号分组
        Map<String, List<AlarmStatVo>> alarmStatMapGroupbyWindturbineId = pressureList.stream().collect(Collectors.groupingBy(AlarmStatVo::getWindturbineId));

        Map<String, List<AlarmStatVo>> resultMap = new TreeMap<>();

        for (Map.Entry<String, List<AlarmStatVo>> entry : alarmStatMapGroupbyWindturbineId.entrySet()) {
            String windturbineId = entry.getKey();
            resultMap.put(windturbineId, entry.getValue());
        }

        //根据风机编号进行排序
        List<Map.Entry<String, List<AlarmStatVo>>> list = new ArrayList<>(resultMap.entrySet());
        Collections.sort(list, new Comparator<Map.Entry<String, List<AlarmStatVo>>>() {
            @Override
            public int compare(Map.Entry<String, List<AlarmStatVo>> o1, Map.Entry<String, List<AlarmStatVo>> o2) {
                String key1=o1.getKey();
                String key2=o1.getKey();
                return key1.compareTo(key2);
            }
        });

        return list;


    }



    @GetMapping(value = "/history/findCtFeatureStatByWpId")
    @ApiOperation(value = "查询自定义报警类型、报警时长、报警次数", notes = "查询报警类型、报警时长、报警次数")
    @ApiImplicitParams({

            @ApiImplicitParam(name = "begin", value = "开始时间", required = true, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "end", value = "结束时间", required = true, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "stationid", value = "场站编号", required = true, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "modelId", value = "型号编号", required = false, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "components", value = "部件集合", required = true, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "deviceType", value = "报警类型 booststation:升压站报警,windturbine:设备报警,inverter:光伏", required = true, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "alarmIds", value = "报警编号集合", required = true, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "timeType", value = "秒、分、时（s,m,h）", required = false, dataType = "string", paramType = "query")
    })
    public List<Map.Entry<String, List<AlarmStatVo>>> findCtFeatureStatByWpId(

            @RequestParam(value = "begin", required = true) String begin,
            @RequestParam(value = "end", required = true) String end,
            @RequestParam(value = "stationid", required = true) String stId,
            @RequestParam(value = "modelId", required = false) String modelId,
            @RequestParam(value = "components", required = true) String components,
            @RequestParam(value = "deviceType", required = true) String deviceType,
            @RequestParam(value = "alarmIds", required = true) String alarmIds,
            @RequestParam(value = "timeType", required = false) String timeType
    ) throws ParseException {


        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date dtStart = sdf.parse(begin);
        Date dtEnd = sdf.parse(end);

        if(StringUtils.empty(modelId))
        {
            modelId=null;
        }
        List<AlarmStatVo> pressureList = alarmHistoryService.findCtFeatureStatByWpId(modelId, dtStart, dtEnd,components,deviceType,alarmIds,timeType);

//
//        Map<String, List<AlarmStatVo>> map=new TreeMap<>();
//
//        for(AlarmStatVo vo:pressureList)
//        {
//            if(map.containsKey(vo.getRelateParts()))
//            {
//                List<AlarmStatVo>
//            }
//        }
        //根据风机编号分组
        Map<String, List<AlarmStatVo>> alarmStatMapGroupbyWindturbineId = pressureList.stream().collect(Collectors.groupingBy(AlarmStatVo::getStationId));

        Map<String, List<AlarmStatVo>> resultMap = new TreeMap<>();

        for (Map.Entry<String, List<AlarmStatVo>> entry : alarmStatMapGroupbyWindturbineId.entrySet()) {
            String wpId = entry.getKey();
            resultMap.put(wpId, entry.getValue());
        }

        //根据风机编号进行排序
        List<Map.Entry<String, List<AlarmStatVo>>> list = new ArrayList<>(resultMap.entrySet());
        Collections.sort(list, new Comparator<Map.Entry<String, List<AlarmStatVo>>>() {
            @Override
            public int compare(Map.Entry<String, List<AlarmStatVo>> o1, Map.Entry<String, List<AlarmStatVo>> o2) {
                String key1=o1.getKey();
                String key2=o1.getKey();
                return key1.compareTo(key2);
            }
        });

        return list;

    }


    @GetMapping(value = "/history/findCtFeatureStatByLnId")
    @ApiOperation(value = "查询自定义报警类型、报警时长、报警次数", notes = "查询报警类型、报警时长、报警次数")
    @ApiImplicitParams({

            @ApiImplicitParam(name = "begin", value = "开始时间", required = true, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "end", value = "结束时间", required = true, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "stationid", value = "场站编号", required = true, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "modelId", value = "型号编号", required = false, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "components", value = "部件集合", required = true, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "deviceType", value = "报警类型 booststation:升压站报警,windturbine:设备报警,inverter:光伏", required = true, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "alarmIds", value = "报警编号集合", required = true, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "timeType", value = "秒、分、时（s,m,h）", required = false, dataType = "string", paramType = "query")
    })
    public List<Map.Entry<String, List<AlarmStatVo>>> findCtFeatureStatByLnId(

            @RequestParam(value = "begin", required = true) String begin,
            @RequestParam(value = "end", required = true) String end,
            @RequestParam(value = "stationid", required = true) String stId,
            @RequestParam(value = "modelId", required = false) String modelId,
            @RequestParam(value = "components", required = true) String components,
            @RequestParam(value = "deviceType", required = true) String deviceType,
            @RequestParam(value = "alarmIds", required = true) String alarmIds,
            @RequestParam(value = "timeType", required = false) String timeType
    ) throws ParseException {


        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date dtStart = sdf.parse(begin);
        Date dtEnd = sdf.parse(end);

        if(StringUtils.empty(modelId))
        {
            modelId=null;
        }
        List<AlarmStatVo> pressureList = alarmHistoryService.findCtFeatureStatByLnId(stId,modelId, dtStart, dtEnd,components,deviceType,alarmIds,timeType);

//
//        Map<String, List<AlarmStatVo>> map=new TreeMap<>();
//
//        for(AlarmStatVo vo:pressureList)
//        {
//            if(map.containsKey(vo.getRelateParts()))
//            {
//                List<AlarmStatVo>
//            }
//        }
        //根据风机编号分组
        Map<String, List<AlarmStatVo>> alarmStatMapGroupbyWindturbineId = pressureList.stream().collect(Collectors.groupingBy(AlarmStatVo::getStationId));

        Map<String, List<AlarmStatVo>> resultMap = new TreeMap<>();

        for (Map.Entry<String, List<AlarmStatVo>> entry : alarmStatMapGroupbyWindturbineId.entrySet()) {
            String wpId = entry.getKey();
            resultMap.put(wpId, entry.getValue());
        }

        //根据风机编号进行排序
        List<Map.Entry<String, List<AlarmStatVo>>> list = new ArrayList<>(resultMap.entrySet());
        Collections.sort(list, new Comparator<Map.Entry<String, List<AlarmStatVo>>>() {
            @Override
            public int compare(Map.Entry<String, List<AlarmStatVo>> o1, Map.Entry<String, List<AlarmStatVo>> o2) {
                String key1=o1.getKey();
                String key2=o1.getKey();
                return key1.compareTo(key2);
            }
        });

        return list;

    }



    @GetMapping(value = "/history/findCtFeatureStatByWtId")
    @ApiOperation(value = "查询自定义报警类型、报警时长、报警次数", notes = "查询报警类型、报警时长、报警次数")
    @ApiImplicitParams({

            @ApiImplicitParam(name = "begin", value = "开始时间", required = true, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "end", value = "结束时间", required = true, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "deviceid", value = "设备编号", required = true, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "modelId", value = "型号编号", required = false, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "components", value = "部件集合", required = true, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "deviceType", value = "报警类型 booststation:升压站报警,windturbine:设备报警,inverter:光伏", required = true, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "alarmIds", value = "报警编号集合", required = false, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "timeType", value = "秒、分、时（s,m,h）", required = false, dataType = "string", paramType = "query")
    })
    public List<Map.Entry<String, List<AlarmStatVo>>> findCtFeatureStatByWtId(

            @RequestParam(value = "begin", required = true) String begin,
            @RequestParam(value = "end", required = true) String end,
            @RequestParam(value = "deviceid", required = true) String wtId,
            @RequestParam(value = "modelId", required = false) String modelId,
            @RequestParam(value = "components", required = false) String components,
            @RequestParam(value = "deviceType", required = false) String deviceType,
            @RequestParam(value = "alarmIds", required = false) String alarmIds,
            @RequestParam(value = "timeType", required = false) String timeType
    ) throws ParseException {


        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date dtStart = sdf.parse(begin);
        Date dtEnd = sdf.parse(end);

        if(StringUtils.empty(modelId))
        {
            modelId=null;
        }
        List<AlarmStatVo> pressureList = alarmHistoryService.findCtFeatureStatByWtId(wtId,modelId, dtStart, dtEnd,components,deviceType,alarmIds,timeType);

//
//        Map<String, List<AlarmStatVo>> map=new TreeMap<>();
//
//        for(AlarmStatVo vo:pressureList)
//        {
//            if(map.containsKey(vo.getRelateParts()))
//            {
//                List<AlarmStatVo>
//            }
//        }
        //根据风机编号分组
        Map<String, List<AlarmStatVo>> alarmStatMapGroupbyWindturbineId = pressureList.stream().collect(Collectors.groupingBy(AlarmStatVo::getStationId));

        Map<String, List<AlarmStatVo>> resultMap = new TreeMap<>();

        for (Map.Entry<String, List<AlarmStatVo>> entry : alarmStatMapGroupbyWindturbineId.entrySet()) {
            String wpId = entry.getKey();
            resultMap.put(wpId, entry.getValue());
        }

        //根据风机编号进行排序
        List<Map.Entry<String, List<AlarmStatVo>>> list = new ArrayList<>(resultMap.entrySet());
        Collections.sort(list, new Comparator<Map.Entry<String, List<AlarmStatVo>>>() {
            @Override
            public int compare(Map.Entry<String, List<AlarmStatVo>> o1, Map.Entry<String, List<AlarmStatVo>> o2) {
                String key1=o1.getKey();
                String key2=o1.getKey();
                return key1.compareTo(key2);
            }
        });

        return list;

    }
}




