package com.ruoyi.ems.service.impl;

import com.ruoyi.ems.service.IAlarmService;
import com.ruoyi.ems.domain.Alarm;
import com.ruoyi.ems.domain.AlarmHandle;
import com.ruoyi.ems.mapper.AlarmHandleMapper;
import com.ruoyi.ems.mapper.AlarmMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 告警Service实现类
 */
@Slf4j
@Service
public class AlarmServiceImpl implements IAlarmService {

    @Autowired
    private AlarmMapper alarmMapper;

    @Autowired
    private AlarmHandleMapper handleMapper;

    @Override
    public Alarm selectById(Long id) {
        return alarmMapper.selectById(id);
    }

    @Override
    public Alarm selectByAlarmId(String alarmId) {
        return alarmMapper.selectByAlarmId(alarmId);
    }

    @Override
    public List<Alarm> selectList(Alarm alarm) {
        return alarmMapper.selectList(alarm);
    }

    @Override
    public List<Alarm> selectActiveAlarms(String areaCode) {
        return alarmMapper.selectActiveAlarms(areaCode);
    }

    @Override
    public int insert(Alarm alarm) {
        return alarmMapper.insert(alarm);
    }

    @Override
    public int update(Alarm alarm) {
        return alarmMapper.update(alarm);
    }

    @Override
    public int deleteByIds(Long[] ids) {
        return alarmMapper.deleteByIds(ids);
    }

    @Override
    public List<AlarmHandle> selectHandlesByAlarmId(String alarmId) {
        return handleMapper.selectByAlarmId(alarmId);
    }

    // ==================== 统计接口实现 ====================

    @Override
    public Map<String, Object> selectAlarmStats(Alarm query) {
        Map<String, Object> stats = new HashMap<>();

        // 按级别统计
        List<Map<String, Object>> levelStats = countByLevel(query);
        stats.put("levelStats", levelStats);

        // 按状态统计
        List<Map<String, Object>> statusStats = countByStatus(query);
        stats.put("statusStats", statusStats);

        // 处理率
        Map<String, Object> handleRate = countHandleRate(query);
        stats.put("handleRate", handleRate);

        // 计算汇总
        int totalCount = 0;
        int activeCount = 0;
        int urgentCount = 0;

        for (Map<String, Object> item : levelStats) {
            int cnt = ((Number) item.getOrDefault("cnt", 0)).intValue();
            totalCount += cnt;
            Integer level = (Integer) item.get("alarmLevel");
            if (level != null && level == Alarm.LEVEL_URGENT) {
                urgentCount = cnt;
            }
        }

        for (Map<String, Object> item : statusStats) {
            Integer status = (Integer) item.get("alarmStatus");
            if (status != null && status <= Alarm.STATUS_HANDLING) {
                activeCount += ((Number) item.getOrDefault("cnt", 0)).intValue();
            }
        }

        stats.put("totalCount", totalCount);
        stats.put("activeCount", activeCount);
        stats.put("urgentCount", urgentCount);

        return stats;
    }

    @Override
    public List<Map<String, Object>> countByLevel(Alarm query) {
        return alarmMapper.countByLevel(query);
    }

    @Override
    public List<Map<String, Object>> countByStatus(Alarm query) {
        return alarmMapper.countByStatus(query);
    }

    @Override
    public List<Map<String, Object>> countByTimeTrend(Alarm query, String granularity) {
        if ("month".equalsIgnoreCase(granularity)) {
            return alarmMapper.countByMonth(query);
        } else {
            return alarmMapper.countByDay(query);
        }
    }

    @Override
    public List<Map<String, Object>> countBySubsystem(Alarm query) {
        return alarmMapper.countBySubsystem(query);
    }

    @Override
    public Map<String, Object> countHandleRate(Alarm query) {
        Map<String, Object> result = alarmMapper.countHandleRate(query);
        if (result == null) {
            result = new HashMap<>();
            result.put("total", 0);
            result.put("handled", 0);
            result.put("pending", 0);
            result.put("rate", 0.0);
        } else {
            // 计算处理率
            int total = ((Number) result.getOrDefault("total", 0)).intValue();
            int handled = ((Number) result.getOrDefault("handled", 0)).intValue();
            double rate = total > 0 ? (handled * 100.0 / total) : 0.0;
            result.put("rate", Math.round(rate * 100) / 100.0);
        }
        return result;
    }
}