package com.qaup.collision.event.service;

import com.qaup.collision.rule.event.RuleViolationEvent;
import com.qaup.collision.rule.model.enums.RuleAlertLevel;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.util.concurrent.atomic.AtomicLong;

/**
 * 威胁级别事件服务
 * 基于威胁级别统一处理各种事件的通知机制
 * 
 * @author AI Assistant
 * @since 2025-01-17
 */
@Service
public class ThreatLevelEventService {

    private static final Logger logger = LoggerFactory.getLogger(ThreatLevelEventService.class);

    // 统计计数器
    private final AtomicLong infoEventCount = new AtomicLong(0);
    private final AtomicLong warningEventCount = new AtomicLong(0);
    private final AtomicLong criticalEventCount = new AtomicLong(0);
    private final AtomicLong emergencyEventCount = new AtomicLong(0);

    /**
     * 处理违规事件通知（基于违规类型）
     * 
     * @param violationEvent 违规事件
     */
    public void processViolationNotification(RuleViolationEvent violationEvent) {
        
        switch (violationEvent.getAlertLevel()) {
            case INFO:
                handleInfoLevelEvent(violationEvent);
                infoEventCount.incrementAndGet();
                break;
            case WARNING:
                handleWarningLevelEvent(violationEvent);
                warningEventCount.incrementAndGet();
                break;
            case CRITICAL:
                handleCriticalLevelEvent(violationEvent);
                criticalEventCount.incrementAndGet();
                break;
            case EMERGENCY:
                handleEmergencyLevelEvent(violationEvent);
                emergencyEventCount.incrementAndGet();
                break;
            default:
                logger.warn("未知的威胁级别: {}, 车辆ID: {}", violationEvent.getAlertLevel(), violationEvent.getVehicleId());
        }
    }
    
    /**
     * 处理自定义威胁级别事件
     * 
     * @param threatLevel 威胁级别
     * @param eventId 事件ID
     * @param eventType 事件类型
     * @param message 事件消息
     * @param details 事件详情
     */
    public void processCustomThreatEvent(RuleAlertLevel threatLevel, String eventId, 
                                       String eventType, String message, Object details) {
        logger.info("处理自定义威胁事件: level={}, type={}, eventId={}", threatLevel, eventType, eventId);
        
        switch (threatLevel) {
            case INFO:
                handleInfoLevelNotification(eventId, eventType, message, details);
                infoEventCount.incrementAndGet();
                break;
            case WARNING:
                handleWarningLevelNotification(eventId, eventType, message, details);
                warningEventCount.incrementAndGet();
                break;
            case CRITICAL:
                handleCriticalLevelNotification(eventId, eventType, message, details);
                criticalEventCount.incrementAndGet();
                break;
            case EMERGENCY:
                handleEmergencyLevelNotification(eventId, eventType, message, details);
                emergencyEventCount.incrementAndGet();
                break;
        }
    }

    // ========== 信息级事件处理 ==========

    private void handleInfoLevelEvent(RuleViolationEvent violationEvent) {
        logger.info("INFO级违规事件: vehicleId={}, ruleId={}, description={}", 
                   violationEvent.getVehicleId(), violationEvent.getRuleName(), 
                   violationEvent.getDescription());
        
        // 信息级事件只记录日志，通过WebSocket推送到前端
        // WebSocket推送由RuleEventWebSocketPublisher自动处理
    }

    private void handleInfoLevelNotification(String eventId, String eventType, String message, Object details) {
        logger.info("INFO级事件通知: type={}, eventId={}, message={}", eventType, eventId, message);
    }

    // ========== 警告级事件处理 ==========

    private void handleWarningLevelEvent(RuleViolationEvent violationEvent) {
        logger.warn("WARNING级违规事件: vehicleId={}, ruleId={}, description={}", 
                   violationEvent.getVehicleId(), violationEvent.getRuleName(), 
                   violationEvent.getDescription());
        
        // 警告级事件记录详细日志，并通过WebSocket推送
        // 可以考虑在前端显示更明显的提示
    }

    private void handleWarningLevelNotification(String eventId, String eventType, String message, Object details) {
        logger.warn("WARNING级事件通知: type={}, eventId={}, message={}", eventType, eventId, message);
    }

    // ========== 严重级事件处理 ==========

    private void handleCriticalLevelEvent(RuleViolationEvent violationEvent) {
        logger.error("CRITICAL级违规事件: vehicleId={}, ruleId={}, severity={}, description={}", 
                    violationEvent.getVehicleId(), violationEvent.getRuleName(), 
                    violationEvent.getViolationType(), violationEvent.getDescription());
        
        // 严重级事件需要特别关注
        // 1. 记录详细的错误日志
        // 2. 通过WebSocket立即推送到前端
        // 3. 可能需要触发特定的响应流程
        handleCriticalEventResponse(violationEvent);
    }

    private void handleCriticalLevelNotification(String eventId, String eventType, String message, Object details) {
        logger.error("CRITICAL级事件通知: type={}, eventId={}, message={}, details={}", 
                    eventType, eventId, message, details);
    }

    // ========== 紧急级事件处理 ==========

    private void handleEmergencyLevelEvent(RuleViolationEvent violationEvent) {
        logger.error("EMERGENCY级违规事件: vehicleId={}, ruleId={}, severity={}, location={}", 
                    violationEvent.getVehicleId(), violationEvent.getRuleName(), 
                    violationEvent.getViolationType(), violationEvent.getLocation());
        
        // 紧急级事件需要立即响应
        // 1. 记录到专门的紧急事件日志
        // 2. 立即通过WebSocket推送到前端
        // 3. 可能需要立即通知相关人员
        // 4. 触发紧急响应流程
        handleEmergencyEventResponse(violationEvent);
    }

    private void handleEmergencyLevelNotification(String eventId, String eventType, String message, Object details) {
        logger.error("EMERGENCY级事件通知: type={}, eventId={}, message={}, details={}", 
                    eventType, eventId, message, details);
        
        // 紧急级别事件可能需要额外的通知渠道
        handleEmergencyNotification(eventId, eventType, message, details);
    }

    // ========== 响应处理方法 ==========

    private void handleCriticalEventResponse(RuleViolationEvent violationEvent) {
        // 严重事件的响应处理
        logger.warn("触发严重事件响应流程: id={}", violationEvent.getId());
        
        // 这里可以添加具体的响应逻辑：
        // - 发送特定通知
        // - 触发自动化响应
        // - 记录到特殊的监控系统
    }

    private void handleEmergencyEventResponse(RuleViolationEvent violationEvent) {
        // 紧急事件的响应处理
        logger.error("触发紧急事件响应流程: id={}, vehicleId={}", 
                    violationEvent.getId(), violationEvent.getVehicleId());
        
        // 紧急事件需要立即响应：
        // - 可能需要立即停止相关车辆
        // - 通知紧急响应团队
        // - 记录到事故报告系统
        handleEmergencyResponse(violationEvent);
    }

    private void handleEmergencyNotification(String eventId, String eventType, String message, Object details) {
        // 紧急通知处理
        logger.error("发送紧急通知: id={}, type={}", eventId, eventType);
        
        // 这里可以集成其他通知渠道：
        // - 短信通知
        // - 邮件通知
        // - 第三方告警系统
    }

    private void handleEmergencyResponse(RuleViolationEvent violationEvent) {
        // 紧急响应处理
        logger.error("执行紧急响应: vehicleLicense={}, location={}", 
                    violationEvent.getVehicleId(), violationEvent.getLocation());
        
        // 紧急响应逻辑：
        // 1. 记录到紧急事件数据库
        // 2. 可能需要立即停止车辆
        // 3. 通知控制中心
        // 4. 启动应急预案
    }

    // ========== 统计和监控方法 ==========

    /**
     * 获取各威胁级别的事件统计
     */
    public ThreatLevelStatistics getThreatLevelStatistics() {
        return new ThreatLevelStatistics(
            infoEventCount.get(),
            warningEventCount.get(),
            criticalEventCount.get(),
            emergencyEventCount.get()
        );
    }

    /**
     * 重置统计计数器
     */
    public void resetStatistics() {
        infoEventCount.set(0);
        warningEventCount.set(0);
        criticalEventCount.set(0);
        emergencyEventCount.set(0);
        logger.info("威胁级别事件统计已重置");
    }

    /**
     * 威胁级别统计信息
     */
    public static class ThreatLevelStatistics {
        private final long infoCount;
        private final long warningCount;
        private final long criticalCount;
        private final long emergencyCount;
        private final long totalCount;

        public ThreatLevelStatistics(long infoCount, long warningCount, long criticalCount, long emergencyCount) {
            this.infoCount = infoCount;
            this.warningCount = warningCount;
            this.criticalCount = criticalCount;
            this.emergencyCount = emergencyCount;
            this.totalCount = infoCount + warningCount + criticalCount + emergencyCount;
        }

        // Getters
        public long getInfoCount() { return infoCount; }
        public long getWarningCount() { return warningCount; }
        public long getCriticalCount() { return criticalCount; }
        public long getEmergencyCount() { return emergencyCount; }
        public long getTotalCount() { return totalCount; }

        @Override
        public String toString() {
            return String.format("ThreatLevelStatistics{total=%d, info=%d, warning=%d, critical=%d, emergency=%d}",
                    totalCount, infoCount, warningCount, criticalCount, emergencyCount);
        }
    }
} 