import { useState, useEffect } 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 {
  AlertTriangle,
  Bell,
  BellRing,
  CheckCircle,
  XCircle,
  Settings,
  Plus,
  Edit,
  Trash2,
  Eye,
  Mail,
  MessageSquare,
  Phone,
  Users,
  Activity,
  TrendingUp,
  Zap,
  Droplets,
  ThermometerSun,
  Gauge,
  TestTube,
  Clock,
  Calendar,
  Download,
  RefreshCw,
  AlertCircle,
  Shield,
  Target,
  Filter,
  Send,
} from 'lucide-react';
import { toast } from 'sonner@2.0.3';

interface MonitoringAlertProps {
  activePath?: string;
}

type AlertLevel = '提示' | '警告' | '严重';
type AlertStatus = '启用' | '禁用';
type NotificationChannel = '短信' | '邮件' | '站内信';
type ConditionOperator = '且' | '或';
type ComparisonOperator = '>' | '<' | '=' | '>=' | '<=';

interface AlertCondition {
  id: string;
  parameter: string;
  operator: ComparisonOperator;
  value: number;
  unit: string;
}

interface AlertRule {
  id: string;
  name: string;
  description: string;
  status: AlertStatus;
  level: AlertLevel;
  conditions: AlertCondition[];
  conditionOperator: ConditionOperator;
  duration: number; // 持续时间（分钟）
  createdAt: string;
  triggeredCount: number;
  lastTriggered?: string;
}

interface ThresholdConfig {
  id: string;
  parameter: string;
  category: string;
  minValue?: number;
  maxValue?: number;
  warningMin?: number;
  warningMax?: number;
  criticalMin?: number;
  criticalMax?: number;
  unit: string;
  currentValue: number;
  status: '正常' | '警告' | '严重';
  enabled: boolean;
}

interface AlertRecord {
  id: string;
  ruleName: string;
  level: AlertLevel;
  message: string;
  triggeredAt: string;
  status: '待处理' | '处理中' | '已处理';
  handler?: string;
  handledAt?: string;
  channels: NotificationChannel[];
}

interface NotificationContact {
  id: string;
  name: string;
  phone: string;
  email: string;
  role: string;
  enabled: boolean;
  channels: NotificationChannel[];
}

export function MonitoringAlert({ activePath }: MonitoringAlertProps) {
  const [activeTab, setActiveTab] = useState('alert-logic');
  const [showRuleDialog, setShowRuleDialog] = useState(false);
  const [showThresholdDialog, setShowThresholdDialog] = useState(false);
  const [showAlertDetailDialog, setShowAlertDetailDialog] = useState(false);
  const [editingRule, setEditingRule] = useState<AlertRule | null>(null);
  const [editingThreshold, setEditingThreshold] = useState<ThresholdConfig | null>(null);
  const [viewingAlert, setViewingAlert] = useState<AlertRecord | null>(null);
  
  // 删除确认对话框
  const [showDeleteConfirm, setShowDeleteConfirm] = useState(false);
  const [ruleToDelete, setRuleToDelete] = useState<string | null>(null);
  
  // 联系人删除确认对话框
  const [showDeleteContactConfirm, setShowDeleteContactConfirm] = useState(false);
  const [contactToDelete, setContactToDelete] = useState<NotificationContact | null>(null);
  
  // 新建规则时的触发条件管理
  const [ruleConditions, setRuleConditions] = useState<Array<{
    id: string;
    device: string;
    parameter: string;
    operator: ComparisonOperator;
    value: string;
  }>>([]);
  
  // 规则表单数据
  const [ruleName, setRuleName] = useState('');
  const [ruleDescription, setRuleDescription] = useState('');
  const [ruleLevel, setRuleLevel] = useState<AlertLevel>('警告');
  const [conditionOperator, setConditionOperator] = useState<ConditionOperator>('且');
  const [ruleDuration, setRuleDuration] = useState(0);
  
  // 阈值配置表单数据
  const [selectedComponent, setSelectedComponent] = useState('');
  const [selectedParameter, setSelectedParameter] = useState('');
  const [thresholdWarningMin, setThresholdWarningMin] = useState<number>(0);
  const [thresholdWarningMax, setThresholdWarningMax] = useState<number>(0);

  // 通知方式启用状态
  const [smsEnabled, setSmsEnabled] = useState(true);
  const [emailEnabled, setEmailEnabled] = useState(true);
  const [inAppEnabled, setInAppEnabled] = useState(true);

  // 根据路径自动切换Tab
  useEffect(() => {
    if (activePath) {
      if (activePath.includes('/alert-logic')) {
        setActiveTab('alert-logic');
      } else if (activePath.includes('/threshold-alert')) {
        setActiveTab('threshold-alert');
      } else if (activePath.includes('/notification-push')) {
        setActiveTab('notification-push');
      }
    }
  }, [activePath]);

  // 预警规则
  const [alertRules, setAlertRules] = useState<AlertRule[]>([
    {
      id: 'rule-1',
      name: '土壤湿度持续低位预警',
      description: '当土壤湿度连续1小时低于30%且天气预报无雨时，触发灌溉预警',
      status: '启用',
      level: '警告',
      conditions: [
        { id: 'cond-1', parameter: '土壤湿度', operator: '<', value: 30, unit: '%' },
        { id: 'cond-2', parameter: '天气预报', operator: '=', value: 0, unit: '降雨概率' },
      ],
      conditionOperator: '且',
      duration: 60,
      createdAt: '2024-10-10 10:00:00',
      triggeredCount: 12,
      lastTriggered: '2024-10-15 14:30:00',
    },
    {
      id: 'rule-2',
      name: 'EC值异常预警',
      description: '当EC值超出目标范围±0.5时，立即触发预警',
      status: '启用',
      level: '严重',
      conditions: [
        { id: 'cond-3', parameter: 'EC偏差', operator: '>', value: 0.5, unit: 'mS/cm' },
      ],
      conditionOperator: '且',
      duration: 0,
      createdAt: '2024-10-08 15:00:00',
      triggeredCount: 5,
      lastTriggered: '2024-10-14 09:15:00',
    },
    {
      id: 'rule-3',
      name: '水压异常预警',
      description: '当水压低于1.5bar或高于4.5bar时，触发预警',
      status: '启用',
      level: '警告',
      conditions: [
        { id: 'cond-4', parameter: '水压', operator: '<', value: 1.5, unit: 'bar' },
        { id: 'cond-5', parameter: '水压', operator: '>', value: 4.5, unit: 'bar' },
      ],
      conditionOperator: '或',
      duration: 5,
      createdAt: '2024-10-05 12:00:00',
      triggeredCount: 8,
      lastTriggered: '2024-10-13 16:45:00',
    },
  ]);

  // 阈值配置
  const [thresholdConfigs, setThresholdConfigs] = useState<ThresholdConfig[]>([
    {
      id: 'th-1',
      parameter: 'EC值',
      category: '水质参数',
      minValue: 1.5,
      maxValue: 4.0,
      warningMin: 1.8,
      warningMax: 3.5,
      criticalMin: 1.5,
      criticalMax: 4.0,
      unit: 'mS/cm',
      currentValue: 2.35,
      status: '正常',
      enabled: true,
    },
    {
      id: 'th-2',
      parameter: 'PH值',
      category: '水质参数',
      minValue: 5.5,
      maxValue: 7.5,
      warningMin: 6.0,
      warningMax: 7.0,
      criticalMin: 5.5,
      criticalMax: 7.5,
      unit: 'pH',
      currentValue: 6.8,
      status: '正常',
      enabled: true,
    },
    {
      id: 'th-3',
      parameter: '水压',
      category: '设备参数',
      minValue: 1.5,
      maxValue: 4.5,
      warningMin: 2.0,
      warningMax: 4.0,
      criticalMin: 1.5,
      criticalMax: 4.5,
      unit: 'bar',
      currentValue: 2.8,
      status: '正常',
      enabled: true,
    },
    {
      id: 'th-4',
      parameter: '土壤湿度',
      category: '环境参数',
      minValue: 30,
      maxValue: 85,
      warningMin: 35,
      warningMax: 80,
      criticalMin: 30,
      criticalMax: 85,
      unit: '%',
      currentValue: 65,
      status: '正常',
      enabled: true,
    },
    {
      id: 'th-5',
      parameter: '液位',
      category: '设备参数',
      minValue: 100,
      maxValue: 450,
      warningMin: 150,
      warningMax: 400,
      criticalMin: 100,
      criticalMax: 450,
      unit: 'L',
      currentValue: 320,
      status: '正常',
      enabled: true,
    },
    {
      id: 'th-6',
      parameter: '电池电压',
      category: '设备参数',
      minValue: 10.5,
      maxValue: 13.5,
      warningMin: 11.0,
      warningMax: 13.0,
      criticalMin: 10.5,
      criticalMax: 13.5,
      unit: 'V',
      currentValue: 10.8,
      status: '警告',
      enabled: true,
    },
  ]);

  // 告警记录
  const [alertRecords, setAlertRecords] = useState<AlertRecord[]>([
    {
      id: 'alert-1',
      ruleName: '土壤湿度持续低位预警',
      level: '警告',
      message: '1号大棚土壤湿度已连续1小时低于30%，且未来24小时无降雨，建议立即启动灌溉',
      triggeredAt: '2024-10-15 14:30:00',
      status: '已处理',
      handler: '张三',
      handledAt: '2024-10-15 14:35:00',
      channels: ['短信', '邮件'],
    },
    {
      id: 'alert-2',
      ruleName: 'EC值异常预警',
      level: '严重',
      message: '水肥机EC值当前2.85，超出目标值2.5范围0.35，请检查肥料配比',
      triggeredAt: '2024-10-15 16:20:00',
      status: '处理中',
      handler: '李四',
      channels: ['短信', '邮件', '站内信'],
    },
    {
      id: 'alert-3',
      ruleName: '电池电压低预警',
      level: '提示',
      message: 'V-04阀门电池电压10.5V，已接近下限，请及时充电或更换电池',
      triggeredAt: '2024-10-15 17:10:00',
      status: '待处理',
      channels: ['站内信'],
    },
    {
      id: 'alert-4',
      ruleName: '水压异常预警',
      level: '警告',
      message: 'V-01阀门水压持续5分钟低于1.5bar，可能存在管道泄漏或水泵故障',
      triggeredAt: '2024-10-15 18:05:00',
      status: '待处理',
      channels: ['短信', '邮件'],
    },
  ]);

  // 联系人 - 从用户管理系统获取
  const [contacts, setContacts] = useState<NotificationContact[]>([]);
  const [systemUsers, setSystemUsers] = useState<any[]>([]);
  const [selectedUserId, setSelectedUserId] = useState('');

  // 从用户管理系统加载用户
  useEffect(() => {
    const data = localStorage.getItem('smart_agriculture_users');
    if (data) {
      const users = JSON.parse(data);
      setSystemUsers(users);
      
      // 初始化已选择的通知人（如果没有则初始化样例数据）
      const savedContacts = localStorage.getItem('irrigation_notification_contacts');
      if (savedContacts) {
        setContacts(JSON.parse(savedContacts));
      } else {
        // 初始化样例数据 - 从用户系统中选择前3个活跃用户
        const activeUsers = users.filter((u: any) => u.status === 'active').slice(0, 3);
        if (activeUsers.length > 0) {
          const sampleContacts: NotificationContact[] = activeUsers.map((user: any, index: number) => ({
            id: user.id,
            name: user.name,
            phone: user.phone || '',
            email: user.email || '',
            role: user.roles?.[0] || user.userType,
            enabled: true,
            // 第一个用户接收所有通知渠道，第二个用户短信+邮件，第三个用户短信+站内信
            channels: index === 0 
              ? ['短信', '邮件', '站内信'] 
              : index === 1 
              ? ['短信', '邮件']
              : ['短信', '站内信'],
          }));
          setContacts(sampleContacts);
        } else {
          // 如果用户系统中没有用户，使用固定的样例数据
          setContacts([
            {
              id: 'sample-1',
              name: '系统管理员',
              phone: '13900000000',
              email: 'admin@system.com',
              role: '超级管理员',
              enabled: true,
              channels: ['短信', '邮件', '站内信'],
            },
            {
              id: 'sample-2',
              name: '李总',
              phone: '13900139002',
              email: 'litotal@fengshou.com',
              role: '企业管理员',
              enabled: true,
              channels: ['短信', '邮件'],
            },
            {
              id: 'sample-3',
              name: '张三',
              phone: '13800138001',
              email: 'zhangsan@fengshou.com',
              role: '操作员',
              enabled: true,
              channels: ['短信', '站内信'],
            },
          ]);
        }
      }
    } else {
      // 如果没有用户管理数据，直接使用固定样例数据
      const savedContacts = localStorage.getItem('irrigation_notification_contacts');
      if (savedContacts) {
        setContacts(JSON.parse(savedContacts));
      } else {
        setContacts([
          {
            id: 'sample-1',
            name: '系统管理员',
            phone: '13900000000',
            email: 'admin@system.com',
            role: '超级管理员',
            enabled: true,
            channels: ['短信', '邮件', '站内信'],
          },
          {
            id: 'sample-2',
            name: '李总',
            phone: '13900139002',
            email: 'litotal@fengshou.com',
            role: '企业管理员',
            enabled: true,
            channels: ['短信', '邮件'],
          },
          {
            id: 'sample-3',
            name: '张三',
            phone: '13800138001',
            email: 'zhangsan@fengshou.com',
            role: '操作员',
            enabled: true,
            channels: ['短信', '站内信'],
          },
        ]);
      }
    }
  }, []);

  // 保存通知人到localStorage
  useEffect(() => {
    if (contacts.length > 0) {
      localStorage.setItem('irrigation_notification_contacts', JSON.stringify(contacts));
    }
  }, [contacts]);

  const getParameterUnit = (parameter: string): string => {
    const unitMap: Record<string, string> = {
      'ec': 'mS/cm',
      'ph': 'pH',
      'water-pressure': 'bar',
      'flow-rate': 'L/h',
      'tank-level': 'L',
      'soil-moisture': '%',
      'soil-temperature': '℃',
      'air-temperature': '℃',
      'air-humidity': '%',
      'battery-voltage': 'V',
      'solar-voltage': 'V'
    };
    return unitMap[parameter] || '';
  };

  const getParameterLabel = (parameter: string): string => {
    const labelMap: Record<string, string> = {
      'ec': 'EC值',
      'ph': 'PH值',
      'water-pressure': '水压',
      'flow-rate': '流量',
      'tank-level': '液位',
      'soil-moisture': '土壤湿度',
      'soil-temperature': '土壤温度',
      'air-temperature': '气温',
      'air-humidity': '空气湿度',
      'battery-voltage': '电池电压',
      'solar-voltage': '光伏电压'
    };
    return labelMap[parameter] || parameter;
  };

  const getDeviceLabel = (device: string): string => {
    const labelMap: Record<string, string> = {
      'water-machine-1': '水肥机-01',
      'water-machine-2': '水肥机-02',
      'water-machine-3': '水肥机-03',
      'water-machine-4': '水肥机-04',
      'valve-1': '电动阀-V01',
      'valve-2': '电动阀-V02',
      'soil-sensor-1': '土壤传感器-01',
      'weather-station': '气象站'
    };
    return labelMap[device] || device;
  };

  // 水肥机部件配置
  const componentConfig = {
    'ec-sensor': { name: 'EC传感器', category: '水质参数' },
    'ph-sensor': { name: 'PH传感器', category: '水质参数' },
    'water-pressure': { name: '水压传感器', category: '设备参数' },
    'flow-meter': { name: '流量计', category: '设备参数' },
    'tank-level': { name: '液位传感器', category: '设备参数' },
    'fertilizer-pump-a': { name: 'A桶肥料泵', category: '设备参数' },
    'fertilizer-pump-b': { name: 'B桶肥料泵', category: '设备参数' },
    'fertilizer-pump-c': { name: 'C桶肥料泵', category: '设备参数' },
    'solenoid-valve-1': { name: '1号电磁阀', category: '设备参数' },
    'solenoid-valve-2': { name: '2号电磁阀', category: '设备参数' },
    'battery': { name: '电池', category: '设备参数' },
    'solar-panel': { name: '太阳能板', category: '设备参数' }
  };

  // 参数配置（根据部件联动）
  const parameterConfig: Record<string, Array<{
    key: string;
    name: string;
    minValue: number;
    maxValue: number;
    warningMin: number;
    warningMax: number;
    criticalMin: number;
    criticalMax: number;
    unit: string;
  }>> = {
    'ec-sensor': [
      {
        key: 'ec-value',
        name: 'EC值',
        minValue: 1.5,
        maxValue: 4.0,
        warningMin: 1.8,
        warningMax: 3.5,
        criticalMin: 1.5,
        criticalMax: 4.0,
        unit: 'mS/cm'
      }
    ],
    'ph-sensor': [
      {
        key: 'ph-value',
        name: 'PH值',
        minValue: 5.5,
        maxValue: 7.5,
        warningMin: 6.0,
        warningMax: 7.0,
        criticalMin: 5.5,
        criticalMax: 7.5,
        unit: 'pH'
      }
    ],
    'water-pressure': [
      {
        key: 'pressure',
        name: '水压',
        minValue: 1.5,
        maxValue: 4.5,
        warningMin: 2.0,
        warningMax: 4.0,
        criticalMin: 1.5,
        criticalMax: 4.5,
        unit: 'bar'
      }
    ],
    'flow-meter': [
      {
        key: 'flow-rate',
        name: '流量',
        minValue: 50,
        maxValue: 500,
        warningMin: 80,
        warningMax: 450,
        criticalMin: 50,
        criticalMax: 500,
        unit: 'L/h'
      }
    ],
    'tank-level': [
      {
        key: 'level',
        name: '液位',
        minValue: 100,
        maxValue: 450,
        warningMin: 150,
        warningMax: 400,
        criticalMin: 100,
        criticalMax: 450,
        unit: 'L'
      }
    ],
    'fertilizer-pump-a': [
      {
        key: 'pump-pressure',
        name: '泵压',
        minValue: 0.5,
        maxValue: 3.0,
        warningMin: 0.8,
        warningMax: 2.5,
        criticalMin: 0.5,
        criticalMax: 3.0,
        unit: 'bar'
      },
      {
        key: 'pump-flow',
        name: '泵流量',
        minValue: 10,
        maxValue: 100,
        warningMin: 20,
        warningMax: 90,
        criticalMin: 10,
        criticalMax: 100,
        unit: 'L/h'
      }
    ],
    'fertilizer-pump-b': [
      {
        key: 'pump-pressure',
        name: '泵压',
        minValue: 0.5,
        maxValue: 3.0,
        warningMin: 0.8,
        warningMax: 2.5,
        criticalMin: 0.5,
        criticalMax: 3.0,
        unit: 'bar'
      },
      {
        key: 'pump-flow',
        name: '泵流量',
        minValue: 10,
        maxValue: 100,
        warningMin: 20,
        warningMax: 90,
        criticalMin: 10,
        criticalMax: 100,
        unit: 'L/h'
      }
    ],
    'fertilizer-pump-c': [
      {
        key: 'pump-pressure',
        name: '泵压',
        minValue: 0.5,
        maxValue: 3.0,
        warningMin: 0.8,
        warningMax: 2.5,
        criticalMin: 0.5,
        criticalMax: 3.0,
        unit: 'bar'
      },
      {
        key: 'pump-flow',
        name: '泵流量',
        minValue: 10,
        maxValue: 100,
        warningMin: 20,
        warningMax: 90,
        criticalMin: 10,
        criticalMax: 100,
        unit: 'L/h'
      }
    ],
    'solenoid-valve-1': [
      {
        key: 'valve-status',
        name: '阀门状态',
        minValue: 0,
        maxValue: 1,
        warningMin: 0,
        warningMax: 1,
        criticalMin: 0,
        criticalMax: 1,
        unit: '开关'
      }
    ],
    'solenoid-valve-2': [
      {
        key: 'valve-status',
        name: '阀门状态',
        minValue: 0,
        maxValue: 1,
        warningMin: 0,
        warningMax: 1,
        criticalMin: 0,
        criticalMax: 1,
        unit: '开关'
      }
    ],
    'battery': [
      {
        key: 'voltage',
        name: '电池电压',
        minValue: 10.5,
        maxValue: 13.5,
        warningMin: 11.0,
        warningMax: 13.0,
        criticalMin: 10.5,
        criticalMax: 13.5,
        unit: 'V'
      }
    ],
    'solar-panel': [
      {
        key: 'voltage',
        name: '光伏电压',
        minValue: 12.0,
        maxValue: 18.0,
        warningMin: 13.0,
        warningMax: 17.0,
        criticalMin: 12.0,
        criticalMax: 18.0,
        unit: 'V'
      }
    ]
  };

  // 获取可选参数列表
  const getAvailableParameters = () => {
    if (!selectedComponent) return [];
    return parameterConfig[selectedComponent] || [];
  };

  // 获取当前选择的参数配置
  const getCurrentParameterConfig = () => {
    const params = getAvailableParameters();
    return params.find(p => p.key === selectedParameter);
  };

  const getLevelColor = (level: AlertLevel) => {
    switch (level) {
      case '提示': return 'bg-info-muted text-info-muted-foreground';
      case '警告': return 'bg-warning-muted text-warning-muted-foreground';
      case '严重': return 'bg-error-muted text-error-muted-foreground';
      default: return 'bg-muted text-muted-foreground';
    }
  };

  const getStatusColor = (status: ThresholdConfig['status']) => {
    switch (status) {
      case '正常': return 'bg-success-muted text-success-muted-foreground';
      case '警告': return 'bg-warning-muted text-warning-muted-foreground';
      case '严重': return 'bg-error-muted text-error-muted-foreground';
      default: return 'bg-muted text-muted-foreground';
    }
  };

  const getAlertStatusColor = (status: AlertRecord['status']) => {
    switch (status) {
      case '待处理': return 'bg-error-muted text-error-muted-foreground';
      case '处理中': return 'bg-warning-muted text-warning-muted-foreground';
      case '已处理': return 'bg-success-muted text-success-muted-foreground';
      default: return 'bg-muted text-muted-foreground';
    }
  };

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

  const confirmDeleteRule = () => {
    if (ruleToDelete) {
      const rule = alertRules.find(r => r.id === ruleToDelete);
      setAlertRules(alertRules.filter(r => r.id !== ruleToDelete));
      toast.success(`预警规则"${rule?.name}"已删除`);
      setRuleToDelete(null);
    }
    setShowDeleteConfirm(false);
  };

  const handleToggleRuleStatus = (ruleId: string) => {
    setAlertRules(alertRules.map(r => 
      r.id === ruleId 
        ? { ...r, status: r.status === '启用' ? '禁用' : '启用' }
        : r
    ));
    const rule = alertRules.find(r => r.id === ruleId);
    toast.success(`规则已${rule?.status === '启用' ? '禁用' : '启用'}`);
  };

  const handleToggleThreshold = (thresholdId: string) => {
    setThresholdConfigs(thresholdConfigs.map(t => 
      t.id === thresholdId 
        ? { ...t, enabled: !t.enabled }
        : t
    ));
    toast.success('阈值配置已更新');
  };

  const handleUpdateAlertStatus = (alertId: string, status: AlertRecord['status']) => {
    setAlertRecords(alertRecords.map(a => 
      a.id === alertId 
        ? { ...a, status, handler: status !== '待处理' ? '当前用户' : undefined }
        : a
    ));
    toast.success(`告警状态已更新为：${status}`);
  };

  const handleDeleteContact = (contact: NotificationContact) => {
    setContactToDelete(contact);
    setShowDeleteContactConfirm(true);
  };

  const confirmDeleteContact = () => {
    if (contactToDelete) {
      setContacts(contacts.filter(c => c.id !== contactToDelete.id));
      toast.success(`已移除通知用户：${contactToDelete.name}`);
      setContactToDelete(null);
    }
    setShowDeleteContactConfirm(false);
  };

  return (
    <div className="space-y-6">
      <div>
        <h2>实时监测与预警</h2>
        <p className="text-sm text-muted-foreground mt-1">
          预警逻辑、阈值告警、多通道推送
        </p>
      </div>

      {/* 统计卡片 */}
      <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
        <Card className="p-6">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-xs text-muted-foreground">预警规则</p>
              <p className="mt-2 text-3xl text-blue-600">
                {alertRules.filter(r => r.status === '启用').length}
              </p>
              <p className="text-xs text-blue-600 mt-1">/ {alertRules.length} 条</p>
            </div>
            <Shield className="w-12 h-12 text-blue-600 opacity-50" />
          </div>
        </Card>

        <Card className="p-6">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-xs text-muted-foreground">待处理告警</p>
              <p className="mt-2 text-3xl text-red-600">
                {alertRecords.filter(a => a.status === '待处理').length}
              </p>
              <p className="text-xs text-red-600 mt-1">条告警待处理</p>
            </div>
            <AlertTriangle className="w-12 h-12 text-red-600 opacity-50" />
          </div>
        </Card>

        <Card className="p-6">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-xs text-muted-foreground">阈值监控</p>
              <p className="mt-2 text-3xl text-green-600">
                {thresholdConfigs.filter(t => t.enabled).length}
              </p>
              <p className="text-xs text-green-600 mt-1">项参数监控中</p>
            </div>
            <Target className="w-12 h-12 text-green-600 opacity-50" />
          </div>
        </Card>

        <Card className="p-6">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-xs text-muted-foreground">通知联系人</p>
              <p className="mt-2 text-3xl text-purple-600">
                {contacts.filter(c => c.enabled).length}
              </p>
              <p className="text-xs text-purple-600 mt-1">位联系人</p>
            </div>
            <Users className="w-12 h-12 text-purple-600 opacity-50" />
          </div>
        </Card>
      </div>

      <Tabs value={activeTab} onValueChange={setActiveTab}>
        <TabsList className="grid w-full grid-cols-3">
          <TabsTrigger value="alert-logic">预警逻辑管理</TabsTrigger>
          <TabsTrigger value="threshold-alert">阈值预警与告警</TabsTrigger>
          <TabsTrigger value="notification-push">多通道告警推送</TabsTrigger>
        </TabsList>

        {/* 预警逻辑管理 */}
        <TabsContent value="alert-logic" className="space-y-4">
          <Card className="p-4 bg-gradient-to-r from-blue-50 to-cyan-50 border-blue-200">
            <div className="flex items-start gap-2">
              <Settings className="w-5 h-5 text-blue-600 flex-shrink-0 mt-0.5" />
              <div className="text-sm text-blue-900">
                <p className="mb-2">预警逻辑管理功能：</p>
                <ul className="space-y-1 text-xs">
                  <li>• <strong>多条件规则</strong>: 配置复杂的多条件预警规则</li>
                  <li>• <strong>逻辑组合</strong>: 支持"且"、"或"逻辑运算符</li>
                  <li>• <strong>条件判断</strong>: 参数对比、阈值判断、时间持续</li>
                  <li>• <strong>智能预警</strong>: 事前预警，提前发现潜在问题</li>
                  <li>• <strong>精准监测</strong>: 减少误报，提高预警准确性</li>
                  <li>• <strong>灵活配置</strong>: 启用/禁用规则，动态调整</li>
                </ul>
              </div>
            </div>
          </Card>

          <div className="flex gap-4">
            <Button className="bg-blue-600 hover:bg-blue-700" onClick={() => {
              setEditingRule(null);
              setRuleConditions([]);
              setRuleName('');
              setRuleDescription('');
              setRuleLevel('警告');
              setConditionOperator('且');
              setRuleDuration(0);
              setShowRuleDialog(true);
            }}>
              <Plus className="w-4 h-4 mr-2" />
              新建预警规则
            </Button>
          </div>

          {/* 预警规则列表 */}
          <div className="grid grid-cols-1 gap-4">
            {alertRules.map((rule) => (
              <Card key={rule.id} className="p-6">
                <div className="flex items-start justify-between mb-4">
                  <div className="flex-1">
                    <div className="flex items-center gap-2 mb-2">
                      <h4>{rule.name}</h4>
                      <Badge className={rule.status === '启用' ? 'bg-green-100 text-green-700' : 'bg-gray-100 text-gray-700'}>
                        {rule.status}
                      </Badge>
                      <Badge className={getLevelColor(rule.level)}>
                        {rule.level}
                      </Badge>
                    </div>
                    <p className="text-sm text-muted-foreground">{rule.description}</p>
                  </div>
                  <div className="flex gap-2">
                    <Button size="sm" variant="outline" onClick={() => handleToggleRuleStatus(rule.id)}>
                      <Activity className="w-3 h-3 mr-1" />
                      {rule.status === '启用' ? '禁用' : '启用'}
                    </Button>
                    <Button size="sm" variant="outline" onClick={() => {
                      setEditingRule(rule);
                      // 加载规则数据到表单
                      setRuleName(rule.name);
                      setRuleDescription(rule.description);
                      setRuleLevel(rule.level);
                      setConditionOperator(rule.conditionOperator);
                      setRuleDuration(rule.duration);
                      // 加载规则的条件到编辑状态
                      setRuleConditions(rule.conditions.map(c => ({
                        id: c.id,
                        device: '',
                        parameter: c.parameter,
                        operator: c.operator,
                        value: c.value.toString()
                      })));
                      setShowRuleDialog(true);
                    }}>
                      <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>

                {/* 条件展示 */}
                <Card className="p-4 bg-gray-50">
                  <h4 className="text-sm mb-3 flex items-center gap-2">
                    <Filter className="w-4 h-4 text-blue-600" />
                    触发条件（{rule.conditionOperator}逻辑）
                  </h4>
                  <div className="space-y-2">
                    {rule.conditions.map((condition, index) => (
                      <div key={condition.id} className="flex items-center gap-2 text-sm">
                        <Badge variant="outline">{index + 1}</Badge>
                        <span className="text-muted-foreground">{getParameterLabel(condition.parameter) || condition.parameter}</span>
                        <Badge className="bg-blue-100 text-blue-700">{condition.operator}</Badge>
                        <span>{condition.value}</span>
                        <span className="text-muted-foreground">{condition.unit}</span>
                      </div>
                    ))}
                  </div>
                  {rule.duration > 0 && (
                    <div className="mt-3 pt-3 border-t flex items-center gap-2 text-sm text-muted-foreground">
                      <Clock className="w-4 h-4" />
                      持续时间: {rule.duration} 分钟
                    </div>
                  )}
                </Card>

                {/* 统计信息 */}
                <div className="grid grid-cols-3 gap-4 mt-4">
                  <Card className="p-3 bg-blue-50">
                    <p className="text-xs text-muted-foreground mb-1">触发次数</p>
                    <p className="text-lg">{rule.triggeredCount} 次</p>
                  </Card>
                  <Card className="p-3 bg-green-50">
                    <p className="text-xs text-muted-foreground mb-1">创建时间</p>
                    <p className="text-sm">{rule.createdAt}</p>
                  </Card>
                  <Card className="p-3 bg-orange-50">
                    <p className="text-xs text-muted-foreground mb-1">最近触发</p>
                    <p className="text-sm">{rule.lastTriggered || '未触发'}</p>
                  </Card>
                </div>
              </Card>
            ))}
          </div>
        </TabsContent>

        {/* 阈值预警与告警 */}
        <TabsContent value="threshold-alert" className="space-y-4">
          <Card className="p-4 bg-gradient-to-r from-orange-50 to-amber-50 border-orange-200">
            <div className="flex items-start gap-2">
              <Target className="w-5 h-5 text-orange-600 flex-shrink-0 mt-0.5" />
              <div className="text-sm text-orange-900">
                <p className="mb-2">阈值预警与告警功能：</p>
                <ul className="space-y-1 text-xs">
                  <li>• <strong>自定义阈值</strong>: 各项参数安全阈值自定义配置</li>
                  <li>• <strong>实时对比</strong>: 系统实时数据与阈值比对</li>
                  <li>• <strong>多级告警</strong>: 提示、警告、严重三级别告警</li>
                  <li>• <strong>异常发现</strong>: 及时发现潜在风险</li>
                  <li>• <strong>分级响应</strong>: 根据告警级别分级处理</li>
                  <li>• <strong>告警记录</strong>: 完整的告警历史记录</li>
                </ul>
              </div>
            </div>
          </Card>

          {/* 阈值配置 */}
          <Card className="p-6">
            <div className="flex items-center justify-between mb-4">
              <h4 className="flex items-center gap-2">
                <Settings className="w-5 h-5 text-orange-600" />
                阈值参数配置
              </h4>
              <Button onClick={() => {
                setEditingThreshold(null);
                setSelectedComponent('');
                setSelectedParameter('');
                setThresholdWarningMin(0);
                setThresholdWarningMax(0);
                setShowThresholdDialog(true);
              }}>
                <Plus className="w-4 h-4 mr-2" />
                添加阈值
              </Button>
            </div>

            <div className="grid grid-cols-1 gap-4">
              {thresholdConfigs.map((config) => (
                <Card key={config.id} className="p-4 bg-gray-50">
                  <div className="flex items-start justify-between mb-3">
                    <div className="flex-1">
                      <div className="flex items-center gap-2 mb-1">
                        <h4>{config.parameter}</h4>
                        <Badge variant="outline">{config.category}</Badge>
                        <Badge className={getStatusColor(config.status)}>
                          {config.status}
                        </Badge>
                      </div>
                      <p className="text-sm text-muted-foreground">
                        当前值: <span className="text-foreground">{config.currentValue} {config.unit}</span>
                      </p>
                    </div>
                    <div className="flex items-center gap-2">
                      <Switch 
                        checked={config.enabled} 
                        onCheckedChange={() => handleToggleThreshold(config.id)}
                      />
                      <Button size="sm" variant="outline" onClick={() => {
                        setEditingThreshold(config);
                        setShowThresholdDialog(true);
                      }}>
                        <Edit className="w-3 h-3" />
                      </Button>
                    </div>
                  </div>

                  <div className="grid grid-cols-3 gap-3">
                    <div className="p-3 bg-green-50 rounded-lg">
                      <p className="text-xs text-muted-foreground mb-2">正常范围</p>
                      <p className="text-sm">
                        {config.warningMin} - {config.warningMax} {config.unit}
                      </p>
                    </div>
                    <div className="p-3 bg-orange-50 rounded-lg">
                      <p className="text-xs text-muted-foreground mb-2">警告范围</p>
                      <p className="text-sm">
                        {config.minValue} - {config.warningMin} {config.unit}<br />
                        {config.warningMax} - {config.maxValue} {config.unit}
                      </p>
                    </div>
                    <div className="p-3 bg-red-50 rounded-lg">
                      <p className="text-xs text-muted-foreground mb-2">严重范围</p>
                      <p className="text-sm">
                        {'<'} {config.criticalMin} {config.unit}<br />
                        {'>'} {config.criticalMax} {config.unit}
                      </p>
                    </div>
                  </div>
                </Card>
              ))}
            </div>
          </Card>

          {/* 告警记录 */}
          <Card className="p-6">
            <h4 className="mb-4 flex items-center gap-2">
              <Bell className="w-5 h-5 text-red-600" />
              实时告警记录
            </h4>

            <div className="space-y-3">
              {alertRecords.map((alert) => (
                <Card key={alert.id} className="p-4">
                  <div className="flex items-start justify-between mb-3">
                    <div className="flex-1">
                      <div className="flex items-center gap-2 mb-2">
                        <Badge className={getLevelColor(alert.level)}>
                          {alert.level}
                        </Badge>
                        <Badge className={getAlertStatusColor(alert.status)}>
                          {alert.status}
                        </Badge>
                        <span className="text-sm">{alert.ruleName}</span>
                      </div>
                      <p className="text-sm text-muted-foreground mb-2">{alert.message}</p>
                      <div className="flex items-center gap-4 text-xs text-muted-foreground">
                        <span className="flex items-center gap-1">
                          <Clock className="w-3 h-3" />
                          {alert.triggeredAt}
                        </span>
                        {alert.handler && (
                          <span className="flex items-center gap-1">
                            <Users className="w-3 h-3" />
                            处理人: {alert.handler}
                          </span>
                        )}
                        <div className="flex items-center gap-1">
                          {alert.channels.map((channel, index) => (
                            <Badge key={index} variant="outline" className="text-xs">
                              {channel}
                            </Badge>
                          ))}
                        </div>
                      </div>
                    </div>
                    <div className="flex gap-2">
                      {alert.status === '待处理' && (
                        <>
                          <Button size="sm" onClick={() => handleUpdateAlertStatus(alert.id, '处理中')}>
                            开始处理
                          </Button>
                          <Button size="sm" variant="outline" onClick={() => handleUpdateAlertStatus(alert.id, '已处理')}>
                            标记已处理
                          </Button>
                        </>
                      )}
                      {alert.status === '处理中' && (
                        <Button size="sm" onClick={() => handleUpdateAlertStatus(alert.id, '已处理')}>
                          完成处理
                        </Button>
                      )}
                      <Button size="sm" variant="outline" onClick={() => {
                        setViewingAlert(alert);
                        setShowAlertDetailDialog(true);
                      }}>
                        <Eye className="w-3 h-3" />
                      </Button>
                    </div>
                  </div>
                </Card>
              ))}
            </div>
          </Card>
        </TabsContent>

        {/* 多通道告警推送 */}
        <TabsContent value="notification-push" className="space-y-4">
          <Card className="p-4 bg-gradient-to-r from-purple-50 to-pink-50 border-purple-200">
            <div className="flex items-start gap-2">
              <Send className="w-5 h-5 text-purple-600 flex-shrink-0 mt-0.5" />
              <div className="text-sm text-purple-900">
                <p className="mb-2">多通道告警推送功能：</p>
                <ul className="space-y-1 text-xs">
                  <li>• <strong>多种方式</strong>: 短信、邮件、站内信多渠道推送</li>
                  <li>• <strong>精准推送</strong>: 预警信息推送给系统用户</li>
                  <li>• <strong>即时触达</strong>: 确保问题第一时间通知到位</li>
                  <li>• <strong>灵活配置</strong>: 可启用或停用各通知渠道</li>
                  <li>• <strong>用户集成</strong>: 直接从用户管理系统选择通知人</li>
                  <li>• <strong>应急响应</strong>: 提升应急响应效率</li>
                </ul>
              </div>
            </div>
          </Card>

          {/* 通知方式配置 */}
          <Card className="p-6">
            <h4 className="mb-4 flex items-center gap-2">
              <BellRing className="w-5 h-5 text-purple-600" />
              通知方式配置
            </h4>

            <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
              <Card className="p-4 bg-gradient-to-br from-blue-50 to-cyan-50">
                <div className="flex items-center gap-3 mb-3">
                  <div className="p-2 bg-blue-600 rounded-lg">
                    <MessageSquare className="w-5 h-5 text-white" />
                  </div>
                  <div className="flex-1">
                    <h4>短信通知</h4>
                    <p className="text-xs text-muted-foreground">实时短信推送</p>
                  </div>
                  <Switch 
                    checked={smsEnabled} 
                    onCheckedChange={(checked) => {
                      setSmsEnabled(checked);
                      toast.success(`短信通知已${checked ? '启用' : '停用'}`);
                    }}
                  />
                </div>
                <div className="space-y-2 text-sm">
                  <div className="flex justify-between">
                    <span className="text-muted-foreground">状态:</span>
                    <Badge className={smsEnabled ? 'bg-green-100 text-green-700' : 'bg-gray-100 text-gray-700'}>
                      {smsEnabled ? '已启用' : '已停用'}
                    </Badge>
                  </div>
                  <div className="flex justify-between">
                    <span className="text-muted-foreground">今日发送:</span>
                    <span>12 条</span>
                  </div>
                  <div className="flex justify-between">
                    <span className="text-muted-foreground">成功率:</span>
                    <span className="text-green-600">98.5%</span>
                  </div>
                </div>
              </Card>

              <Card className="p-4 bg-gradient-to-br from-green-50 to-teal-50">
                <div className="flex items-center gap-3 mb-3">
                  <div className="p-2 bg-green-600 rounded-lg">
                    <Mail className="w-5 h-5 text-white" />
                  </div>
                  <div className="flex-1">
                    <h4>邮件通知</h4>
                    <p className="text-xs text-muted-foreground">详细邮件推送</p>
                  </div>
                  <Switch 
                    checked={emailEnabled} 
                    onCheckedChange={(checked) => {
                      setEmailEnabled(checked);
                      toast.success(`邮件通知已${checked ? '启用' : '停用'}`);
                    }}
                  />
                </div>
                <div className="space-y-2 text-sm">
                  <div className="flex justify-between">
                    <span className="text-muted-foreground">状态:</span>
                    <Badge className={emailEnabled ? 'bg-green-100 text-green-700' : 'bg-gray-100 text-gray-700'}>
                      {emailEnabled ? '已启用' : '已停用'}
                    </Badge>
                  </div>
                  <div className="flex justify-between">
                    <span className="text-muted-foreground">今日发送:</span>
                    <span>8 封</span>
                  </div>
                  <div className="flex justify-between">
                    <span className="text-muted-foreground">成功率:</span>
                    <span className="text-green-600">100%</span>
                  </div>
                </div>
              </Card>

              <Card className="p-4 bg-gradient-to-br from-purple-50 to-pink-50">
                <div className="flex items-center gap-3 mb-3">
                  <div className="p-2 bg-purple-600 rounded-lg">
                    <Bell className="w-5 h-5 text-white" />
                  </div>
                  <div className="flex-1">
                    <h4>站内信通知</h4>
                    <p className="text-xs text-muted-foreground">系统内部消息</p>
                  </div>
                  <Switch 
                    checked={inAppEnabled} 
                    onCheckedChange={(checked) => {
                      setInAppEnabled(checked);
                      toast.success(`站内信通知已${checked ? '启用' : '停用'}`);
                    }}
                  />
                </div>
                <div className="space-y-2 text-sm">
                  <div className="flex justify-between">
                    <span className="text-muted-foreground">状态:</span>
                    <Badge className={inAppEnabled ? 'bg-green-100 text-green-700' : 'bg-gray-100 text-gray-700'}>
                      {inAppEnabled ? '已启用' : '已停用'}
                    </Badge>
                  </div>
                  <div className="flex justify-between">
                    <span className="text-muted-foreground">今日发送:</span>
                    <span>15 条</span>
                  </div>
                  <div className="flex justify-between">
                    <span className="text-muted-foreground">成功率:</span>
                    <span className="text-green-600">100%</span>
                  </div>
                </div>
              </Card>
            </div>
          </Card>

          {/* 联系人管理 */}
          <Card className="p-6">
            <div className="flex items-center justify-between mb-4">
              <h4 className="flex items-center gap-2">
                <Users className="w-5 h-5 text-blue-600" />
                通知用户管理
              </h4>
              <div className="flex gap-2">
                <Select value={selectedUserId} onValueChange={(value) => setSelectedUserId(value)}>
                  <SelectTrigger className="w-64">
                    <SelectValue placeholder="从用户管理系统选择用户" />
                  </SelectTrigger>
                  <SelectContent>
                    {systemUsers
                      .filter(user => user.status === 'active')
                      .filter(user => !contacts.some(c => c.id === user.id))
                      .map((user) => (
                        <SelectItem key={user.id} value={user.id}>
                          {user.name} ({user.roles?.[0] || user.userType})
                        </SelectItem>
                      ))}
                  </SelectContent>
                </Select>
                <Button onClick={() => {
                  if (!selectedUserId) {
                    toast.error('请先选择用户');
                    return;
                  }
                  const user = systemUsers.find(u => u.id === selectedUserId);
                  if (user) {
                    const newContact: NotificationContact = {
                      id: user.id,
                      name: user.name,
                      phone: user.phone || '',
                      email: user.email || '',
                      role: user.roles?.[0] || user.userType,
                      enabled: true,
                      channels: ['短信', '邮件', '站内信'],
                    };
                    setContacts([...contacts, newContact]);
                    setSelectedUserId('');
                    toast.success(`已添加通知用户：${user.name}`);
                  }
                }}>
                  <Plus className="w-4 h-4 mr-2" />
                  添加
                </Button>
              </div>
            </div>

            <div className="grid grid-cols-1 gap-3">
              {contacts.map((contact) => (
                <Card key={contact.id} className="p-4">
                  <div className="flex items-start justify-between">
                    <div className="flex-1">
                      <div className="flex items-center gap-2 mb-2">
                        <h4>{contact.name}</h4>
                        <Badge variant="outline">{contact.role}</Badge>
                      </div>
                      <div className="grid grid-cols-2 md:grid-cols-4 gap-3 text-sm">
                        <div className="flex items-center gap-2">
                          <Phone className="w-4 h-4 text-muted-foreground" />
                          <span>{contact.phone}</span>
                        </div>
                        <div className="flex items-center gap-2">
                          <Mail className="w-4 h-4 text-muted-foreground" />
                          <span className="truncate">{contact.email}</span>
                        </div>
                        <div className="flex items-center gap-2">
                          <Bell className="w-4 h-4 text-muted-foreground" />
                          <div className="flex gap-1">
                            {contact.channels.map((channel, index) => (
                              <Badge key={index} variant="outline" className="text-xs">
                                {channel}
                              </Badge>
                            ))}
                          </div>
                        </div>
                      </div>
                    </div>
                    <div className="flex gap-2">
                      <Button 
                        size="sm" 
                        variant="outline" 
                        className="text-red-600 hover:text-red-700 hover:bg-red-50"
                        onClick={() => handleDeleteContact(contact)}
                      >
                        <Trash2 className="w-3 h-3 mr-1" />
                        删除
                      </Button>
                    </div>
                  </div>
                </Card>
              ))}
            </div>
          </Card>
        </TabsContent>
      </Tabs>

      {/* 新建/编辑预警规则对话框 */}
      <Dialog open={showRuleDialog} onOpenChange={setShowRuleDialog}>
        <DialogContent className="max-w-3xl">
          <DialogHeader>
            <DialogTitle>{editingRule ? '编辑预警规则' : '新建预警规则'}</DialogTitle>
            <DialogDescription>
              先选择水肥机部件，再选择监测参数，配置多条件预警规则实现智能预警
            </DialogDescription>
          </DialogHeader>

          <div className="space-y-4">
            <div className="grid grid-cols-2 gap-4">
              <div>
                <Label>规则名称</Label>
                <Input 
                  placeholder="请输入规则名称" 
                  className="mt-2"
                  value={ruleName}
                  onChange={(e) => setRuleName(e.target.value)}
                />
              </div>
              <div>
                <Label>告警级别</Label>
                <Select value={ruleLevel} onValueChange={(value) => setRuleLevel(value as AlertLevel)}>
                  <SelectTrigger className="mt-2">
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="提示">提示</SelectItem>
                    <SelectItem value="警告">警告</SelectItem>
                    <SelectItem value="严重">严重</SelectItem>
                  </SelectContent>
                </Select>
              </div>
            </div>

            <div>
              <Label>规则描述</Label>
              <Textarea 
                placeholder="请输入规则描述" 
                className="mt-2" 
                rows={3}
                value={ruleDescription}
                onChange={(e) => setRuleDescription(e.target.value)}
              />
            </div>

            <div>
              <Label>条件逻辑</Label>
              <Select value={conditionOperator} onValueChange={(value) => setConditionOperator(value as ConditionOperator)}>
                <SelectTrigger className="mt-2">
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="且">且（AND）- 所有条件都满足</SelectItem>
                  <SelectItem value="或">或（OR）- 任一条件满足</SelectItem>
                </SelectContent>
              </Select>
            </div>

            <div>
              <div className="flex items-center justify-between mb-2">
                <Label>触发条件</Label>
                <Button 
                  size="sm" 
                  variant="outline"
                  onClick={() => {
                    setRuleConditions([...ruleConditions, {
                      id: `cond-${Date.now()}`,
                      device: '',
                      parameter: '',
                      operator: '>',
                      value: ''
                    }]);
                  }}
                >
                  <Plus className="w-3 h-3 mr-1" />
                  添加条件
                </Button>
              </div>
              
              {/* 提示说明 */}
              <Card className="mt-2 p-3 bg-blue-50 border-blue-200">
                <p className="text-xs text-blue-800">
                  <strong>ℹ️ 操作提示：</strong>先选择水肥机部件（如EC传感器、肥料泵等），系统将自动显示该部件的可监测参数
                </p>
              </Card>
              
              <Card className="mt-2 p-4 bg-gray-50 space-y-3">
                {ruleConditions.length === 0 ? (
                  <p className="text-sm text-muted-foreground text-center py-4">
                    暂无触发条件，请点击"添加条件"按钮添加
                  </p>
                ) : (
                  ruleConditions.map((condition, index) => (
                    <Card key={condition.id} className="p-4 bg-white">
                      <div className="flex items-center justify-between mb-3">
                        <Badge variant="outline">条件 {index + 1}</Badge>
                        <Button 
                          size="sm" 
                          variant="ghost"
                          onClick={() => {
                            setRuleConditions(ruleConditions.filter(c => c.id !== condition.id));
                          }}
                        >
                          <Trash2 className="w-3 h-3 text-red-600" />
                        </Button>
                      </div>
                      
                      <div className="grid grid-cols-1 md:grid-cols-4 gap-3">
                        {/* 水肥机部件选择 */}
                        <div>
                          <Label className="text-xs">水肥机部件</Label>
                          <Select 
                            value={condition.device}
                            onValueChange={(value) => {
                              setRuleConditions(ruleConditions.map(c => 
                                c.id === condition.id ? { ...c, device: value, parameter: '' } : c
                              ));
                            }}
                          >
                            <SelectTrigger className="mt-1 h-9">
                              <SelectValue placeholder="选择部件" />
                            </SelectTrigger>
                            <SelectContent>
                              {Object.entries(componentConfig).map(([key, config]) => (
                                <SelectItem key={key} value={key}>
                                  {config.name}
                                </SelectItem>
                              ))}
                            </SelectContent>
                          </Select>
                        </div>

                        {/* 参数选择（根据部件联动） */}
                        <div>
                          <Label className="text-xs">参数</Label>
                          <Select 
                            value={condition.parameter}
                            disabled={!condition.device}
                            onValueChange={(value) => {
                              setRuleConditions(ruleConditions.map(c => 
                                c.id === condition.id ? { ...c, parameter: value } : c
                              ));
                            }}
                          >
                            <SelectTrigger className="mt-1 h-9">
                              <SelectValue placeholder={condition.device ? "选择参数" : "请先选择部件"} />
                            </SelectTrigger>
                            <SelectContent>
                              {condition.device && parameterConfig[condition.device]?.map((param) => (
                                <SelectItem key={param.key} value={param.key}>
                                  {param.name} ({param.unit})
                                </SelectItem>
                              ))}
                            </SelectContent>
                          </Select>
                        </div>

                        {/* 等式选择 */}
                        <div>
                          <Label className="text-xs">等式</Label>
                          <Select 
                            value={condition.operator}
                            onValueChange={(value) => {
                              setRuleConditions(ruleConditions.map(c => 
                                c.id === condition.id ? { ...c, operator: value as ComparisonOperator } : c
                              ));
                            }}
                          >
                            <SelectTrigger className="mt-1 h-9">
                              <SelectValue />
                            </SelectTrigger>
                            <SelectContent>
                              <SelectItem value=">">大于 {'>'}</SelectItem>
                              <SelectItem value=">=">大于等于 {'>='}</SelectItem>
                              <SelectItem value="<">小于 {'<'}</SelectItem>
                              <SelectItem value="<=">小于等于 {'<='}</SelectItem>
                              <SelectItem value="=">等于 =</SelectItem>
                            </SelectContent>
                          </Select>
                        </div>

                        {/* 阈值输入 */}
                        <div>
                          <Label className="text-xs">阈值</Label>
                          <Input 
                            type="number"
                            placeholder="输入数值"
                            className="mt-1 h-9"
                            value={condition.value}
                            onChange={(e) => {
                              setRuleConditions(ruleConditions.map(c => 
                                c.id === condition.id ? { ...c, value: e.target.value } : c
                              ));
                            }}
                          />
                        </div>
                      </div>
                    </Card>
                  ))
                )}
              </Card>
            </div>

            <div>
              <Label>持续时间（分钟）</Label>
              <Input 
                type="number" 
                placeholder="0表示立即触发" 
                className="mt-2" 
                value={ruleDuration}
                onChange={(e) => setRuleDuration(parseInt(e.target.value) || 0)}
              />
            </div>
          </div>

          <DialogFooter>
            <Button variant="outline" onClick={() => setShowRuleDialog(false)}>
              取消
            </Button>
            <Button onClick={() => {
              // 验证表单
              if (!ruleName.trim()) {
                toast.error('请输入规则名称');
                return;
              }
              if (ruleConditions.length === 0) {
                toast.error('请至少添加一个触发条件');
                return;
              }
              
              // 验证所有条件是否填写完整
              const incompleteCondition = ruleConditions.find(c => 
                !c.device || !c.parameter || !c.value
              );
              if (incompleteCondition) {
                toast.error('请完整填写所有触发条件');
                return;
              }

              // 构建新规则数据
              const newRule: AlertRule = {
                id: editingRule?.id || `rule-${Date.now()}`,
                name: ruleName,
                description: ruleDescription,
                status: editingRule?.status || '启用',
                level: ruleLevel,
                conditions: ruleConditions.map(c => ({
                  id: c.id,
                  parameter: c.parameter,
                  operator: c.operator,
                  value: parseFloat(c.value),
                  unit: getParameterUnit(c.parameter)
                })),
                conditionOperator: conditionOperator,
                duration: ruleDuration,
                createdAt: editingRule?.createdAt || new Date().toLocaleString('zh-CN'),
                triggeredCount: editingRule?.triggeredCount || 0,
                lastTriggered: editingRule?.lastTriggered
              };

              // 保存规则
              if (editingRule) {
                setAlertRules(alertRules.map(r => r.id === editingRule.id ? newRule : r));
                toast.success('预警规则已更新');
              } else {
                setAlertRules([newRule, ...alertRules]);
                toast.success('预警规则已创建');
              }
              
              setShowRuleDialog(false);
            }}>
              保存规则
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* 阈值配置对话框 */}
      <Dialog open={showThresholdDialog} onOpenChange={setShowThresholdDialog}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>{editingThreshold ? '编辑阈值配置' : '添加阈值配置'}</DialogTitle>
            <DialogDescription>
              先选择水肥机部件，再选择监测参数，系统将自动设置阈值范围
            </DialogDescription>
          </DialogHeader>

          <div className="space-y-4">
            {/* 部件选择 */}
            <div>
              <Label>水肥机部件</Label>
              <Select 
                value={selectedComponent}
                onValueChange={(value) => {
                  setSelectedComponent(value);
                  setSelectedParameter(''); // 清空参数选择
                }}
              >
                <SelectTrigger className="mt-2">
                  <SelectValue placeholder="请选择水肥机部件" />
                </SelectTrigger>
                <SelectContent>
                  {Object.entries(componentConfig).map(([key, config]) => (
                    <SelectItem key={key} value={key}>
                      {config.name}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>

            {/* 参数选择（部件选中后才能选择） */}
            <div>
              <Label>监测参数</Label>
              <Select 
                value={selectedParameter}
                onValueChange={setSelectedParameter}
                disabled={!selectedComponent}
              >
                <SelectTrigger className="mt-2">
                  <SelectValue placeholder={selectedComponent ? "请选择监测参数" : "请先选择部件"} />
                </SelectTrigger>
                <SelectContent>
                  {getAvailableParameters().map((param) => (
                    <SelectItem key={param.key} value={param.key}>
                      {param.name}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>

            {/* 参数配置预览（选择参数后显示） */}
            {selectedParameter && getCurrentParameterConfig() && (
              <Card className="p-4 bg-blue-50 border-blue-200">
                <div className="space-y-3">
                  <div className="flex items-center gap-2 mb-3">
                    <Settings className="w-4 h-4 text-blue-600" />
                    <h4 className="text-sm">参数配置（自动生成）</h4>
                  </div>

                  <div className="grid grid-cols-2 gap-3">
                    <div className="p-2 bg-white rounded">
                      <p className="text-xs text-muted-foreground">参数类别</p>
                      <p className="text-sm mt-1">{componentConfig[selectedComponent]?.category}</p>
                    </div>
                    <div className="p-2 bg-white rounded">
                      <p className="text-xs text-muted-foreground">单位</p>
                      <p className="text-sm mt-1">{getCurrentParameterConfig()?.unit}</p>
                    </div>
                  </div>

                  <div className="grid grid-cols-2 gap-3">
                    <div className="p-2 bg-white rounded">
                      <p className="text-xs text-muted-foreground">最小值</p>
                      <p className="text-sm mt-1">{getCurrentParameterConfig()?.minValue}</p>
                    </div>
                    <div className="p-2 bg-white rounded">
                      <p className="text-xs text-muted-foreground">最大值</p>
                      <p className="text-sm mt-1">{getCurrentParameterConfig()?.maxValue}</p>
                    </div>
                  </div>

                  <p className="text-xs text-blue-600 mt-2">
                    ℹ️ 最小值、最大值和单位由系统自动设置，不可修改
                  </p>
                </div>
              </Card>
            )}

            {/* 警告阈值设置 */}
            {selectedParameter && getCurrentParameterConfig() && (
              <>
                <div className="grid grid-cols-2 gap-4">
                  <div>
                    <Label>警告下限</Label>
                    <Input 
                      type="number" 
                      className="mt-2"
                      value={thresholdWarningMin}
                      onChange={(e) => setThresholdWarningMin(parseFloat(e.target.value) || 0)}
                      placeholder={`建议: ${getCurrentParameterConfig()?.warningMin}`}
                    />
                  </div>
                  <div>
                    <Label>警告上限</Label>
                    <Input 
                      type="number" 
                      className="mt-2"
                      value={thresholdWarningMax}
                      onChange={(e) => setThresholdWarningMax(parseFloat(e.target.value) || 0)}
                      placeholder={`建议: ${getCurrentParameterConfig()?.warningMax}`}
                    />
                  </div>
                </div>

                <Card className="p-3 bg-orange-50 border-orange-200">
                  <p className="text-xs text-orange-800">
                    <strong>提示：</strong>警告阈值应在最小值 ({getCurrentParameterConfig()?.minValue}) 
                    和最大值 ({getCurrentParameterConfig()?.maxValue}) 之间
                  </p>
                </Card>
              </>
            )}
          </div>

          <DialogFooter>
            <Button variant="outline" onClick={() => {
              setShowThresholdDialog(false);
              setSelectedComponent('');
              setSelectedParameter('');
              setThresholdWarningMin(0);
              setThresholdWarningMax(0);
            }}>
              取消
            </Button>
            <Button 
              disabled={!selectedComponent || !selectedParameter}
              onClick={() => {
                const paramConfig = getCurrentParameterConfig();
                if (!paramConfig) {
                  toast.error('请选择有效的参数');
                  return;
                }

                // 验证警告阈值
                if (thresholdWarningMin < paramConfig.minValue || thresholdWarningMax > paramConfig.maxValue) {
                  toast.error('警告阈值超出允许范围');
                  return;
                }

                if (thresholdWarningMin >= thresholdWarningMax) {
                  toast.error('警告下限必须小于警告上限');
                  return;
                }

                // 创建新的阈值配置
                const newThreshold: ThresholdConfig = {
                  id: `th-${Date.now()}`,
                  parameter: paramConfig.name,
                  category: componentConfig[selectedComponent].category,
                  minValue: paramConfig.minValue,
                  maxValue: paramConfig.maxValue,
                  warningMin: thresholdWarningMin || paramConfig.warningMin,
                  warningMax: thresholdWarningMax || paramConfig.warningMax,
                  criticalMin: paramConfig.criticalMin,
                  criticalMax: paramConfig.criticalMax,
                  unit: paramConfig.unit,
                  currentValue: (paramConfig.minValue + paramConfig.maxValue) / 2,
                  status: '正常',
                  enabled: true
                };

                setThresholdConfigs([newThreshold, ...thresholdConfigs]);
                toast.success('阈值配置已添加');
                
                // 重置表单
                setShowThresholdDialog(false);
                setSelectedComponent('');
                setSelectedParameter('');
                setThresholdWarningMin(0);
                setThresholdWarningMax(0);
              }}
            >
              保存配置
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* 告警记录详情查看对话框 */}
      <Dialog open={showAlertDetailDialog} onOpenChange={setShowAlertDetailDialog}>
        <DialogContent className="max-w-2xl">
          <DialogHeader>
            <DialogTitle className="flex items-center gap-2">
              <Bell className="w-5 h-5 text-red-600" />
              告警记录详情
            </DialogTitle>
            <DialogDescription>
              查看告警记录的完整信息和处理情况
            </DialogDescription>
          </DialogHeader>

          {viewingAlert && (
            <div className="space-y-4">
              {/* 基本信息 */}
              <Card className="p-4 bg-gradient-to-r from-red-50 to-orange-50">
                <div className="flex items-start justify-between mb-3">
                  <div>
                    <div className="flex items-center gap-2 mb-2">
                      <Badge className={getLevelColor(viewingAlert.level)}>
                        {viewingAlert.level}
                      </Badge>
                      <Badge className={getAlertStatusColor(viewingAlert.status)}>
                        {viewingAlert.status}
                      </Badge>
                    </div>
                    <h4>{viewingAlert.ruleName}</h4>
                  </div>
                </div>
              </Card>

              {/* 告警信息 */}
              <div className="space-y-3">
                <div>
                  <Label>告警消息</Label>
                  <Card className="p-3 mt-2 bg-gray-50">
                    <p className="text-sm">{viewingAlert.message}</p>
                  </Card>
                </div>

                <div className="grid grid-cols-2 gap-3">
                  <div>
                    <Label>触发时间</Label>
                    <div className="field-value flex items-center gap-2">
                      <Clock className="w-4 h-4 text-muted-foreground" />
                      {viewingAlert.triggeredAt}
                    </div>
                  </div>
                  <div>
                    <Label>告警级别</Label>
                    <div className="field-value">
                      <Badge className={getLevelColor(viewingAlert.level)}>
                        {viewingAlert.level}
                      </Badge>
                    </div>
                  </div>
                </div>

                <div className="grid grid-cols-2 gap-3">
                  <div>
                    <Label>当前状态</Label>
                    <div className="field-value">
                      <Badge className={getAlertStatusColor(viewingAlert.status)}>
                        {viewingAlert.status}
                      </Badge>
                    </div>
                  </div>
                  <div>
                    <Label>推送渠道</Label>
                    <div className="field-value flex gap-1">
                      {viewingAlert.channels.map((channel, index) => (
                        <Badge key={index} variant="outline">
                          {channel}
                        </Badge>
                      ))}
                    </div>
                  </div>
                </div>

                {/* 处理信息 */}
                {viewingAlert.handler && (
                  <Card className="p-4 bg-green-50 border-green-200">
                    <h4 className="text-sm mb-3 flex items-center gap-2">
                      <CheckCircle className="w-4 h-4 text-green-600" />
                      处理信息
                    </h4>
                    <div className="grid grid-cols-2 gap-3 text-sm">
                      <div>
                        <p className="text-muted-foreground mb-1">处理人</p>
                        <p className="flex items-center gap-2">
                          <Users className="w-4 h-4 text-muted-foreground" />
                          {viewingAlert.handler}
                        </p>
                      </div>
                      {viewingAlert.handledAt && (
                        <div>
                          <p className="text-muted-foreground mb-1">处理时间</p>
                          <p className="flex items-center gap-2">
                            <Clock className="w-4 h-4 text-muted-foreground" />
                            {viewingAlert.handledAt}
                          </p>
                        </div>
                      )}
                    </div>
                  </Card>
                )}

                {/* 待处理提示 */}
                {viewingAlert.status === '待处理' && (
                  <Card className="p-3 bg-yellow-50 border-yellow-200">
                    <p className="text-sm text-yellow-800">
                      <strong>⚠️ 提示：</strong>该告警尚未处理，请及时关注并采取相应措施。
                    </p>
                  </Card>
                )}
              </div>

              {/* 操作建议 */}
              <Card className="p-4 bg-blue-50 border-blue-200">
                <h4 className="text-sm mb-2 flex items-center gap-2">
                  <Settings className="w-4 h-4 text-blue-600" />
                  处理建议
                </h4>
                <ul className="space-y-1 text-sm text-blue-900">
                  <li>• 检查相关设备运行状态</li>
                  <li>• 核实监测数据是否准确</li>
                  <li>• 根据告警级别采取相应措施</li>
                  <li>• 处理完成后及时更新告警状态</li>
                </ul>
              </Card>
            </div>
          )}

          <DialogFooter>
            <Button variant="outline" onClick={() => setShowAlertDetailDialog(false)}>
              关闭
            </Button>
            {viewingAlert?.status === '待处理' && (
              <Button onClick={() => {
                if (viewingAlert) {
                  handleUpdateAlertStatus(viewingAlert.id, '处理中');
                  setShowAlertDetailDialog(false);
                }
              }}>
                开始处理
              </Button>
            )}
            {viewingAlert?.status === '处理中' && (
              <Button onClick={() => {
                if (viewingAlert) {
                  handleUpdateAlertStatus(viewingAlert.id, '已处理');
                  setShowAlertDetailDialog(false);
                }
              }}>
                标记已处理
              </Button>
            )}
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* 删除预警规则确认对话框 */}
      <AlertDialog open={showDeleteConfirm} onOpenChange={setShowDeleteConfirm}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle className="flex items-center gap-2">
              <AlertTriangle className="w-5 h-5 text-red-600" />
              确认删除预警规则
            </AlertDialogTitle>
            <AlertDialogDescription>
              {ruleToDelete && `您确定要删除预警规则"${alertRules.find(r => r.id === ruleToDelete)?.name}"吗？`}
            </AlertDialogDescription>
          </AlertDialogHeader>
          
          {ruleToDelete && (
            <div className="space-y-3">
              <div className="p-3 bg-red-50 border border-red-200 rounded-md">
                <p className="text-sm text-red-800">
                  <strong>警告：</strong>删除后将无法恢复，该规则的所有配置信息将被永久删除。
                </p>
              </div>
              {alertRules.find(r => r.id === ruleToDelete)?.status === '启用' && (
                <div className="p-3 bg-orange-50 border border-orange-200 rounded-md">
                  <p className="text-sm text-orange-800">
                    <strong>提示：</strong>该规则当前处于启用状态，删除后将立即停止监控。
                  </p>
                </div>
              )}
            </div>
          )}
          
          <AlertDialogFooter>
            <AlertDialogCancel onClick={() => setRuleToDelete(null)}>
              取消
            </AlertDialogCancel>
            <AlertDialogAction
              onClick={confirmDeleteRule}
              className="bg-red-600 hover:bg-red-700"
            >
              确认删除
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>

      {/* 删除通知用户确认对话框 */}
      <AlertDialog open={showDeleteContactConfirm} onOpenChange={setShowDeleteContactConfirm}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle className="flex items-center gap-2">
              <AlertTriangle className="w-5 h-5 text-red-600" />
              确认删除通知用户
            </AlertDialogTitle>
            <AlertDialogDescription>
              {contactToDelete && `您确定要删除通知用户"${contactToDelete.name}"吗？`}
            </AlertDialogDescription>
          </AlertDialogHeader>
          
          {contactToDelete && (
            <div className="space-y-3">
              <Card className="p-3 bg-gray-50">
                <div className="space-y-2 text-sm">
                  <div className="flex items-center gap-2">
                    <span className="text-muted-foreground">姓名：</span>
                    <span>{contactToDelete.name}</span>
                  </div>
                  <div className="flex items-center gap-2">
                    <span className="text-muted-foreground">角色：</span>
                    <Badge variant="outline">{contactToDelete.role}</Badge>
                  </div>
                  <div className="flex items-center gap-2">
                    <Phone className="w-4 h-4 text-muted-foreground" />
                    <span>{contactToDelete.phone}</span>
                  </div>
                  <div className="flex items-center gap-2">
                    <Mail className="w-4 h-4 text-muted-foreground" />
                    <span className="truncate">{contactToDelete.email}</span>
                  </div>
                  <div className="flex items-center gap-2">
                    <Bell className="w-4 h-4 text-muted-foreground" />
                    <div className="flex gap-1">
                      {contactToDelete.channels.map((channel, index) => (
                        <Badge key={index} variant="outline" className="text-xs">
                          {channel}
                        </Badge>
                      ))}
                    </div>
                  </div>
                </div>
              </Card>

              <div className="p-3 bg-red-50 border border-red-200 rounded-md">
                <p className="text-sm text-red-800">
                  <strong>警告：</strong>删除后，该用户将不再接收任何告警通知。
                </p>
              </div>
            </div>
          )}
          
          <AlertDialogFooter>
            <AlertDialogCancel onClick={() => setContactToDelete(null)}>
              取消
            </AlertDialogCancel>
            <AlertDialogAction
              onClick={confirmDeleteContact}
              className="bg-red-600 hover:bg-red-700"
            >
              确认删除
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </div>
  );
}
