package com.gyee.runeconomy.service.monitor;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.gyee.runeconomy.dto.AlarmDataParser;
import com.gyee.runeconomy.init.CacheContext;
import com.gyee.runeconomy.model.auto.ProBasicEquipment;
import com.gyee.runeconomy.model.auto.ProEconAlarmType;
import com.gyee.runeconomy.model.vo.PoliceVo;
import com.gyee.runeconomy.service.EarlyWarning.ApiClient;
import com.gyee.runeconomy.service.auto.IProEconAlarmTypeService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class AlarmService {

    @Resource
    private IProEconAlarmTypeService proEconAlarmTypeService;

    ApiClient client = new ApiClient();

    public List<PoliceVo.AlarmDetails> Alarm(String type, String wtid) throws Exception {

        Map<String, Object> map = new HashMap<>();
        // 获取当天零点时间
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        Date startDate = calendar.getTime();

        // 获取当前时间
        Date endDate = new Date();

        // 格式化时间为字符串
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String startTime = sdf.format(startDate);
        String endTime = sdf.format(endDate);

        List<PoliceVo.AlarmDetails> list = new ArrayList<>();

        List<ProBasicEquipment> equipments = CacheContext.wtls.stream()
                .filter(a -> wtid.equals(a.getId())).collect(Collectors.toList());

        String modelId = "WT2000D121H85";
        String station = "NX_FGS_HA_FDC_STA";
        if (equipments.size() > 0) {
            modelId = equipments.get(0).getModelId();
            station = equipments.get(0).getWindpowerstationId();
        }


//        startTime = "2024-12-12 00:00:00";
        String result = client.getgzFromApi(
                startTime,
                endTime,
                "windturbine",
                station,
                wtid,
                "",
                modelId,
                "windturbine",
                "",
                type,
                "",
                "",
                "1",
                "1000"
        );


        // 解析预警数据
        try {
            // 调用parseJson方法解析JSON
            PoliceVo policeVo = ApiClient.parseJson(result);

            if (policeVo != null) {

                // 输出解析后的对象，检查内容
                List<PoliceVo.AlarmDetails> alarmList1 = policeVo.getData().getLs();
                for (PoliceVo.AlarmDetails alarm1 : alarmList1) {
                    list.add(alarm1);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return list;
    }

    public Map<String, Object> flAlarm(String wtid) throws Exception {
        List<ProEconAlarmType> bylist = proEconAlarmTypeService.bylist(wtid);
        Map<String, Object> map = new HashMap<>();
        // 获取当天零点时间
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        Date startDate = calendar.getTime();

        // 获取当前时间
        Date endDate = new Date();

        // 格式化时间为字符串
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String startTime = sdf.format(startDate);
        String endTime = sdf.format(endDate);

        List<PoliceVo.AlarmDetails> zslist = new ArrayList<>();

        List<ProBasicEquipment> equipments = CacheContext.wtls.stream()
                .filter(a -> wtid.equals(a.getId())).collect(Collectors.toList());

        String modelId = "WT2000D121H85";
        String station = "NX_FGS_HA_FDC_STA";
        if (equipments.size() > 0) {
            modelId = equipments.get(0).getModelId();
            station = equipments.get(0).getWindpowerstationId();
        }

        for (ProEconAlarmType p : bylist) {

            String zsresult = client.getgzFromApi(
                    startTime,
                    endTime,
                    "windturbine",
                    station,
                    wtid,
                    "",
                    modelId,
                    "windturbine",
                    "",
                    p.getNemCode(),
                    "",
                    "",
                    "1",
                    "1000"
            );
            // 解析所有类别预警数据
            try {
                // 调用parseJson方法解析JSON
                PoliceVo policeVo = ApiClient.parseJson(zsresult);

                if (policeVo != null) {

                    // 输出解析后的对象，检查内容
                    List<PoliceVo.AlarmDetails> alarmList1 = policeVo.getData().getLs();
                    for (PoliceVo.AlarmDetails alarm1 : alarmList1) {
                        zslist.add(alarm1);
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

//            // 创建一个 name 到 nemcode 的映射
//            Map<String, String> nameToNemcodeMap = bylists.stream()
//                    .collect(Collectors.toMap(
//                            ProEconAlarmType::getNemCode,
//                            ProEconAlarmType::getName,
//                            (existing, replacement) -> existing // 保留已存在的值（第一个）
//                    ));
//
//            // 创建一个新的 Map 存储替换后的结果
//            Map<String, Long> updatedComponentCountMap = new HashMap<>();
//
//
//            // 遍历 componentCountMap
//            componentCountMap.forEach((key, value) -> {
//                // 检查是否能匹配到 nemcode
//                if (nameToNemcodeMap.containsKey(key)) {
//                    // 如果匹配，使用 nemcode 替换 key
//                    updatedComponentCountMap.put(nameToNemcodeMap.get(key), value);
//                } else {
//                    // 如果未匹配，保留原来的 key
//                    updatedComponentCountMap.put("QT", value);
//                }
//            });
        }
        Map<String, Long> componentCountMap = zslist.stream()
                .collect(Collectors.groupingBy(
                        PoliceVo.AlarmDetails::getSubcomponents, // 分组条件：按照 components 字段
                        Collectors.counting()                // 统计数量
                ));
            Long zscount = (long) zslist.size();
            componentCountMap.put("zs", zscount);
            map.put("data", bylist);
            map.put("count", componentCountMap);


        return map;
    }

}
