package com.qqchen.deploy.backend.deploy.service.impl;

import com.qqchen.deploy.backend.deploy.dto.ServerMonitorDataDTO;
import com.qqchen.deploy.backend.deploy.dto.ServerMonitorNotificationConfig;
import com.qqchen.deploy.backend.deploy.entity.Server;
import com.qqchen.deploy.backend.deploy.entity.ServerAlertLog;
import com.qqchen.deploy.backend.deploy.entity.ServerAlertRule;
import com.qqchen.deploy.backend.framework.enums.MonitorAlertLevelEnum;
import com.qqchen.deploy.backend.framework.enums.MonitorMetricEnum;
import com.qqchen.deploy.backend.framework.enums.ServerAlertStatusEnum;
import com.qqchen.deploy.backend.deploy.repository.IServerAlertLogRepository;
import com.qqchen.deploy.backend.deploy.repository.IServerAlertRuleRepository;
import com.qqchen.deploy.backend.deploy.repository.IServerRepository;
import com.qqchen.deploy.backend.deploy.service.IServerAlertService;
import com.qqchen.deploy.backend.framework.dto.DiskUsageInfo;
import com.qqchen.deploy.backend.notification.dto.SendNotificationRequest;
import com.qqchen.deploy.backend.notification.service.INotificationService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * 服务器告警服务实现
 */
@Slf4j
@Service
public class ServerAlertServiceImpl implements IServerAlertService {

    @Resource
    private IServerAlertRuleRepository alertRuleRepository;

    @Resource
    private IServerAlertLogRepository alertLogRepository;

    @Resource
    private IServerRepository serverRepository;

    @Resource
    private INotificationService notificationService;

    @Override
    public void checkAlertRules(Long serverId, ServerMonitorDataDTO monitorData, 
                               ServerMonitorNotificationConfig config) {
        // 查询所有规则并调用重载方法
        List<ServerAlertRule> allRules = alertRuleRepository.findAll();
        checkAlertRules(serverId, monitorData, allRules, config);
    }
    
    @Override
    public void checkAlertRules(Long serverId, ServerMonitorDataDTO monitorData,
                               List<ServerAlertRule> allRules,
                               ServerMonitorNotificationConfig config) {
        if (monitorData == null) {
            return;
        }

        // 按照告警类型分组规则，实现专属规则覆盖全局规则
        Map<MonitorMetricEnum, ServerAlertRule> effectiveRules = new HashMap<>();
        
        for (ServerAlertRule rule : allRules) {
            // 跳过其他服务器的专属规则
            if (rule.getServerId() != null && !rule.getServerId().equals(serverId)) {
                continue;
            }
            
            // 跳过禁用的规则
            if (!Boolean.TRUE.equals(rule.getEnabled())) {
                continue;
            }
            
            MonitorMetricEnum alertType = rule.getAlertType();
            ServerAlertRule existingRule = effectiveRules.get(alertType);
            
            if (existingRule == null) {
                // 该类型还没有规则，直接使用
                effectiveRules.put(alertType, rule);
            } else {
                // 该类型已有规则，专属规则优先（覆盖全局规则）
                boolean isExistingGlobal = existingRule.getServerId() == null;
                boolean isCurrentSpecific = rule.getServerId() != null;
                
                if (isCurrentSpecific && isExistingGlobal) {
                    // 当前是专属规则，已有是全局规则 → 用专属规则覆盖
                    effectiveRules.put(alertType, rule);
                    log.debug("服务器专属规则覆盖全局规则: serverId={}, alertType={}, ruleId={}", 
                        serverId, alertType, rule.getId());
                }
                // 否则保持原有规则（专属优先，或者先到先得）
            }
        }
        
        // 使用筛选后的有效规则进行检查
        for (ServerAlertRule rule : effectiveRules.values()) {
            checkSingleRule(serverId, monitorData, rule, config);
        }
    }

    /**
     * 检查单个告警规则
     */
    private void checkSingleRule(Long serverId, ServerMonitorDataDTO monitorData, ServerAlertRule rule,
                                ServerMonitorNotificationConfig config) {
        BigDecimal currentValue = null;
        String resourceInfo = "";

        // 根据告警类型获取当前值
        switch (rule.getAlertType()) {
            case CPU:
                currentValue = monitorData.getCpuUsage();
                resourceInfo = "CPU";
                break;
            case MEMORY:
                currentValue = monitorData.getMemoryUsage();
                resourceInfo = "内存";
                break;
            case DISK:
                // 磁盘告警：检查所有分区，任意分区超过阈值就告警
                checkDiskAlert(serverId, monitorData, rule, config);
                return;
        }

        if (currentValue == null) {
            return;
        }

        // 判断告警级别
        MonitorAlertLevelEnum alertLevel = null;
        BigDecimal threshold = null;

        if (currentValue.compareTo(rule.getCriticalThreshold()) >= 0) {
            alertLevel = MonitorAlertLevelEnum.CRITICAL;
            threshold = rule.getCriticalThreshold();
        } else if (currentValue.compareTo(rule.getWarningThreshold()) >= 0) {
            alertLevel = MonitorAlertLevelEnum.WARNING;
            threshold = rule.getWarningThreshold();
        }

        // 查询是否已有活跃或待处理的告警
        Optional<ServerAlertLog> existingAlertOpt = alertLogRepository.findActiveOrPendingAlert(
            serverId, rule.getId(), rule.getAlertType());

        if (alertLevel != null) {
            // 当前超过阈值
            handleAlertTriggered(existingAlertOpt, serverId, rule, alertLevel, currentValue, threshold, resourceInfo, config);
        } else {
            // 当前值正常，检查是否需要解除告警
            if (existingAlertOpt.isPresent()) {
                resolveAlert(existingAlertOpt.get());
            }
        }
    }

    /**
     * 检查磁盘告警
     * 策略：计算所有分区的总使用率 = (所有已用空间总和) / (所有总容量) * 100%
     */
    private void checkDiskAlert(Long serverId, ServerMonitorDataDTO monitorData, ServerAlertRule rule,
                               ServerMonitorNotificationConfig config) {
        List<DiskUsageInfo> diskUsageList = monitorData.getDiskUsage();
        if (diskUsageList == null || diskUsageList.isEmpty()) {
            return;
        }

        // 计算所有分区的总容量和已用空间
        BigDecimal totalCapacity = BigDecimal.ZERO;  // 总容量（GB）
        BigDecimal totalUsed = BigDecimal.ZERO;      // 已用空间（GB）
        
        for (DiskUsageInfo disk : diskUsageList) {
            if (disk.getTotalSize() != null && disk.getUsedSize() != null) {
                totalCapacity = totalCapacity.add(disk.getTotalSize());
                totalUsed = totalUsed.add(disk.getUsedSize());
            }
        }
        
        if (totalCapacity.compareTo(BigDecimal.ZERO) == 0) {
            return;
        }
        
        // 计算总磁盘使用率
        BigDecimal totalUsagePercent = totalUsed
            .multiply(new BigDecimal(100))
            .divide(totalCapacity, 2, BigDecimal.ROUND_HALF_UP);
        
        // 判断是否超过阈值
        MonitorAlertLevelEnum alertLevel = null;
        BigDecimal threshold = null;
        
        if (totalUsagePercent.compareTo(rule.getCriticalThreshold()) >= 0) {
            alertLevel = MonitorAlertLevelEnum.CRITICAL;
            threshold = rule.getCriticalThreshold();
        } else if (totalUsagePercent.compareTo(rule.getWarningThreshold()) >= 0) {
            alertLevel = MonitorAlertLevelEnum.WARNING;
            threshold = rule.getWarningThreshold();
        }
        
        // 查询是否已有活跃或待处理的告警
        Optional<ServerAlertLog> existingAlertOpt = alertLogRepository.findActiveOrPendingAlert(
            serverId, rule.getId(), rule.getAlertType());
        
        if (alertLevel != null) {
            // 当前超过阈值
            String resourceInfo = String.format("总磁盘（%d个分区，总容量%.0fGB，已用%.0fGB）", 
                diskUsageList.size(), totalCapacity.doubleValue(), totalUsed.doubleValue());
            handleAlertTriggered(existingAlertOpt, serverId, rule, alertLevel, totalUsagePercent, threshold, resourceInfo, config);
        } else {
            // 当前值正常，检查是否需要解除告警
            if (existingAlertOpt.isPresent()) {
                resolveAlert(existingAlertOpt.get());
            }
        }
    }

    /**
     * 处理告警触发逻辑
     */
    private void handleAlertTriggered(Optional<ServerAlertLog> existingAlertOpt, Long serverId, 
                                     ServerAlertRule rule, MonitorAlertLevelEnum level,
                                     BigDecimal currentValue, BigDecimal threshold, 
                                     String resourceInfo, ServerMonitorNotificationConfig config) {
        if (!existingAlertOpt.isPresent()) {
            // 首次检测到超过阈值
            if (rule.getDurationMinutes() == null || rule.getDurationMinutes() == 0) {
                // 立即告警
                createActiveAlertAndNotify(serverId, rule, level, currentValue, threshold, resourceInfo, config);
            } else {
                // 创建 PENDING 状态，等待持续时间验证
                createPendingAlert(serverId, rule, level, currentValue, threshold, resourceInfo);
            }
        } else {
            ServerAlertLog existingAlert = existingAlertOpt.get();
            
            if (ServerAlertStatusEnum.PENDING.equals(existingAlert.getStatus())) {
                // 已有 PENDING 告警，检查是否达到持续时间
                long durationMinutes = java.time.Duration.between(
                    existingAlert.getAlertTime(), LocalDateTime.now()).toMinutes();
                
                if (durationMinutes >= rule.getDurationMinutes()) {
                    // 达到持续时间，激活并发送通知
                    activateAndNotify(existingAlert, rule, config);
                } else {
                    // 未达到持续时间，更新当前值（如果级别变化）
                    if (existingAlert.getAlertLevel() != level) {
                        updateAlertLevel(existingAlert, level, currentValue, threshold, resourceInfo);
                    }
                    log.debug("⏳ 告警持续时间不足: serverId={}, 已持续{}分钟/需要{}分钟", 
                        serverId, durationMinutes, rule.getDurationMinutes());
                }
            } else if (ServerAlertStatusEnum.ACTIVE.equals(existingAlert.getStatus())) {
                // 已有 ACTIVE 告警
                if (existingAlert.getAlertLevel() != level && 
                    level.ordinal() > existingAlert.getAlertLevel().ordinal()) {
                    // 级别升级（例如从 WARNING 升级到 CRITICAL），重新发送通知
                    updateAlertLevelAndNotify(existingAlert, rule, level, currentValue, threshold, resourceInfo, config);
                } else if (existingAlert.getAlertLevel() != level) {
                    // 级别变化但未升级，只更新数据不发通知
                    updateAlertLevel(existingAlert, level, currentValue, threshold, resourceInfo);
                }
                // 否则不重复发送通知
            }
        }
    }
    
    /**
     * 创建 PENDING 状态的告警（需要等待持续时间验证）
     */
    private void createPendingAlert(Long serverId, ServerAlertRule rule, MonitorAlertLevelEnum level,
                                   BigDecimal currentValue, BigDecimal threshold, String resourceInfo) {
        String alertMessage = String.format("%s使用率达到%s级别: 当前值=%.2f%%, 阈值=%.2f%% (等待持续%d分钟验证)",
            resourceInfo, level.getDescription(), currentValue, threshold, rule.getDurationMinutes());
        
        ServerAlertLog alertLog = ServerAlertLog.builder()
            .serverId(serverId)
            .ruleId(rule.getId())
            .alertType(rule.getAlertType())
            .alertLevel(level)
            .alertValue(currentValue)
            .thresholdValue(threshold)
            .alertMessage(alertMessage)
            .status(ServerAlertStatusEnum.PENDING)
            .alertTime(LocalDateTime.now())
            .notified(false)
            .build();
        
        try {
            alertLogRepository.save(alertLog);
            log.info("📝 PENDING 告警已创建: id={}, serverId={}, 需持续{}分钟", 
                alertLog.getId(), serverId, rule.getDurationMinutes());
        } catch (Exception e) {
            log.error("创建 PENDING 告警失败", e);
        }
    }
    
    /**
     * 创建 ACTIVE 状态的告警并立即发送通知
     */
    private void createActiveAlertAndNotify(Long serverId, ServerAlertRule rule, MonitorAlertLevelEnum level,
                                           BigDecimal currentValue, BigDecimal threshold, 
                                           String resourceInfo, ServerMonitorNotificationConfig config) {
        String alertMessage = String.format("%s使用率达到%s级别: 当前值=%.2f%%, 阈值=%.2f%%",
            resourceInfo, level.getDescription(), currentValue, threshold);
        
        ServerAlertLog alertLog = ServerAlertLog.builder()
            .serverId(serverId)
            .ruleId(rule.getId())
            .alertType(rule.getAlertType())
            .alertLevel(level)
            .alertValue(currentValue)
            .thresholdValue(threshold)
            .alertMessage(alertMessage)
            .status(ServerAlertStatusEnum.ACTIVE)
            .alertTime(LocalDateTime.now())
            .notified(false)
            .build();
        
        try {
            alertLogRepository.save(alertLog);
            log.warn("🚨 告警已触发: id={}, serverId={}, message={}", 
                alertLog.getId(), serverId, alertMessage);
        } catch (Exception e) {
            log.error("保存告警记录失败", e);
            return;
        }
        
        // 发送通知
        sendNotificationAndUpdateStatus(alertLog, rule, resourceInfo, config);
    }
    
    /**
     * 激活 PENDING 告警并发送通知
     */
    private void activateAndNotify(ServerAlertLog alertLog, ServerAlertRule rule, 
                                  ServerMonitorNotificationConfig config) {
        alertLog.setStatus(ServerAlertStatusEnum.ACTIVE);
        String resourceInfo = getResourceInfo(rule.getAlertType());
        alertLog.setAlertMessage(String.format("%s使用率达到%s级别: 当前值=%.2f%%, 阈值=%.2f%% (已持续%d分钟)",
            resourceInfo, alertLog.getAlertLevel().getDescription(), 
            alertLog.getAlertValue(), alertLog.getThresholdValue(), rule.getDurationMinutes()));
        
        try {
            alertLogRepository.save(alertLog);
            log.warn("🚨 告警已激活: id={}, serverId={}, 已持续{}分钟", 
                alertLog.getId(), alertLog.getServerId(), rule.getDurationMinutes());
        } catch (Exception e) {
            log.error("激活告警失败", e);
            return;
        }
        
        // 发送通知
        sendNotificationAndUpdateStatus(alertLog, rule, resourceInfo, config);
    }
    
    /**
     * 更新告警级别
     */
    private void updateAlertLevel(ServerAlertLog alertLog, MonitorAlertLevelEnum newLevel,
                                 BigDecimal currentValue, BigDecimal threshold, String resourceInfo) {
        alertLog.setAlertLevel(newLevel);
        alertLog.setAlertValue(currentValue);
        alertLog.setThresholdValue(threshold);
        alertLog.setAlertMessage(String.format("%s使用率达到%s级别: 当前值=%.2f%%, 阈值=%.2f%%",
            resourceInfo, newLevel.getDescription(), currentValue, threshold));
        
        try {
            alertLogRepository.save(alertLog);
            log.info("📊 告警级别已更新: id={}, 新级别={}", alertLog.getId(), newLevel);
        } catch (Exception e) {
            log.error("更新告警级别失败", e);
        }
    }
    
    /**
     * 更新告警级别并重新发送通知（级别升级时）
     */
    private void updateAlertLevelAndNotify(ServerAlertLog alertLog, ServerAlertRule rule,
                                          MonitorAlertLevelEnum newLevel, BigDecimal currentValue,
                                          BigDecimal threshold, String resourceInfo,
                                          ServerMonitorNotificationConfig config) {
        MonitorAlertLevelEnum oldLevel = alertLog.getAlertLevel();
        updateAlertLevel(alertLog, newLevel, currentValue, threshold, resourceInfo);
        
        log.warn("⬆️ 告警级别升级: id={}, {} → {}, 重新发送通知", 
            alertLog.getId(), oldLevel, newLevel);
        
        // 重新发送通知
        sendNotificationAndUpdateStatus(alertLog, rule, resourceInfo, config);
    }
    
    /**
     * 解除告警
     */
    private void resolveAlert(ServerAlertLog alertLog) {
        alertLog.setStatus(ServerAlertStatusEnum.RESOLVED);
        alertLog.setResolveTime(LocalDateTime.now());
        
        try {
            alertLogRepository.save(alertLog);
            log.info("✅ 告警已解除: id={}, serverId={}", alertLog.getId(), alertLog.getServerId());
        } catch (Exception e) {
            log.error("解除告警失败", e);
        }
    }
    
    /**
     * 发送通知并更新状态
     */
    private void sendNotificationAndUpdateStatus(ServerAlertLog alertLog, ServerAlertRule rule,
                                                String resourceInfo, ServerMonitorNotificationConfig config) {
        if (config == null || config.getNotificationChannelId() == null || 
            config.getResourceAlertTemplateId() == null) {
            log.debug("通知配置不完整，跳过发送通知");
            return;
        }
        
        try {
            sendAlertNotification(alertLog.getServerId(), rule, alertLog.getAlertLevel(), 
                alertLog.getAlertValue(), alertLog.getThresholdValue(), resourceInfo, config);
            
            // 发送成功后，更新数据库通知状态
            alertLog.setNotified(true);
            alertLog.setNotifyTime(LocalDateTime.now());
            alertLogRepository.save(alertLog);
            
            log.info("✅ 告警通知已发送: alertLogId={}, serverId={}", 
                alertLog.getId(), alertLog.getServerId());
        } catch (Exception e) {
            log.error("发送告警通知失败: serverId={}, error={}", 
                alertLog.getServerId(), e.getMessage(), e);
        }
    }
    
    /**
     * 获取资源信息描述
     */
    private String getResourceInfo(MonitorMetricEnum alertType) {
        switch (alertType) {
            case CPU: return "CPU";
            case MEMORY: return "内存";
            case DISK: return "磁盘";
            default: return "未知";
        }
    }
    
    /**
     * 发送告警通知
     */
    private void sendAlertNotification(Long serverId, ServerAlertRule rule, MonitorAlertLevelEnum level,
                                      BigDecimal currentValue, BigDecimal threshold, String resourceInfo,
                                      ServerMonitorNotificationConfig config) {
        try {
            // 1. 获取服务器信息
            Server server = serverRepository.findById(serverId).orElse(null);
            if (server == null) {
                log.warn("服务器不存在，跳过发送通知: serverId={}", serverId);
                return;
            }
            
            // 2. 构建模板参数
            Map<String, Object> templateParams = new HashMap<>();
            templateParams.put("serverName", server.getServerName());
            templateParams.put("serverIp", server.getHostIp());
            templateParams.put("ruleName", rule.getRuleName());
            templateParams.put("alertType", rule.getAlertType().getDescription());
            templateParams.put("alertLevel", level.getDescription());
            templateParams.put("resourceInfo", resourceInfo);
            templateParams.put("currentValue", String.format("%.2f", currentValue));
            templateParams.put("threshold", String.format("%.2f", threshold));
            templateParams.put("alertTime", LocalDateTime.now().format(
                java.time.format.DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
            
            // 3. 构建SendNotificationRequest
            SendNotificationRequest request = new SendNotificationRequest();
            request.setChannelId(config.getNotificationChannelId());
            request.setNotificationTemplateId(config.getResourceAlertTemplateId());
            request.setTemplateParams(templateParams);
            
            // 4. 发送通知（NotificationService会自动根据渠道类型创建请求对象）
            notificationService.send(request);
            
            log.info("✅ 告警通知已发送: serverId={}, channelId={}, templateId={}", 
                serverId, config.getNotificationChannelId(), config.getResourceAlertTemplateId());
                
        } catch (Exception e) {
            log.error("发送告警通知异常: serverId={}", serverId, e);
            throw e;
        }
    }

    @Override
    public void checkServerStatusAlert(Long serverId, int failureCount, 
                                      List<ServerAlertRule> allRules,
                                      ServerMonitorNotificationConfig config) {
        // 获取SERVER_STATUS类型的有效规则（优先专属规则）
        ServerAlertRule statusRule = getEffectiveRule(serverId, MonitorMetricEnum.SERVER_STATUS, allRules);
        
        if (statusRule == null) {
            log.debug("未找到启用的服务器状态告警规则: serverId={}", serverId);
            return;
        }
        
        int warningCount = statusRule.getWarningThreshold().intValue();
        int criticalCount = statusRule.getCriticalThreshold().intValue();
        
        log.debug("检查服务器状态告警: serverId={}, failureCount={}, warningCount={}, criticalCount={}", 
            serverId, failureCount, warningCount, criticalCount);
        
        // 判断当前应该触发的告警级别
        MonitorAlertLevelEnum currentLevel = null;
        int threshold = 0;
        
        if (failureCount >= criticalCount) {
            currentLevel = MonitorAlertLevelEnum.CRITICAL;
            threshold = criticalCount;
        } else if (failureCount >= warningCount) {
            currentLevel = MonitorAlertLevelEnum.WARNING;
            threshold = warningCount;
        }
        
        // 查询是否已有活跃告警
        Optional<ServerAlertLog> existingAlertOpt = alertLogRepository.findActiveOrPendingAlert(
            serverId, statusRule.getId(), MonitorMetricEnum.SERVER_STATUS);
        
        if (currentLevel != null) {
            // 需要触发告警
            if (existingAlertOpt.isPresent()) {
                // 已有告警，检查是否需要升级
                ServerAlertLog existingAlert = existingAlertOpt.get();
                if (currentLevel.ordinal() > existingAlert.getAlertLevel().ordinal()) {
                    // 级别升级：WARNING → CRITICAL
                    updateServerStatusAlertLevel(existingAlert, statusRule, currentLevel, 
                        failureCount, threshold, config);
                } else {
                    log.debug("服务器状态告警已存在且级别未变化: serverId={}, level={}", 
                        serverId, currentLevel);
                }
            } else {
                // 创建新告警
                createServerStatusAlert(serverId, statusRule, currentLevel, failureCount, threshold, config);
            }
        }
    }

    @Override
    public void resolveServerStatusAlert(Long serverId) {
        // 查询所有SERVER_STATUS类型的规则
        List<ServerAlertRule> statusRules = alertRuleRepository.findAll().stream()
            .filter(rule -> rule.getAlertType() == MonitorMetricEnum.SERVER_STATUS)
            .collect(java.util.stream.Collectors.toList());
        
        for (ServerAlertRule rule : statusRules) {
            Optional<ServerAlertLog> activeAlertOpt = alertLogRepository.findActiveOrPendingAlert(
                serverId, rule.getId(), MonitorMetricEnum.SERVER_STATUS);
            
            if (activeAlertOpt.isPresent()) {
                resolveAlert(activeAlertOpt.get());
                log.info("✅ 服务器状态告警已解除: serverId={}, ruleId={}", serverId, rule.getId());
            }
        }
    }

    /**
     * 获取有效规则（优先专属规则，其次全局规则）
     */
    private ServerAlertRule getEffectiveRule(Long serverId, MonitorMetricEnum alertType, 
                                            List<ServerAlertRule> allRules) {
        ServerAlertRule specificRule = null;
        ServerAlertRule globalRule = null;
        
        for (ServerAlertRule rule : allRules) {
            if (rule.getAlertType() != alertType || !Boolean.TRUE.equals(rule.getEnabled())) {
                continue;
            }
            
            if (serverId.equals(rule.getServerId())) {
                specificRule = rule;
                break; // 找到专属规则，直接返回
            } else if (rule.getServerId() == null) {
                globalRule = rule;
            }
        }
        
        return specificRule != null ? specificRule : globalRule;
    }

    /**
     * 创建服务器状态告警
     */
    private void createServerStatusAlert(Long serverId, ServerAlertRule rule, 
                                        MonitorAlertLevelEnum level, int failureCount, 
                                        int threshold, ServerMonitorNotificationConfig config) {
        Server server = serverRepository.findById(serverId).orElse(null);
        if (server == null) {
            log.warn("服务器不存在: serverId={}", serverId);
            return;
        }
        
        ServerAlertLog alertLog = new ServerAlertLog();
        alertLog.setServerId(serverId);
        alertLog.setRuleId(rule.getId());
        alertLog.setAlertType(MonitorMetricEnum.SERVER_STATUS);
        alertLog.setAlertLevel(level);
        alertLog.setAlertValue(new BigDecimal(failureCount));
        alertLog.setThresholdValue(new BigDecimal(threshold));
        alertLog.setAlertTime(LocalDateTime.now());
        alertLog.setStatus(ServerAlertStatusEnum.PENDING);
        alertLog.setAlertMessage(String.format("服务器连续%d次连接失败，达到%s级别（阈值:%d次）", 
            failureCount, level.getDescription(), threshold));
        
        try {
            alertLogRepository.save(alertLog);
            log.warn("🔔 服务器状态告警已创建: serverId={}, serverName={}, level={}, failureCount={}", 
                serverId, server.getServerName(), level, failureCount);
            
            // 发送通知
            sendServerStatusNotification(alertLog, server, config);
        } catch (Exception e) {
            log.error("创建服务器状态告警失败: serverId={}", serverId, e);
        }
    }

    /**
     * 更新服务器状态告警级别
     */
    private void updateServerStatusAlertLevel(ServerAlertLog alertLog, ServerAlertRule rule,
                                             MonitorAlertLevelEnum newLevel, int failureCount, 
                                             int threshold, ServerMonitorNotificationConfig config) {
        Server server = serverRepository.findById(alertLog.getServerId()).orElse(null);
        if (server == null) {
            return;
        }
        
        MonitorAlertLevelEnum oldLevel = alertLog.getAlertLevel();
        alertLog.setAlertLevel(newLevel);
        alertLog.setAlertValue(new BigDecimal(failureCount));
        alertLog.setThresholdValue(new BigDecimal(threshold));
        alertLog.setAlertMessage(String.format("服务器连续%d次连接失败，达到%s级别（阈值:%d次）", 
            failureCount, newLevel.getDescription(), threshold));
        
        try {
            alertLogRepository.save(alertLog);
            log.warn("⬆️ 服务器状态告警级别升级: id={}, serverId={}, {} → {}, failureCount={}", 
                alertLog.getId(), alertLog.getServerId(), oldLevel, newLevel, failureCount);
            
            // 重新发送通知
            sendServerStatusNotification(alertLog, server, config);
        } catch (Exception e) {
            log.error("更新服务器状态告警级别失败", e);
        }
    }

    /**
     * 发送服务器状态通知
     * 使用统一的资源告警模板（与CPU/内存/磁盘告警相同）
     */
    private void sendServerStatusNotification(ServerAlertLog alertLog, Server server, 
                                             ServerMonitorNotificationConfig config) {
        if (config == null || config.getNotificationChannelId() == null || 
            config.getResourceAlertTemplateId() == null) {
            log.debug("通知配置不完整，跳过发送服务器状态通知");
            return;
        }
        
        try {
            // 查询规则信息
            ServerAlertRule rule = alertRuleRepository.findById(alertLog.getRuleId()).orElse(null);
            if (rule == null) {
                log.warn("告警规则不存在: ruleId={}", alertLog.getRuleId());
                return;
            }
            
            // 构建模板参数（与其他监控告警保持一致）
            Map<String, Object> templateParams = new HashMap<>();
            templateParams.put("serverName", server.getServerName());
            templateParams.put("ruleName", rule.getRuleName());
            templateParams.put("alertType", rule.getAlertType().getDescription());
            templateParams.put("resourceInfo", "服务器状态");
            templateParams.put("alertLevel", alertLog.getAlertLevel().getDescription());
            templateParams.put("currentValue", alertLog.getAlertValue().intValue());
            templateParams.put("threshold", alertLog.getThresholdValue().intValue());
            templateParams.put("alertTime", alertLog.getAlertTime().format(
                java.time.format.DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
            
            SendNotificationRequest request = new SendNotificationRequest();
            request.setChannelId(config.getNotificationChannelId());
            request.setNotificationTemplateId(config.getResourceAlertTemplateId());
            request.setTemplateParams(templateParams);
            
            notificationService.send(request);
            
            // 更新通知状态
            alertLog.setNotified(true);
            alertLog.setNotifyTime(LocalDateTime.now());
            alertLog.setStatus(ServerAlertStatusEnum.ACTIVE);
            alertLogRepository.save(alertLog);
            
            log.info("✅ 服务器状态告警通知已发送: serverId={}, level={}", 
                alertLog.getServerId(), alertLog.getAlertLevel());
        } catch (Exception e) {
            log.error("发送服务器状态通知异常: serverId={}", alertLog.getServerId(), e);
        }
    }
}
