import { useState } from 'react';
import { Card } from '../ui/card';
import { Button } from '../ui/button';
import { Badge } from '../ui/badge';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '../ui/tabs';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '../ui/select';
import { Input } from '../ui/input';
import { Label } from '../ui/label';
import { Switch } from '../ui/switch';
import { Textarea } from '../ui/textarea';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription, DialogFooter } from '../ui/dialog';
import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle } from '../ui/alert-dialog';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '../ui/table';
import {
  Bell,
  BellRing,
  BellOff,
  AlertTriangle,
  AlertCircle,
  Info,
  CheckCircle,
  XCircle,
  Search,
  RefreshCw,
  Eye,
  Plus,
  Edit,
  Trash2,
  Settings,
  Filter,
  Mail,
  MessageSquare,
  Smartphone,
  Clock,
  Target,
  TrendingUp,
  Activity,
  Server,
  Database,
  Zap,
  Users,
  Send,
  Copy,
  History,
  BarChart3,
  PieChart,
  Play,
  CheckCheck,
} from 'lucide-react';
import { toast } from 'sonner@2.0.3';
import {
  LineChart,
  Line,
  BarChart,
  Bar,
  XAxis,
  YAxis,
  CartesianGrid,
  Tooltip as RechartsTooltip,
  Legend,
  ResponsiveContainer,
  PieChart as RechartsPie,
  Pie,
  Cell,
  AreaChart,
  Area,
} from 'recharts';

interface AIAlertManagementProps {
  activePath?: string;
}

// 告警级别
type AlertLevel = 'info' | 'warning' | 'critical';

// 告警状态
type AlertStatus = 'pending' | 'acknowledged' | 'processing' | 'resolved' | 'ignored';

// 告警类型
type AlertType = 'model_service' | 'decision_failure' | 'data_quality' | 'system_resource' | 'business_rule';

// 通知渠道
type NotifyChannel = 'sms' | 'email' | 'app';

// 告警规则
interface AlertRule {
  id: string;
  ruleNo: string;
  ruleName: string;
  alertType: AlertType;
  level: AlertLevel;
  enabled: boolean;
  
  // 触发条件
  condition: {
    metric: string;
    operator: 'gt' | 'lt' | 'eq' | 'gte' | 'lte';
    threshold: number;
    duration?: number; // 持续时间(秒)
  };
  
  // 通知配置
  notification: {
    channels: NotifyChannel[];
    recipients: string[];
    template: string;
  };
  
  // 收敛配置
  convergence: {
    enabled: boolean;
    interval: number; // 收敛间隔(分钟)
    maxCount: number; // 最大告警数
  };
  
  // 统计信息
  triggeredCount: number;
  lastTriggered?: string;
  
  createTime: string;
  createBy: string;
  updateTime?: string;
}

// 告警记录
interface Alert {
  id: string;
  alertNo: string;
  ruleId: string;
  ruleName: string;
  alertType: AlertType;
  level: AlertLevel;
  status: AlertStatus;
  
  // 告警内容
  title: string;
  content: string;
  source: string;
  
  // 触发信息
  triggerValue: number;
  threshold: number;
  triggerTime: string;
  
  // 通知信息
  notifyChannels: NotifyChannel[];
  notifyStatus: {
    sms?: 'success' | 'failed';
    email?: 'success' | 'failed';
    app?: 'success' | 'failed';
  };
  notifyTime?: string;
  
  // 处理信息
  acknowledgedBy?: string;
  acknowledgedAt?: string;
  acknowledgedNote?: string;
  
  processingBy?: string;
  processingAt?: string;
  processingNote?: string;
  
  resolvedBy?: string;
  resolvedAt?: string;
  resolvedNote?: string;
  resolution?: string;
  
  // 收敛信息
  converged: boolean;
  convergenceCount?: number;
  
  // 附加数据
  metadata?: Record<string, any>;
}

// 通知模板
interface NotifyTemplate {
  id: string;
  templateNo: string;
  templateName: string;
  alertType: AlertType;
  channels: NotifyChannel[];
  
  content: {
    sms?: string;
    email?: {
      subject: string;
      body: string;
    };
    app?: {
      title: string;
      body: string;
    };
  };
  
  variables: string[];
  enabled: boolean;
  createTime: string;
}

export function AIAlertManagement({ activePath }: AIAlertManagementProps) {
  const [selectedRule, setSelectedRule] = useState<AlertRule | null>(null);
  const [selectedAlert, setSelectedAlert] = useState<Alert | null>(null);
  const [showRuleDialog, setShowRuleDialog] = useState(false);
  const [showAlertDetail, setShowAlertDetail] = useState(false);
  const [showHandleDialog, setShowHandleDialog] = useState(false);
  const [showProcessDialog, setShowProcessDialog] = useState(false);
  const [showResolveDialog, setShowResolveDialog] = useState(false);
  const [showTemplateDialog, setShowTemplateDialog] = useState(false);
  const [isEditing, setIsEditing] = useState(false);
  const [showDeleteConfirm, setShowDeleteConfirm] = useState(false);
  const [showSaveRuleConfirm, setShowSaveRuleConfirm] = useState(false);
  const [ruleToDelete, setRuleToDelete] = useState<string | null>(null);
  const [handleAction, setHandleAction] = useState<'acknowledge' | 'process' | 'resolve'>('acknowledge');
  const [handleNote, setHandleNote] = useState('');
  const [triggerConditionType, setTriggerConditionType] = useState<string>('response_time');
  
  // 筛选条件
  const [filters, setFilters] = useState({
    alertType: 'all',
    level: 'all',
    status: 'all',
    searchText: '',
    startDate: '',
    endDate: '',
  });

  // 告警规则数据
  const [alertRules] = useState<AlertRule[]>([
    {
      id: 'rule_001',
      ruleNo: 'RULE-001',
      ruleName: '模型服务响应时间过长',
      alertType: 'model_service',
      level: 'warning',
      enabled: true,
      condition: {
        metric: 'avg_response_time',
        operator: 'gt',
        threshold: 500,
        duration: 60,
      },
      notification: {
        channels: ['email', 'app'],
        recipients: ['运维团队', '技术负责人'],
        template: 'template_001',
      },
      convergence: {
        enabled: true,
        interval: 10,
        maxCount: 3,
      },
      triggeredCount: 15,
      lastTriggered: '2024-10-23 16:45:00',
      createTime: '2024-10-01 10:00:00',
      createBy: '系统管理员',
    },
    {
      id: 'rule_002',
      ruleNo: 'RULE-002',
      ruleName: '模型服务不可用',
      alertType: 'model_service',
      level: 'critical',
      enabled: true,
      condition: {
        metric: 'service_status',
        operator: 'eq',
        threshold: 0,
        duration: 10,
      },
      notification: {
        channels: ['sms', 'email', 'app'],
        recipients: ['运维团队', '技术负责人', '系统管理员'],
        template: 'template_002',
      },
      convergence: {
        enabled: true,
        interval: 5,
        maxCount: 5,
      },
      triggeredCount: 3,
      lastTriggered: '2024-10-23 17:15:30',
      createTime: '2024-10-01 10:00:00',
      createBy: '系统管理员',
    },
    {
      id: 'rule_003',
      ruleNo: 'RULE-003',
      ruleName: '决策生成失败率过高',
      alertType: 'decision_failure',
      level: 'critical',
      enabled: true,
      condition: {
        metric: 'failure_rate',
        operator: 'gt',
        threshold: 5,
        duration: 300,
      },
      notification: {
        channels: ['sms', 'email', 'app'],
        recipients: ['AI团队', '技术负责人'],
        template: 'template_003',
      },
      convergence: {
        enabled: true,
        interval: 15,
        maxCount: 2,
      },
      triggeredCount: 2,
      lastTriggered: '2024-10-22 14:30:00',
      createTime: '2024-10-01 10:00:00',
      createBy: '系统管理员',
    },
    {
      id: 'rule_004',
      ruleNo: 'RULE-004',
      ruleName: '数据质量异常',
      alertType: 'data_quality',
      level: 'warning',
      enabled: true,
      condition: {
        metric: 'data_quality_score',
        operator: 'lt',
        threshold: 60,
        duration: 120,
      },
      notification: {
        channels: ['email', 'app'],
        recipients: ['数据团队', '技术负责人'],
        template: 'template_004',
      },
      convergence: {
        enabled: true,
        interval: 30,
        maxCount: 3,
      },
      triggeredCount: 8,
      lastTriggered: '2024-10-23 15:20:00',
      createTime: '2024-10-01 10:00:00',
      createBy: '系统管理员',
    },
    {
      id: 'rule_005',
      ruleNo: 'RULE-005',
      ruleName: 'CPU使用率过高',
      alertType: 'system_resource',
      level: 'warning',
      enabled: true,
      condition: {
        metric: 'cpu_usage',
        operator: 'gt',
        threshold: 85,
        duration: 180,
      },
      notification: {
        channels: ['email', 'app'],
        recipients: ['运维团队'],
        template: 'template_005',
      },
      convergence: {
        enabled: true,
        interval: 10,
        maxCount: 5,
      },
      triggeredCount: 12,
      lastTriggered: '2024-10-23 17:20:00',
      createTime: '2024-10-01 10:00:00',
      createBy: '系统管理员',
    },
    {
      id: 'rule_006',
      ruleNo: 'RULE-006',
      ruleName: '内存使用率过高',
      alertType: 'system_resource',
      level: 'critical',
      enabled: true,
      condition: {
        metric: 'memory_usage',
        operator: 'gt',
        threshold: 90,
        duration: 120,
      },
      notification: {
        channels: ['sms', 'email', 'app'],
        recipients: ['运维团队', '系统管理员'],
        template: 'template_006',
      },
      convergence: {
        enabled: true,
        interval: 5,
        maxCount: 3,
      },
      triggeredCount: 5,
      lastTriggered: '2024-10-23 17:22:00',
      createTime: '2024-10-01 10:00:00',
      createBy: '系统管理员',
    },
  ]);

  // 告警记录数据
  const [alerts] = useState<Alert[]>([
    {
      id: 'alert_001',
      alertNo: 'ALERT-20241023-001',
      ruleId: 'rule_002',
      ruleName: '模型服务不可用',
      alertType: 'model_service',
      level: 'critical',
      status: 'processing',
      title: '生长阶段识别模型服务不可用',
      content: '模型服务连接失败，健康检查超时，服务已离线超过10秒',
      source: '生长阶段识别模型 (MODEL-005)',
      triggerValue: 0,
      threshold: 1,
      triggerTime: '2024-10-23 17:15:30',
      notifyChannels: ['sms', 'email', 'app'],
      notifyStatus: {
        sms: 'success',
        email: 'success',
        app: 'success',
      },
      notifyTime: '2024-10-23 17:15:35',
      acknowledgedBy: '运维人员',
      acknowledgedAt: '2024-10-23 17:16:00',
      acknowledgedNote: '已确认，正在排查服务器连接问题',
      processingBy: '运维人员',
      processingAt: '2024-10-23 17:18:00',
      processingNote: '发现服务器网络异常，正在重启网络服务',
      converged: false,
      metadata: {
        modelId: 'model_005',
        modelName: '生长阶段识别模型',
        endpoint: 'http://ai-service:8005/predict/growth-stage',
      },
    },
    {
      id: 'alert_002',
      alertNo: 'ALERT-20241023-002',
      ruleId: 'rule_006',
      ruleName: '内存使用率过高',
      alertType: 'system_resource',
      level: 'critical',
      status: 'resolved',
      title: '产量预测模型内存使用率达到临界值',
      content: '内存使用率持续超过90%阈值，当前值91%，持续时间超过2分钟',
      source: '产量预测模型 (MODEL-003)',
      triggerValue: 91,
      threshold: 90,
      triggerTime: '2024-10-23 17:22:00',
      notifyChannels: ['sms', 'email', 'app'],
      notifyStatus: {
        sms: 'success',
        email: 'success',
        app: 'success',
      },
      notifyTime: '2024-10-23 17:22:05',
      acknowledgedBy: '运维人员',
      acknowledgedAt: '2024-10-23 17:22:30',
      acknowledgedNote: '已确认，准备重启服务释放内存',
      processingBy: '运维人员',
      processingAt: '2024-10-23 17:23:00',
      processingNote: '正在优雅关闭服务，等待当前任务完成',
      resolvedBy: '运维人员',
      resolvedAt: '2024-10-23 17:25:00',
      resolvedNote: '服务已重启，内存使用率恢复正常至52%',
      resolution: '通过重启服务释放内存，已恢复正常',
      converged: false,
      metadata: {
        modelId: 'model_003',
        modelName: '产量预测模型',
        beforeMemory: 91,
        afterMemory: 52,
      },
    },
    {
      id: 'alert_003',
      alertNo: 'ALERT-20241023-003',
      ruleId: 'rule_005',
      ruleName: 'CPU使用率过高',
      alertType: 'system_resource',
      level: 'warning',
      status: 'acknowledged',
      title: '产量预测模型CPU使用率过高',
      content: 'CPU使用率持续超过85%阈值，当前值88%，持续时间超过3分钟',
      source: '产量预测模型 (MODEL-003)',
      triggerValue: 88,
      threshold: 85,
      triggerTime: '2024-10-23 17:20:00',
      notifyChannels: ['email', 'app'],
      notifyStatus: {
        email: 'success',
        app: 'success',
      },
      notifyTime: '2024-10-23 17:20:05',
      acknowledgedBy: '运维人员',
      acknowledgedAt: '2024-10-23 17:20:30',
      acknowledgedNote: '已确认，正在观察，如持续将优化模型配置',
      converged: false,
      metadata: {
        modelId: 'model_003',
        modelName: '产量预测模型',
        currentCPU: 88,
      },
    },
    {
      id: 'alert_004',
      alertNo: 'ALERT-20241023-004',
      ruleId: 'rule_004',
      ruleName: '数据质量异常',
      alertType: 'data_quality',
      level: 'warning',
      status: 'resolved',
      title: '传感器数据质量评分低于阈值',
      content: '2号大棚传感器数据质量评分55分，低于60分阈值，存在多个缺失字段',
      source: '2号大棚环境传感器',
      triggerValue: 55,
      threshold: 60,
      triggerTime: '2024-10-23 15:20:00',
      notifyChannels: ['email', 'app'],
      notifyStatus: {
        email: 'success',
        app: 'success',
      },
      notifyTime: '2024-10-23 15:20:05',
      acknowledgedBy: '数据工程师',
      acknowledgedAt: '2024-10-23 15:22:00',
      acknowledgedNote: '已确认，发现湿度传感器故障',
      processingBy: '数据工程师',
      processingAt: '2024-10-23 15:25:00',
      processingNote: '正在更换湿度传感器',
      resolvedBy: '数据工程师',
      resolvedAt: '2024-10-23 15:45:00',
      resolvedNote: '传感器已更换，数据质量恢复正常至85分',
      resolution: '更换故障传感器，数据质量已恢复',
      converged: false,
      metadata: {
        sensorId: 'sensor_002',
        fieldName: '2号大棚',
        missingFields: ['humidity'],
        beforeScore: 55,
        afterScore: 85,
      },
    },
    {
      id: 'alert_005',
      alertNo: 'ALERT-20241023-005',
      ruleId: 'rule_001',
      ruleName: '模型服务响应时间过长',
      alertType: 'model_service',
      level: 'warning',
      status: 'pending',
      title: '产量预测模型响应时间超过阈值',
      content: '平均响应时间580ms超过500ms阈值，持续时间超过1分钟',
      source: '产量预测模型 (MODEL-003)',
      triggerValue: 580,
      threshold: 500,
      triggerTime: '2024-10-23 17:25:00',
      notifyChannels: ['email', 'app'],
      notifyStatus: {
        email: 'success',
        app: 'success',
      },
      notifyTime: '2024-10-23 17:25:05',
      converged: false,
      metadata: {
        modelId: 'model_003',
        modelName: '产量预测模型',
        avgResponseTime: 580,
      },
    },
    {
      id: 'alert_006',
      alertNo: 'ALERT-20241023-006',
      ruleId: 'rule_001',
      ruleName: '模型服务响应时间过长',
      alertType: 'model_service',
      level: 'warning',
      status: 'ignored',
      title: '病虫害识别模型响应时间波动',
      content: '平均响应时间短暂超过阈值，但已自动恢复',
      source: '病虫害识别模型 (MODEL-002)',
      triggerValue: 520,
      threshold: 500,
      triggerTime: '2024-10-23 16:45:00',
      notifyChannels: ['app'],
      notifyStatus: {
        app: 'success',
      },
      notifyTime: '2024-10-23 16:45:05',
      converged: true,
      convergenceCount: 3,
      metadata: {
        modelId: 'model_002',
        modelName: '病虫害识别模型',
        note: '已自动恢复，无需处理',
      },
    },
  ]);

  // 统计数据
  const stats = {
    totalAlerts: alerts.length,
    pendingAlerts: alerts.filter(a => a.status === 'pending').length,
    processingAlerts: alerts.filter(a => a.status === 'processing').length,
    resolvedAlerts: alerts.filter(a => a.status === 'resolved').length,
    criticalAlerts: alerts.filter(a => a.level === 'critical' && a.status !== 'resolved').length,
    totalRules: alertRules.length,
    enabledRules: alertRules.filter(r => r.enabled).length,
    avgResponseTime: 8.5, // 分钟
  };

  // 告警趋势数据
  const alertTrend = [
    { date: '10-17', critical: 2, warning: 5, info: 3 },
    { date: '10-18', critical: 1, warning: 4, info: 2 },
    { date: '10-19', critical: 3, warning: 6, info: 4 },
    { date: '10-20', critical: 1, warning: 3, info: 2 },
    { date: '10-21', critical: 2, warning: 5, info: 3 },
    { date: '10-22', critical: 1, warning: 4, info: 1 },
    { date: '10-23', critical: 2, warning: 3, info: 0 },
  ];

  // 告警类型分布
  const alertTypeData = [
    { name: '模型服务', value: 35, color: '#3b82f6' },
    { name: '决策失败', value: 15, color: '#ef4444' },
    { name: '数据质量', value: 25, color: '#f59e0b' },
    { name: '系统资源', value: 20, color: '#8b5cf6' },
    { name: '业务规则', value: 5, color: '#10b981' },
  ];

  // 处理时长分布
  const responseTimeData = [
    { range: '<5分钟', count: 15 },
    { range: '5-10分钟', count: 12 },
    { range: '10-30分钟', count: 8 },
    { range: '>30分钟', count: 3 },
  ];

  const getAlertTypeName = (type: AlertType) => {
    const names = {
      model_service: '模型服务',
      decision_failure: '决策失败',
      data_quality: '数据质量',
      system_resource: '系统资源',
      business_rule: '业务规则',
    };
    return names[type];
  };

  const getLevelBadge = (level: AlertLevel) => {
    const config = {
      info: { label: '提示', className: 'bg-info-muted text-info-muted-foreground' },
      warning: { label: '警告', className: 'bg-warning-muted text-warning-muted-foreground' },
      critical: { label: '严重', className: 'bg-error-muted text-error-muted-foreground' },
    };
    const { label, className } = config[level];
    return <Badge className={className}>{label}</Badge>;
  };

  const getStatusBadge = (status: AlertStatus) => {
    const config = {
      pending: { label: '待处理', icon: AlertCircle, className: 'bg-warning-muted text-warning-muted-foreground' },
      acknowledged: { label: '已确认', icon: CheckCircle, className: 'bg-info-muted text-info-muted-foreground' },
      processing: { label: '处理中', icon: Activity, className: 'bg-accent text-accent-foreground' },
      resolved: { label: '已解决', icon: CheckCircle, className: 'bg-success-muted text-success-muted-foreground' },
      ignored: { label: '已忽略', icon: XCircle, className: 'bg-muted text-muted-foreground' },
    };
    const { label, icon: Icon, className } = config[status];
    return (
      <Badge variant="outline" className={className}>
        <Icon className="w-3 h-3 mr-1" />
        {label}
      </Badge>
    );
  };

  const getChannelIcon = (channel: NotifyChannel) => {
    const icons = {
      sms: Smartphone,
      email: Mail,
      app: MessageSquare,
    };
    return icons[channel];
  };

  const getChannelName = (channel: NotifyChannel) => {
    const names = {
      sms: '短信',
      email: '邮件',
      app: '站内信',
    };
    return names[channel];
  };

  const handleCreateRule = () => {
    setSelectedRule(null);
    setIsEditing(false);
    setTriggerConditionType('response_time');
    setShowRuleDialog(true);
  };

  const handleEditRule = (rule: AlertRule) => {
    setSelectedRule(rule);
    setIsEditing(true);
    // 根据规则的metric设置触发条件类型
    const metricTypeMap: Record<string, string> = {
      'avg_response_time': 'response_time',
      'service_status': 'service_exception',
      'failure_rate': 'decision_failure',
      'data_quality_score': 'data_quality',
      'cpu_usage': 'cpu_usage',
      'memory_usage': 'memory_usage',
    };
    setTriggerConditionType(metricTypeMap[rule.condition.metric] || 'response_time');
    setShowRuleDialog(true);
  };

  const handleDeleteRule = (ruleId: string) => {
    setRuleToDelete(ruleId);
    setShowDeleteConfirm(true);
  };

  const confirmDeleteRule = () => {
    toast.success('告警规则已删除');
    setShowDeleteConfirm(false);
    setRuleToDelete(null);
  };

  const handleSaveRule = () => {
    setShowSaveRuleConfirm(true);
  };

  const confirmSaveRule = () => {
    if (isEditing) {
      toast.success('告警规则已更新');
    } else {
      toast.success('告警规则已创建');
    }
    setShowSaveRuleConfirm(false);
    setShowRuleDialog(false);
  };

  const handleToggleRule = (ruleId: string, enabled: boolean) => {
    toast.success(enabled ? '规则已启用' : '规则已禁用');
  };

  const handleViewAlert = (alert: Alert) => {
    setSelectedAlert(alert);
    setShowAlertDetail(true);
  };

  const handleAcknowledge = (alert: Alert) => {
    setSelectedAlert(alert);
    setHandleAction('acknowledge');
    setHandleNote('');
    setShowHandleDialog(true);
  };

  const handleStartProcess = (alert: Alert) => {
    setSelectedAlert(alert);
    setHandleAction('process');
    setHandleNote('');
    setShowProcessDialog(true);
  };

  const handleResolve = (alert: Alert) => {
    setSelectedAlert(alert);
    setHandleAction('resolve');
    setHandleNote('');
    setShowResolveDialog(true);
  };

  const submitHandle = () => {
    if (handleAction === 'acknowledge') {
      setShowHandleDialog(false);
      toast.success('告警已确认');
    } else if (handleAction === 'process') {
      setShowProcessDialog(false);
      toast.success('已开始处理告警');
    } else if (handleAction === 'resolve') {
      setShowResolveDialog(false);
      toast.success('告警已解决');
    }
    setHandleNote('');
  };

  // 筛选告警
  const filteredAlerts = alerts.filter(alert => {
    if (filters.alertType !== 'all' && alert.alertType !== filters.alertType) return false;
    if (filters.level !== 'all' && alert.level !== filters.level) return false;
    if (filters.status !== 'all' && alert.status !== filters.status) return false;
    if (filters.searchText && !alert.title.toLowerCase().includes(filters.searchText.toLowerCase())) return false;
    if (filters.startDate && alert.triggerTime < filters.startDate) return false;
    if (filters.endDate && alert.triggerTime > filters.endDate) return false;
    return true;
  });

  return (
    <div className="space-y-6">
      {/* 页面标题 */}
      <Card className="p-6 bg-gradient-to-r from-warning-muted to-error-muted border-warning">
        <div className="flex items-start gap-3">
          <Bell className="w-6 h-6 text-warning flex-shrink-0 mt-1" />
          <div className="flex-1">
            <h2 className="mb-2">告警管理</h2>
            <p className="text-sm text-muted-foreground mb-3">
              自定义告警规则与阈值，多渠道通知，支持告警分级、收敛与处理跟踪
            </p>
            <div className="flex flex-wrap gap-2">
              <Badge variant="outline" className="bg-white">
                <Target className="w-3 h-3 mr-1" />
                自定义规则
              </Badge>
              <Badge variant="outline" className="bg-white">
                <Send className="w-3 h-3 mr-1" />
                多渠道通知
              </Badge>
              <Badge variant="outline" className="bg-white">
                <Activity className="w-3 h-3 mr-1" />
                告警收敛
              </Badge>
              <Badge variant="outline" className="bg-white">
                <History className="w-3 h-3 mr-1" />
                处理跟踪
              </Badge>
            </div>
          </div>
        </div>
      </Card>

      {/* 统计卡片 */}
      <div className="grid grid-cols-4 gap-4">
        <Card className="p-6">
          <div className="flex items-center justify-between mb-2">
            <div className="text-sm text-muted-foreground">告警总数</div>
            <Bell className="w-5 h-5 text-info" />
          </div>
          <div className="text-3xl font-bold mb-1">{stats.totalAlerts}</div>
          <div className="text-xs text-muted-foreground">
            待处理: {stats.pendingAlerts}
          </div>
        </Card>

        <Card className="p-6">
          <div className="flex items-center justify-between mb-2">
            <div className="text-sm text-muted-foreground">严重告警</div>
            <AlertTriangle className="w-5 h-5 text-error" />
          </div>
          <div className="text-3xl font-bold mb-1">{stats.criticalAlerts}</div>
          <div className="text-xs text-error">
            需立即处理
          </div>
        </Card>

        <Card className="p-6">
          <div className="flex items-center justify-between mb-2">
            <div className="text-sm text-muted-foreground">告警规则</div>
            <Settings className="w-5 h-5 text-success" />
          </div>
          <div className="text-3xl font-bold mb-1">{stats.totalRules}</div>
          <div className="text-xs text-muted-foreground">
            启用: {stats.enabledRules}
          </div>
        </Card>

        <Card className="p-6">
          <div className="flex items-center justify-between mb-2">
            <div className="text-sm text-muted-foreground">响应时长</div>
            <Clock className="w-5 h-5 text-accent-foreground" />
          </div>
          <div className="text-3xl font-bold mb-1">{stats.avgResponseTime}</div>
          <div className="text-xs text-muted-foreground">
            分钟(平均)
          </div>
        </Card>
      </div>

      {/* Tab切换 */}
      <Tabs defaultValue="alerts" className="space-y-6">
        <TabsList>
          <TabsTrigger value="alerts">
            <BellRing className="w-4 h-4 mr-2" />
            告警记录
          </TabsTrigger>
          <TabsTrigger value="rules">
            <Settings className="w-4 h-4 mr-2" />
            告警规则
          </TabsTrigger>
          <TabsTrigger value="analytics">
            <BarChart3 className="w-4 h-4 mr-2" />
            告警分析
          </TabsTrigger>
        </TabsList>

        {/* 告警记录 */}
        <TabsContent value="alerts">
          <Card className="p-6">
            <div className="flex items-center justify-between mb-4">
              <h3>告警记录</h3>
            </div>

            {/* 筛选条件 */}
            <div className="grid grid-cols-3 gap-4 mb-4">
              <div>
                <Label>告警类型</Label>
                <Select value={filters.alertType} onValueChange={(value) => setFilters({ ...filters, alertType: value })}>
                  <SelectTrigger>
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="all">全部类型</SelectItem>
                    <SelectItem value="model_service">模型服务</SelectItem>
                    <SelectItem value="decision_failure">决策失败</SelectItem>
                    <SelectItem value="data_quality">数据质量</SelectItem>
                    <SelectItem value="system_resource">系统资源</SelectItem>
                    <SelectItem value="business_rule">业务规则</SelectItem>
                  </SelectContent>
                </Select>
              </div>

              <div>
                <Label>告警级别</Label>
                <Select value={filters.level} onValueChange={(value) => setFilters({ ...filters, level: value })}>
                  <SelectTrigger>
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="all">全部级别</SelectItem>
                    <SelectItem value="info">提示</SelectItem>
                    <SelectItem value="warning">警告</SelectItem>
                    <SelectItem value="critical">严重</SelectItem>
                  </SelectContent>
                </Select>
              </div>

              <div>
                <Label>处理状态</Label>
                <Select value={filters.status} onValueChange={(value) => setFilters({ ...filters, status: value })}>
                  <SelectTrigger>
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="all">全部状态</SelectItem>
                    <SelectItem value="pending">待处理</SelectItem>
                    <SelectItem value="acknowledged">已确认</SelectItem>
                    <SelectItem value="processing">处理中</SelectItem>
                    <SelectItem value="resolved">已解决</SelectItem>
                    <SelectItem value="ignored">已忽略</SelectItem>
                  </SelectContent>
                </Select>
              </div>
            </div>

            {/* 告警列表 */}
            <div className="border rounded-lg overflow-hidden">
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead>告警编号</TableHead>
                    <TableHead>告警标题</TableHead>
                    <TableHead>类型</TableHead>
                    <TableHead>级别</TableHead>
                    <TableHead>触发时间</TableHead>
                    <TableHead>通知渠道</TableHead>
                    <TableHead>状态</TableHead>
                    <TableHead>操作</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {filteredAlerts.map((alert) => (
                    <TableRow key={alert.id}>
                      <TableCell className="font-medium">{alert.alertNo}</TableCell>
                      <TableCell>
                        <div>
                          <div className="font-medium">{alert.title}</div>
                          <div className="text-xs text-muted-foreground">{alert.source}</div>
                        </div>
                      </TableCell>
                      <TableCell>
                        <Badge variant="outline">{getAlertTypeName(alert.alertType)}</Badge>
                      </TableCell>
                      <TableCell>{getLevelBadge(alert.level)}</TableCell>
                      <TableCell className="text-sm">{alert.triggerTime}</TableCell>
                      <TableCell>
                        <div className="flex gap-1">
                          {alert.notifyChannels.map((channel) => {
                            const Icon = getChannelIcon(channel);
                            const status = alert.notifyStatus[channel];
                            return (
                              <div
                                key={channel}
                                className={`w-6 h-6 rounded flex items-center justify-center ${
                                  status === 'success' ? 'bg-success-muted text-success' : 'bg-error-muted text-error'
                                }`}
                                title={`${getChannelName(channel)}: ${status === 'success' ? '成功' : '失败'}`}
                              >
                                <Icon className="w-3 h-3" />
                              </div>
                            );
                          })}
                        </div>
                      </TableCell>
                      <TableCell>{getStatusBadge(alert.status)}</TableCell>
                      <TableCell>
                        <div className="flex gap-2">
                          <Button size="sm" variant="outline" onClick={() => handleViewAlert(alert)}>
                            <Eye className="w-3 h-3" />
                          </Button>
                          {(alert.status === 'acknowledged' || alert.status === 'pending') && (
                            <Button size="sm" variant="outline" onClick={() => handleStartProcess(alert)}>
                              <Play className="w-3 h-3 mr-1" />
                              开始处理
                            </Button>
                          )}
                          {alert.status === 'processing' && (
                            <Button size="sm" variant="outline" className="text-success border-success hover:bg-success-muted" onClick={() => handleResolve(alert)}>
                              <CheckCheck className="w-3 h-3 mr-1" />
                              解决
                            </Button>
                          )}
                        </div>
                      </TableCell>
                    </TableRow>
                  ))}
                </TableBody>
              </Table>
            </div>
          </Card>
        </TabsContent>

        {/* 告警规则 */}
        <TabsContent value="rules">
          <Card className="p-6">
            <div className="flex items-center justify-between mb-4">
              <h3>告警规则配置</h3>
              <Button onClick={handleCreateRule}>
                <Plus className="w-4 h-4 mr-2" />
                新建规则
              </Button>
            </div>

            <div className="space-y-4">
              {alertRules.map((rule) => (
                <div key={rule.id} className="p-4 border rounded-lg">
                  <div className="flex items-start justify-between mb-3">
                    <div className="flex items-start gap-3">
                      <Switch
                        checked={rule.enabled}
                        onCheckedChange={(checked) => handleToggleRule(rule.id, checked)}
                      />
                      <div>
                        <div className="flex items-center gap-2 mb-1">
                          <h4>{rule.ruleName}</h4>
                          {getLevelBadge(rule.level)}
                          <Badge variant="outline">{getAlertTypeName(rule.alertType)}</Badge>
                        </div>
                        <p className="text-sm text-muted-foreground">
                          规则编号: {rule.ruleNo}
                        </p>
                      </div>
                    </div>
                    <div className="flex gap-2">
                      <Button size="sm" variant="outline" onClick={() => handleEditRule(rule)}>
                        <Edit className="w-3 h-3" />
                      </Button>
                      <Button size="sm" variant="outline" onClick={() => handleDeleteRule(rule.id)}>
                        <Trash2 className="w-3 h-3" />
                      </Button>
                    </div>
                  </div>

                  <div className="grid grid-cols-4 gap-4 mb-3">
                    <div className="p-3 bg-muted rounded">
                      <div className="text-xs text-muted-foreground mb-1">触发条件</div>
                      <div className="text-sm font-medium">
                        {rule.condition.metric} {rule.condition.operator === 'gt' ? '>' : '<'} {rule.condition.threshold}
                      </div>
                    </div>
                    <div className="p-3 bg-muted rounded">
                      <div className="text-xs text-muted-foreground mb-1">持续时间</div>
                      <div className="text-sm font-medium">{rule.condition.duration}秒</div>
                    </div>
                    <div className="p-3 bg-muted rounded">
                      <div className="text-xs text-muted-foreground mb-1">触发次数</div>
                      <div className="text-sm font-medium">{rule.triggeredCount}次</div>
                    </div>
                    <div className="p-3 bg-muted rounded">
                      <div className="text-xs text-muted-foreground mb-1">最后触发</div>
                      <div className="text-sm font-medium">{rule.lastTriggered || '从未'}</div>
                    </div>
                  </div>

                  <div className="flex items-center gap-4 text-sm">
                    <div className="flex items-center gap-2">
                      <span className="text-muted-foreground">通知渠道:</span>
                      <div className="flex gap-1">
                        {rule.notification.channels.map((channel) => {
                          const Icon = getChannelIcon(channel);
                          return (
                            <Badge key={channel} variant="outline" className="text-xs">
                              <Icon className="w-3 h-3 mr-1" />
                              {getChannelName(channel)}
                            </Badge>
                          );
                        })}
                      </div>
                    </div>
                    <div className="flex items-center gap-2">
                      <span className="text-muted-foreground">收敛:</span>
                      <Badge variant="outline" className="text-xs">
                        {rule.convergence.enabled ? `${rule.convergence.interval}分钟/${rule.convergence.maxCount}次` : '关闭'}
                      </Badge>
                    </div>
                    <div className="flex items-center gap-2">
                      <span className="text-muted-foreground">接收人:</span>
                      <span>{rule.notification.recipients.join(', ')}</span>
                    </div>
                  </div>
                </div>
              ))}
            </div>
          </Card>
        </TabsContent>

        {/* 告警分析 */}
        <TabsContent value="analytics">
          <div className="space-y-6">
            <div className="grid grid-cols-2 gap-6">
              {/* 告警趋势 */}
              <Card className="p-6">
                <h3 className="mb-4">告警趋势 (最近7天)</h3>
                <ResponsiveContainer width="100%" height={300}>
                  <AreaChart data={alertTrend}>
                    <CartesianGrid strokeDasharray="3 3" />
                    <XAxis dataKey="date" />
                    <YAxis />
                    <RechartsTooltip />
                    <Legend />
                    <Area type="monotone" dataKey="critical" stackId="1" stroke="#ef4444" fill="#fee2e2" name="严重" />
                    <Area type="monotone" dataKey="warning" stackId="1" stroke="#f59e0b" fill="#fed7aa" name="警告" />
                    <Area type="monotone" dataKey="info" stackId="1" stroke="#3b82f6" fill="#dbeafe" name="提示" />
                  </AreaChart>
                </ResponsiveContainer>
              </Card>

              {/* 告警类型分布 */}
              <Card className="p-6">
                <h3 className="mb-4">告警类型分布</h3>
                <ResponsiveContainer width="100%" height={300}>
                  <RechartsPie>
                    <Pie
                      data={alertTypeData}
                      cx="50%"
                      cy="50%"
                      labelLine={false}
                      label={({ name, percent }) => `${name} ${(percent * 100).toFixed(0)}%`}
                      outerRadius={100}
                      fill="#8884d8"
                      dataKey="value"
                    >
                      {alertTypeData.map((entry, index) => (
                        <Cell key={`cell-${index}`} fill={entry.color} />
                      ))}
                    </Pie>
                    <RechartsTooltip />
                  </RechartsPie>
                </ResponsiveContainer>
              </Card>
            </div>

            {/* 处理时长分布 */}
            <Card className="p-6">
              <div className="flex items-center justify-between mb-4">
                <h3>告警处理时长分布</h3>
                <Badge variant="outline" className="text-xs">
                  <Clock className="w-3 h-3 mr-1" />
                  统计周期：最近30天
                </Badge>
              </div>
              <div className="mb-3 p-3 bg-info-muted border border-info/30 rounded-lg">
                <p className="text-sm text-info-muted-foreground">
                  <strong>统计说明：</strong>展示最近30天内已处理告警从触发到解决的时长分布情况
                </p>
              </div>
              <ResponsiveContainer width="100%" height={300}>
                <BarChart data={responseTimeData}>
                  <CartesianGrid strokeDasharray="3 3" />
                  <XAxis dataKey="range" />
                  <YAxis />
                  <RechartsTooltip />
                  <Legend />
                  <Bar dataKey="count" fill="#8b5cf6" name="告警数量" />
                </BarChart>
              </ResponsiveContainer>
            </Card>
          </div>
        </TabsContent>
      </Tabs>

      {/* 告警详情对话框 */}
      <Dialog open={showAlertDetail} onOpenChange={setShowAlertDetail}>
        <DialogContent className="max-w-4xl max-h-[90vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle>告警详情</DialogTitle>
            <DialogDescription>
              查看告警的完整信息和处理记录
            </DialogDescription>
          </DialogHeader>

          {selectedAlert && (
            <div className="space-y-6">
              {/* 基本信息 */}
              <div>
                <h4 className="mb-3">基本信息</h4>
                <div className="grid grid-cols-2 gap-4">
                  <div className="p-3 bg-muted rounded">
                    <div className="text-xs text-muted-foreground mb-1">告警编号</div>
                    <div className="font-medium">{selectedAlert.alertNo}</div>
                  </div>
                  <div className="p-3 bg-muted rounded">
                    <div className="text-xs text-muted-foreground mb-1">告警规则</div>
                    <div className="font-medium">{selectedAlert.ruleName}</div>
                  </div>
                  <div className="p-3 bg-muted rounded">
                    <div className="text-xs text-muted-foreground mb-1">告警级别</div>
                    <div>{getLevelBadge(selectedAlert.level)}</div>
                  </div>
                  <div className="p-3 bg-muted rounded">
                    <div className="text-xs text-muted-foreground mb-1">处理状态</div>
                    <div>{getStatusBadge(selectedAlert.status)}</div>
                  </div>
                </div>
              </div>

              {/* 告警内容 */}
              <div>
                <h4 className="mb-3">告警内容</h4>
                <div className="p-4 bg-error-muted border border-error/30 rounded-lg">
                  <h4 className="text-error-muted-foreground mb-2">{selectedAlert.title}</h4>
                  <p className="text-sm text-error-muted-foreground mb-2">{selectedAlert.content}</p>
                  <div className="text-sm text-muted-foreground">
                    来源: {selectedAlert.source}
                  </div>
                </div>
              </div>

              {/* 触发信息 */}
              <div>
                <h4 className="mb-3">触发信息</h4>
                <div className="grid grid-cols-3 gap-4">
                  <div className="p-3 bg-muted rounded">
                    <div className="text-xs text-muted-foreground mb-1">触发值</div>
                    <div className="font-medium">{selectedAlert.triggerValue}</div>
                  </div>
                  <div className="p-3 bg-muted rounded">
                    <div className="text-xs text-muted-foreground mb-1">阈值</div>
                    <div className="font-medium">{selectedAlert.threshold}</div>
                  </div>
                  <div className="p-3 bg-muted rounded">
                    <div className="text-xs text-muted-foreground mb-1">触发时间</div>
                    <div className="font-medium">{selectedAlert.triggerTime}</div>
                  </div>
                </div>
              </div>

              {/* 通知信息 */}
              <div>
                <h4 className="mb-3">通知信息</h4>
                <div className="p-4 bg-info-muted border border-info/30 rounded-lg">
                  <div className="flex items-center gap-4 mb-2">
                    {selectedAlert.notifyChannels.map((channel) => {
                      const Icon = getChannelIcon(channel);
                      const status = selectedAlert.notifyStatus[channel];
                      return (
                        <div key={channel} className="flex items-center gap-2">
                          <Icon className="w-4 h-4" />
                          <span className="text-sm">{getChannelName(channel)}</span>
                          <Badge className={status === 'success' ? 'bg-success text-success-foreground' : 'bg-error text-error-foreground'}>
                            {status === 'success' ? '成功' : '失败'}
                          </Badge>
                        </div>
                      );
                    })}
                  </div>
                  <div className="text-sm text-muted-foreground">
                    通知时间: {selectedAlert.notifyTime}
                  </div>
                </div>
              </div>

              {/* 处理记录 */}
              {(selectedAlert.acknowledgedAt || selectedAlert.processingAt || selectedAlert.resolvedAt) && (
                <div>
                  <h4 className="mb-3">处理记录</h4>
                  <div className="space-y-3">
                    {selectedAlert.acknowledgedAt && (
                      <div className="p-4 bg-info-muted border border-info/30 rounded-lg">
                        <div className="flex items-center gap-2 mb-2">
                          <CheckCircle className="w-4 h-4 text-info" />
                          <span className="font-medium">已确认</span>
                          <Badge className="bg-info text-info-foreground">{selectedAlert.acknowledgedBy}</Badge>
                          <span className="text-sm text-muted-foreground">{selectedAlert.acknowledgedAt}</span>
                        </div>
                        {selectedAlert.acknowledgedNote && (
                          <p className="text-sm text-info-muted-foreground">{selectedAlert.acknowledgedNote}</p>
                        )}
                      </div>
                    )}

                    {selectedAlert.processingAt && (
                      <div className="p-4 bg-accent border border-accent rounded-lg">
                        <div className="flex items-center gap-2 mb-2">
                          <Activity className="w-4 h-4 text-accent-foreground" />
                          <span className="font-medium">处理中</span>
                          <Badge className="bg-accent-foreground text-accent">{selectedAlert.processingBy}</Badge>
                          <span className="text-sm text-muted-foreground">{selectedAlert.processingAt}</span>
                        </div>
                        {selectedAlert.processingNote && (
                          <p className="text-sm text-accent-foreground">{selectedAlert.processingNote}</p>
                        )}
                      </div>
                    )}

                    {selectedAlert.resolvedAt && (
                      <div className="p-4 bg-success-muted border border-success/30 rounded-lg">
                        <div className="flex items-center gap-2 mb-2">
                          <CheckCircle className="w-4 h-4 text-success" />
                          <span className="font-medium">已解决</span>
                          <Badge className="bg-success text-success-foreground">{selectedAlert.resolvedBy}</Badge>
                          <span className="text-sm text-muted-foreground">{selectedAlert.resolvedAt}</span>
                        </div>
                        {selectedAlert.resolution && (
                          <div className="mb-2">
                            <div className="text-sm font-medium text-success-muted-foreground">解决方案:</div>
                            <p className="text-sm text-success-muted-foreground">{selectedAlert.resolution}</p>
                          </div>
                        )}
                        {selectedAlert.resolvedNote && (
                          <p className="text-sm text-success-muted-foreground">{selectedAlert.resolvedNote}</p>
                        )}
                      </div>
                    )}
                  </div>
                </div>
              )}
            </div>
          )}

          <DialogFooter>
            <Button variant="outline" onClick={() => setShowAlertDetail(false)}>关闭</Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* 确认告警对话框 */}
      <Dialog open={showHandleDialog} onOpenChange={setShowHandleDialog}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>确认告警</DialogTitle>
            <DialogDescription>
              确认已知晓该告警，并添加处理备注
            </DialogDescription>
          </DialogHeader>

          <div className="space-y-4">
            <div>
              <Label>处理备注</Label>
              <Textarea
                placeholder="请输入处理备注..."
                rows={4}
                value={handleNote}
                onChange={(e) => setHandleNote(e.target.value)}
              />
            </div>
          </div>

          <DialogFooter>
            <Button variant="outline" onClick={() => setShowHandleDialog(false)}>取消</Button>
            <Button onClick={submitHandle}>
              确认
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* 开始处理对话框 */}
      <Dialog open={showProcessDialog} onOpenChange={setShowProcessDialog}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>开始处理告警</DialogTitle>
            <DialogDescription>
              标记告警为处理中状态，并记录处理说明
            </DialogDescription>
          </DialogHeader>

          <div className="space-y-4">
            <div>
              <Label>处理说明</Label>
              <Textarea
                placeholder="请输入处理说明，如：正在排查问题原因..."
                rows={4}
                value={handleNote}
                onChange={(e) => setHandleNote(e.target.value)}
              />
            </div>
          </div>

          <DialogFooter>
            <Button variant="outline" onClick={() => setShowProcessDialog(false)}>取消</Button>
            <Button onClick={submitHandle}>
              <Play className="w-4 h-4 mr-2" />
              开始处理
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* 解决告警对话框 */}
      <Dialog open={showResolveDialog} onOpenChange={setShowResolveDialog}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>解决告警</DialogTitle>
            <DialogDescription>
              标记告警为已解决状态，并记录解决方案
            </DialogDescription>
          </DialogHeader>

          <div className="space-y-4">
            <div>
              <Label>解决方案</Label>
              <Textarea
                placeholder="请输入解决方案，如：已重启服务，问题已解决..."
                rows={4}
                value={handleNote}
                onChange={(e) => setHandleNote(e.target.value)}
              />
            </div>
          </div>

          <DialogFooter>
            <Button variant="outline" onClick={() => setShowResolveDialog(false)}>取消</Button>
            <Button onClick={submitHandle} className="bg-success hover:bg-success/90">
              <CheckCheck className="w-4 h-4 mr-2" />
              解决
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* 删除规则确认对话框 */}
      <AlertDialog open={showDeleteConfirm} onOpenChange={setShowDeleteConfirm}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>确认删除告警规则</AlertDialogTitle>
            <AlertDialogDescription>
              此操作将永久删除该告警规则，删除后将不再触发相关告警。此操作不可撤销，是否继续?
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel>取消</AlertDialogCancel>
            <AlertDialogAction onClick={confirmDeleteRule} className="bg-destructive hover:bg-destructive/90">
              确认删除
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>

      {/* 规则配置对话框 */}
      <Dialog open={showRuleDialog} onOpenChange={setShowRuleDialog}>
        <DialogContent className="max-w-3xl max-h-[90vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle>{isEditing ? '编辑告警规则' : '新建告警规则'}</DialogTitle>
            <DialogDescription>
              配置告警规则的触发条件、通知方式和收敛策略
            </DialogDescription>
          </DialogHeader>

          <div className="space-y-6">
            {/* 基本信息 */}
            <div>
              <h4 className="mb-3">基本信息</h4>
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <Label>规则名称</Label>
                  <Input placeholder="请输入规则名称" defaultValue={selectedRule?.ruleName} className="mt-2" />
                </div>
                <div>
                  <Label>告警类型</Label>
                  <Select defaultValue={selectedRule?.alertType || 'model_service'}>
                    <SelectTrigger className="mt-2">
                      <SelectValue />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="model_service">模型服务</SelectItem>
                      <SelectItem value="decision_failure">决策失败</SelectItem>
                      <SelectItem value="data_quality">数据质量</SelectItem>
                      <SelectItem value="system_resource">系统资源</SelectItem>
                      <SelectItem value="business_rule">业务规则</SelectItem>
                    </SelectContent>
                  </Select>
                </div>
              </div>
              <div className="mt-4">
                <Label>告警级别</Label>
                <Select defaultValue={selectedRule?.level || 'warning'}>
                  <SelectTrigger className="mt-2">
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="info">提示</SelectItem>
                    <SelectItem value="warning">警告</SelectItem>
                    <SelectItem value="critical">严重</SelectItem>
                  </SelectContent>
                </Select>
              </div>
            </div>

            {/* 触发条件配置 */}
            <div>
              <h4 className="mb-3">触发条件配置</h4>
              <div className="space-y-4">
                <div>
                  <Label>触发条件类型</Label>
                  <Select 
                    value={triggerConditionType} 
                    onValueChange={setTriggerConditionType}
                  >
                    <SelectTrigger className="mt-2">
                      <SelectValue />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="response_time">请求响应时间</SelectItem>
                      <SelectItem value="service_exception">模型服务异常</SelectItem>
                      <SelectItem value="decision_failure">决策生成失败</SelectItem>
                      <SelectItem value="data_quality">数据质量异常</SelectItem>
                      <SelectItem value="cpu_usage">CPU使用率</SelectItem>
                      <SelectItem value="memory_usage">内存使用率</SelectItem>
                      <SelectItem value="error_rate">错误率</SelectItem>
                      <SelectItem value="request_count">请求数量</SelectItem>
                    </SelectContent>
                  </Select>
                </div>

                {/* 根据条件类型显示不同的配置 */}
                {triggerConditionType === 'response_time' && (
                  <div className="p-4 bg-muted rounded-lg space-y-3">
                    <div className="grid grid-cols-2 gap-4">
                      <div>
                        <Label>响应时间阈值 (ms)</Label>
                        <Input type="number" placeholder="500" defaultValue={selectedRule?.condition.threshold} className="mt-2" />
                      </div>
                      <div>
                        <Label>持续时间 (秒)</Label>
                        <Input type="number" placeholder="60" defaultValue={selectedRule?.condition.duration} className="mt-2" />
                      </div>
                    </div>
                    <p className="text-sm text-muted-foreground">
                      当平均响应时间超过阈值并持续指定时间后触发告警
                    </p>
                  </div>
                )}

                {triggerConditionType === 'service_exception' && (
                  <div className="p-4 bg-muted rounded-lg space-y-3">
                    <div className="grid grid-cols-2 gap-4">
                      <div>
                        <Label>异常类型</Label>
                        <Select defaultValue="connection_timeout">
                          <SelectTrigger className="mt-2">
                            <SelectValue />
                          </SelectTrigger>
                          <SelectContent>
                            <SelectItem value="connection_timeout">连接超时</SelectItem>
                            <SelectItem value="service_unavailable">服务不可用</SelectItem>
                            <SelectItem value="api_error">API错误</SelectItem>
                            <SelectItem value="network_error">网络错误</SelectItem>
                          </SelectContent>
                        </Select>
                      </div>
                      <div>
                        <Label>最小异常次数</Label>
                        <Input type="number" placeholder="3" defaultValue="3" className="mt-2" />
                      </div>
                    </div>
                    <p className="text-sm text-muted-foreground">
                      当检测到服务异常达到指定次数后触发告警
                    </p>
                  </div>
                )}

                {triggerConditionType === 'decision_failure' && (
                  <div className="p-4 bg-muted rounded-lg space-y-3">
                    <div className="grid grid-cols-2 gap-4">
                      <div>
                        <Label>失败率阈值 (%)</Label>
                        <Input type="number" placeholder="5" defaultValue="5" className="mt-2" />
                      </div>
                      <div>
                        <Label>统计时间窗口 (分钟)</Label>
                        <Input type="number" placeholder="10" defaultValue="10" className="mt-2" />
                      </div>
                    </div>
                    <div>
                      <Label>失败原因</Label>
                      <Select defaultValue="all">
                        <SelectTrigger className="mt-2">
                          <SelectValue />
                        </SelectTrigger>
                        <SelectContent>
                          <SelectItem value="all">所有失败</SelectItem>
                          <SelectItem value="model_error">模型错误</SelectItem>
                          <SelectItem value="data_error">数据错误</SelectItem>
                          <SelectItem value="timeout">超时</SelectItem>
                          <SelectItem value="validation_error">验证失败</SelectItem>
                        </SelectContent>
                      </Select>
                    </div>
                    <p className="text-sm text-muted-foreground">
                      当决策生成失败率超过阈值时触发告警
                    </p>
                  </div>
                )}

                {triggerConditionType === 'data_quality' && (
                  <div className="p-4 bg-muted rounded-lg space-y-3">
                    <div className="grid grid-cols-2 gap-4">
                      <div>
                        <Label>数据质量评分阈值</Label>
                        <Input type="number" placeholder="60" defaultValue="60" className="mt-2" />
                      </div>
                      <div>
                        <Label>持续时间 (分钟)</Label>
                        <Input type="number" placeholder="5" defaultValue="5" className="mt-2" />
                      </div>
                    </div>
                    <div>
                      <Label>异常指标</Label>
                      <div className="flex gap-4 mt-2">
                        <label className="flex items-center gap-2">
                          <input type="checkbox" defaultChecked />
                          <span className="text-sm">数据缺失</span>
                        </label>
                        <label className="flex items-center gap-2">
                          <input type="checkbox" defaultChecked />
                          <span className="text-sm">数据异常</span>
                        </label>
                        <label className="flex items-center gap-2">
                          <input type="checkbox" />
                          <span className="text-sm">数据延迟</span>
                        </label>
                      </div>
                    </div>
                    <p className="text-sm text-muted-foreground">
                      当数据质量评分低于阈值时触发告警
                    </p>
                  </div>
                )}

                {(triggerConditionType === 'cpu_usage' || triggerConditionType === 'memory_usage') && (
                  <div className="p-4 bg-muted rounded-lg space-y-3">
                    <div className="grid grid-cols-2 gap-4">
                      <div>
                        <Label>使用率阈值 (%)</Label>
                        <Input type="number" placeholder={triggerConditionType === 'cpu_usage' ? '85' : '90'} className="mt-2" />
                      </div>
                      <div>
                        <Label>持续时间 (秒)</Label>
                        <Input type="number" placeholder="120" className="mt-2" />
                      </div>
                    </div>
                    <p className="text-sm text-muted-foreground">
                      当{triggerConditionType === 'cpu_usage' ? 'CPU' : '内存'}使用率持续超过阈值时触发告警
                    </p>
                  </div>
                )}

                {triggerConditionType === 'error_rate' && (
                  <div className="p-4 bg-muted rounded-lg space-y-3">
                    <div className="grid grid-cols-2 gap-4">
                      <div>
                        <Label>错误率阈值 (%)</Label>
                        <Input type="number" placeholder="1" defaultValue="1" className="mt-2" />
                      </div>
                      <div>
                        <Label>统计时间窗口 (分钟)</Label>
                        <Input type="number" placeholder="5" defaultValue="5" className="mt-2" />
                      </div>
                    </div>
                    <p className="text-sm text-muted-foreground">
                      当系统错误率超过阈值时触发告警
                    </p>
                  </div>
                )}

                {triggerConditionType === 'request_count' && (
                  <div className="p-4 bg-muted rounded-lg space-y-3">
                    <div className="grid grid-cols-2 gap-4">
                      <div>
                        <Label>请求数阈值</Label>
                        <Input type="number" placeholder="1000" defaultValue="1000" className="mt-2" />
                      </div>
                      <div>
                        <Label>统计时间窗口 (分钟)</Label>
                        <Input type="number" placeholder="1" defaultValue="1" className="mt-2" />
                      </div>
                    </div>
                    <div>
                      <Label>比较方式</Label>
                      <Select defaultValue="greater">
                        <SelectTrigger className="mt-2">
                          <SelectValue />
                        </SelectTrigger>
                        <SelectContent>
                          <SelectItem value="greater">大于阈值</SelectItem>
                          <SelectItem value="less">小于阈值</SelectItem>
                        </SelectContent>
                      </Select>
                    </div>
                    <p className="text-sm text-muted-foreground">
                      当请求数量异常时触发告警
                    </p>
                  </div>
                )}
              </div>
            </div>

            {/* 通知配置 */}
            <div>
              <h4 className="mb-3">通知配置</h4>
              <div>
                <Label>通知渠道</Label>
                <div className="flex gap-4 mt-2">
                  <label className="flex items-center gap-2">
                    <input type="checkbox" defaultChecked={selectedRule?.notification.channels.includes('sms')} />
                    <span className="text-sm">短信</span>
                  </label>
                  <label className="flex items-center gap-2">
                    <input type="checkbox" defaultChecked={selectedRule?.notification.channels.includes('email')} />
                    <span className="text-sm">邮件</span>
                  </label>
                  <label className="flex items-center gap-2">
                    <input type="checkbox" defaultChecked={selectedRule?.notification.channels.includes('app')} />
                    <span className="text-sm">站内信</span>
                  </label>
                </div>
              </div>
            </div>

            {/* 描述 */}
            <div>
              <Label>规则描述</Label>
              <Textarea placeholder="请输入规则描述..." rows={3} className="mt-2" />
            </div>
          </div>

          <DialogFooter>
            <Button variant="outline" onClick={() => setShowRuleDialog(false)}>取消</Button>
            <Button onClick={handleSaveRule}>
              {isEditing ? '保存' : '创建'}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* 保存规则确认对话框 */}
      <AlertDialog open={showSaveRuleConfirm} onOpenChange={setShowSaveRuleConfirm}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>{isEditing ? '确认更新告警规则' : '确认创建告警规则'}</AlertDialogTitle>
            <AlertDialogDescription>
              {isEditing 
                ? '规则更新后将立即生效，可能会影响现有的告警触发逻辑。是否确认更新?' 
                : '新规则创建后将立即生效并开始监控。是否确认创建?'}
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel>取消</AlertDialogCancel>
            <AlertDialogAction onClick={confirmSaveRule}>
              确认{isEditing ? '更新' : '创建'}
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </div>
  );
}
