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 { Progress } from '../ui/progress';
import { Switch } from '../ui/switch';
import { Textarea } from '../ui/textarea';
import { Checkbox } from '../ui/checkbox';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription, DialogTrigger } from '../ui/dialog';
import {
  AlertTriangle,
  Bell,
  CheckCircle2,
  Clock,
  CloudRain,
  Droplets,
  Eye,
  FileText,
  Mail,
  MessageSquare,
  Phone,
  RefreshCw,
  Send,
  Snowflake,
  Sun,
  ThermometerSnowflake,
  TrendingDown,
  TrendingUp,
  Wifi,
  WifiOff,
  X,
  Zap,
  Bug,
  Wind,
  Activity,
  MapPin,
  User,
  CheckCheck,
  AlertCircle,
} from 'lucide-react';
import { toast } from 'sonner@2.0.3';
import {
  LineChart,
  Line,
  XAxis,
  YAxis,
  CartesianGrid,
  Tooltip,
  Legend,
  ResponsiveContainer,
  Area,
  AreaChart,
} from 'recharts';

interface FieldRiskWarningProps {
  activePath?: string;
}

type RiskLevel = '无风险' | '轻度风险' | '中度风险' | '高度风险';
type RiskType = '干旱' | '涝渍' | '低温' | '高温' | '病虫害' | '强风';
type DisposalStatus = '未查看' | '已查看' | '处理中' | '已完成';

interface RiskData {
  id: string;
  fieldId: string;
  fieldName: string;
  riskType: RiskType;
  riskLevel: RiskLevel;
  riskScore: number;
  indexValue: number;
  threshold: number;
  updateTime: string;
  sensorStatus: 'online' | 'offline';
  location: string;
  expectedImpact: string;
  suggestedActions: string[];
}

interface DisposalTimeline {
  time: string;
  action: string;
  operator: string;
  details?: string;
}

interface WarningRecord {
  id: string;
  fieldId: string;
  fieldName: string;
  riskType: RiskType;
  riskLevel: RiskLevel;
  warningTime: string;
  recipients: string[];
  channels: ('消息中心' | '短信' | '邮件')[];
  status: DisposalStatus;
  viewTime?: string;
  disposalPlan?: string;
  disposalPlanSubmitTime?: string;
  disposalResult?: string;
  completedTime?: string;
  responsible: string;
  timeline?: DisposalTimeline[];
  processingNotes?: string; // 处置过程记录
  resources?: string; // 调用资源
  actualCost?: string; // 实际成本
  effectEvaluation?: string; // 效果评估
}

interface PushRule {
  id: string;
  name: string;
  riskLevel: RiskLevel;
  condition: string;
  pushDelay: string;
  recipients: string[];
  channels: ('消息中心' | '短信' | '邮件')[];
  enabled: boolean;
}

export function FieldRiskWarning({ activePath }: FieldRiskWarningProps) {
  const [activeTab, setActiveTab] = useState('monitoring');
  const [autoRefresh, setAutoRefresh] = useState(true);
  const [selectedField, setSelectedField] = useState('all');
  const [showWarningDetail, setShowWarningDetail] = useState(false);
  const [selectedWarning, setSelectedWarning] = useState<WarningRecord | null>(null);
  const [disposalPlan, setDisposalPlan] = useState('');
  const [disposalResult, setDisposalResult] = useState('');
  const [processingNotes, setProcessingNotes] = useState('');
  const [resources, setResources] = useState('');
  const [actualCost, setActualCost] = useState('');
  const [effectEvaluation, setEffectEvaluation] = useState('');
  const [showRuleDialog, setShowRuleDialog] = useState(false);
  const [editingRule, setEditingRule] = useState<PushRule | null>(null);
  const [showRecordDetail, setShowRecordDetail] = useState(false);
  const [selectedRecord, setSelectedRecord] = useState<WarningRecord | null>(null);

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

  // 模拟实时风险数据
  const [riskData, setRiskData] = useState<RiskData[]>([
    {
      id: 'risk-1',
      fieldId: 'field-1',
      fieldName: '东区1号地',
      riskType: '干旱',
      riskLevel: '中度风险',
      riskScore: 65,
      indexValue: 0.35,
      threshold: 0.50,
      updateTime: '2024-10-15 14:35',
      sensorStatus: 'online',
      location: '东经120.15°, 北纬30.25°',
      expectedImpact: '预计未来3天无降雨，土壤湿度将持续下降，可能影响水稻生长',
      suggestedActions: ['启动喷灌系统', '增加灌溉频次', '监测土壤湿度'],
    },
    {
      id: 'risk-2',
      fieldId: 'field-2',
      fieldName: '西区2号地',
      riskLevel: '高度风险',
      riskType: '涝渍',
      riskScore: 85,
      indexValue: 0.82,
      threshold: 0.70,
      updateTime: '2024-10-15 14:33',
      sensorStatus: 'online',
      location: '东经120.12°, 北纬30.28°',
      expectedImpact: '连续强降雨导致积水严重，可能造成玉米根系缺氧',
      suggestedActions: ['开启排水系统', '清理排水沟渠', '加强巡查'],
    },
    {
      id: 'risk-3',
      fieldId: 'field-3',
      fieldName: '南区3号地',
      riskType: '低温',
      riskLevel: '轻度风险',
      riskScore: 45,
      indexValue: 8.5,
      threshold: 10.0,
      updateTime: '2024-10-15 14:30',
      sensorStatus: 'online',
      location: '东经120.18°, 北纬30.22°',
      expectedImpact: '夜间温度可能降至8℃以下，需注意作物保温',
      suggestedActions: ['准备保温材料', '关注天气预报', '适当延迟灌溉'],
    },
    {
      id: 'risk-4',
      fieldId: 'field-4',
      fieldName: '北区4号地',
      riskType: '病虫害',
      riskLevel: '中度风险',
      riskScore: 70,
      indexValue: 68,
      threshold: 50,
      updateTime: '2024-10-15 14:28',
      sensorStatus: 'offline',
      location: '东经120.20°, 北纬30.30°',
      expectedImpact: '温湿度适宜病虫害发生，需加强监测和防治',
      suggestedActions: ['喷洒预防性农药', '设置诱虫灯', '加强田间巡查'],
    },
  ]);

  // 预警记录
  const [warningRecords, setWarningRecords] = useState<WarningRecord[]>([
    {
      id: 'warn-1',
      fieldId: 'field-2',
      fieldName: '西区2号地',
      riskType: '涝渍',
      riskLevel: '高度风险',
      warningTime: '2024-10-15 14:33',
      recipients: ['张三', '李四', '王五'],
      channels: ['消息中心', '短信', '邮件'],
      status: '处理中',
      viewTime: '2024-10-15 14:35',
      disposalPlan: '已启动排水系统，派遣工作组前往现场清理排水沟渠',
      disposalPlanSubmitTime: '2024-10-15 14:40',
      responsible: '张三',
      processingNotes: '现场排水沟渠已清理完毕，正在使用水泵抽水',
      resources: '水泵2台，工作人员5人',
      timeline: [
        { time: '2024-10-15 14:33', action: '预警发出', operator: '系统', details: '检测到涝渍风险等级达到高度风险' },
        { time: '2024-10-15 14:35', action: '责任人查看', operator: '张三', details: '已确认接收预警信息' },
        { time: '2024-10-15 14:40', action: '提交处置方案', operator: '张三', details: '启动排水系统，派遣工作组清理沟渠' },
        { time: '2024-10-15 14:45', action: '开始处置', operator: '张三', details: '工作组已到达现场，开始清理作业' },
      ],
    },
    {
      id: 'warn-2',
      fieldId: 'field-1',
      fieldName: '东区1号地',
      riskType: '干旱',
      riskLevel: '中度风险',
      warningTime: '2024-10-15 14:35',
      recipients: ['张三', '李四'],
      channels: ['消息中心', '短信'],
      status: '已查看',
      viewTime: '2024-10-15 14:36',
      responsible: '李四',
      timeline: [
        { time: '2024-10-15 14:35', action: '预警发出', operator: '系统', details: '检测到干旱风险等级达到中度风险' },
        { time: '2024-10-15 14:36', action: '责任人查看', operator: '李四', details: '已确认接收预警信息' },
      ],
    },
    {
      id: 'warn-3',
      fieldId: 'field-3',
      fieldName: '南区3号地',
      riskType: '低温',
      riskLevel: '轻度风险',
      warningTime: '2024-10-15 14:30',
      recipients: ['王五'],
      channels: ['消息中心'],
      status: '已完成',
      viewTime: '2024-10-15 14:31',
      disposalPlan: '准备保温材料，延迟夜间灌溉',
      disposalPlanSubmitTime: '2024-10-15 14:33',
      disposalResult: '已完成保温材料准备，作物情况良好',
      completedTime: '2024-10-15 15:20',
      responsible: '王五',
      processingNotes: '已覆盖保温膜，调整灌溉时间至白天进行',
      resources: '保温膜200平方米，人员3人',
      actualCost: '1200元',
      effectEvaluation: '处置及时有效，作物未受低温影响，长势良好',
      timeline: [
        { time: '2024-10-15 14:30', action: '预警发出', operator: '系统', details: '检测到低温风险' },
        { time: '2024-10-15 14:31', action: '责任人查看', operator: '王五', details: '已确认接收预警' },
        { time: '2024-10-15 14:33', action: '提交处置方案', operator: '王五', details: '准备保温材料，调整灌溉计划' },
        { time: '2024-10-15 14:35', action: '开始处置', operator: '王五', details: '开始准备保温材料' },
        { time: '2024-10-15 15:20', action: '处置完成', operator: '王五', details: '保温措施实施完成，作物情况良好' },
      ],
    },
    {
      id: 'warn-4',
      fieldId: 'field-4',
      fieldName: '北区4号地',
      riskType: '病虫害',
      riskLevel: '中度风险',
      warningTime: '2024-10-15 14:28',
      recipients: ['张三', '赵六'],
      channels: ['消息中心', '短信', '邮件'],
      status: '未查看',
      responsible: '赵六',
      timeline: [
        { time: '2024-10-15 14:28', action: '预警发出', operator: '系统', details: '检测到病虫害风险等级达到中度风险' },
      ],
    },
  ]);

  // 推送规则
  const [pushRules, setPushRules] = useState<PushRule[]>([
    {
      id: 'rule-1',
      name: '高度风险规则',
      riskLevel: '高度风险',
      condition: '风险评分 ≥ 80',
      pushDelay: '立即推送',
      recipients: ['地块责任人', '系统管理员'],
      channels: ['消息中心', '短信', '邮件'],
      enabled: true,
    },
    {
      id: 'rule-2',
      name: '中度风险规则',
      riskLevel: '中度风险',
      condition: '风险评分 ≥ 60',
      pushDelay: '5分钟内推送',
      recipients: ['地块责任人'],
      channels: ['消息中心', '短信'],
      enabled: true,
    },
    {
      id: 'rule-3',
      name: '轻度风险规则',
      riskLevel: '轻度风险',
      condition: '风险评分 ≥ 40',
      pushDelay: '15分钟内推送',
      recipients: ['地块责任人'],
      channels: ['消息中心'],
      enabled: true,
    },
  ]);

  // 历史风险趋势数据
  const riskTrendData = [
    { time: '10:00', 干旱指数: 0.25, 涝渍指数: 0.15, 温度: 22 },
    { time: '11:00', 干旱指数: 0.28, 涝渍指数: 0.20, 温度: 24 },
    { time: '12:00', 干旱指数: 0.30, 涝渍指数: 0.35, 温度: 26 },
    { time: '13:00', 干旱指数: 0.32, 涝渍指数: 0.55, 温度: 27 },
    { time: '14:00', 干旱指数: 0.35, 涝渍指数: 0.82, 温度: 25 },
  ];

  const getRiskLevelColor = (level: RiskLevel) => {
    switch (level) {
      case '无风险': return 'bg-gray-500 text-white';
      case '轻度风险': return 'bg-yellow-500 text-white';
      case '中度风险': return 'bg-orange-500 text-white';
      case '高度风险': return 'bg-red-500 text-white';
      default: return 'bg-gray-500 text-white';
    }
  };

  const getRiskTypeIcon = (type: RiskType) => {
    switch (type) {
      case '干旱': return <Sun className="w-5 h-5" />;
      case '涝渍': return <CloudRain className="w-5 h-5" />;
      case '低温': return <Snowflake className="w-5 h-5" />;
      case '高温': return <ThermometerSnowflake className="w-5 h-5" />;
      case '病虫害': return <Bug className="w-5 h-5" />;
      case '强风': return <Wind className="w-5 h-5" />;
      default: return <AlertTriangle className="w-5 h-5" />;
    }
  };

  const getStatusIcon = (status: DisposalStatus) => {
    switch (status) {
      case '未查看': return <AlertCircle className="w-4 h-4" />;
      case '已查看': return <Eye className="w-4 h-4" />;
      case '处理中': return <Activity className="w-4 h-4" />;
      case '已完成': return <CheckCircle2 className="w-4 h-4" />;
      default: return <Clock className="w-4 h-4" />;
    }
  };

  const getStatusColor = (status: DisposalStatus) => {
    switch (status) {
      case '未查看': return 'text-red-600 bg-red-50';
      case '已查看': return 'text-blue-600 bg-blue-50';
      case '处理中': return 'text-orange-600 bg-orange-50';
      case '已完成': return 'text-green-600 bg-green-50';
      default: return 'text-gray-600 bg-gray-50';
    }
  };

  const handleSendWarning = (risk: RiskData) => {
    toast.success(`已向责任人推送${risk.fieldName}的${risk.riskType}预警`);
    const now = new Date().toLocaleString('zh-CN');
    // 创建新的预警记录
    const newWarning: WarningRecord = {
      id: `warn-${Date.now()}`,
      fieldId: risk.fieldId,
      fieldName: risk.fieldName,
      riskType: risk.riskType,
      riskLevel: risk.riskLevel,
      warningTime: now,
      recipients: ['张三', '李四'],
      channels: ['消息中心', '短信', '邮件'],
      status: '未查看',
      responsible: '张三',
      timeline: [
        { time: now, action: '预警发出', operator: '系统', details: `检测到${risk.riskType}风险等级达到${risk.riskLevel}` },
      ],
    };
    setWarningRecords([newWarning, ...warningRecords]);
  };

  const handleViewWarning = (warning: WarningRecord) => {
    setSelectedWarning(warning);
    setDisposalPlan(warning.disposalPlan || '');
    setDisposalResult(warning.disposalResult || '');
    setProcessingNotes(warning.processingNotes || '');
    setResources(warning.resources || '');
    setActualCost(warning.actualCost || '');
    setEffectEvaluation(warning.effectEvaluation || '');
    setShowWarningDetail(true);
  };

  const handleUpdateStatus = (status: DisposalStatus) => {
    if (!selectedWarning) return;

    const now = new Date().toLocaleString('zh-CN');
    const updatedRecords = warningRecords.map(record => {
      if (record.id === selectedWarning.id) {
        const updated = { ...record, status };
        const timeline = [...(record.timeline || [])];
        
        if (status === '已查看' && !record.viewTime) {
          updated.viewTime = now;
          timeline.push({
            time: now,
            action: '责任人查看',
            operator: record.responsible,
            details: '已确认接收预警信息',
          });
        }
        if (status === '处理中') {
          updated.disposalPlan = disposalPlan;
          updated.disposalPlanSubmitTime = now;
          updated.processingNotes = processingNotes;
          updated.resources = resources;
          timeline.push({
            time: now,
            action: '提交处置方案',
            operator: record.responsible,
            details: disposalPlan,
          });
          timeline.push({
            time: now,
            action: '开始处置',
            operator: record.responsible,
            details: '开始执行处置方案',
          });
        }
        if (status === '已完成') {
          updated.completedTime = now;
          updated.disposalResult = disposalResult;
          updated.actualCost = actualCost;
          updated.effectEvaluation = effectEvaluation;
          timeline.push({
            time: now,
            action: '处置完成',
            operator: record.responsible,
            details: disposalResult,
          });
        }
        
        updated.timeline = timeline;
        return updated;
      }
      return record;
    });

    setWarningRecords(updatedRecords);
    const updatedWarning = updatedRecords.find(r => r.id === selectedWarning.id) || selectedWarning;
    setSelectedWarning(updatedWarning);
    toast.success(`预警状态已更新为：${status}`);
  };

  const handleRefresh = () => {
    toast.success('风险数据已刷新');
  };

  // 推送规则管理
  const handleAddRule = () => {
    setEditingRule(null);
    setShowRuleDialog(true);
  };

  const handleEditRule = (rule: PushRule) => {
    setEditingRule(rule);
    setShowRuleDialog(true);
  };

  const handleDeleteRule = (ruleId: string) => {
    setPushRules(pushRules.filter(r => r.id !== ruleId));
    toast.success('推送规则已删除');
  };

  const handleSaveRule = () => {
    if (editingRule) {
      // 编辑
      setPushRules(pushRules.map(r => r.id === editingRule.id ? editingRule : r));
      toast.success('推送规则已更新');
    } else {
      // 新增
      const newRule: PushRule = {
        id: `rule-${Date.now()}`,
        name: '新规则',
        riskLevel: '中度风险',
        condition: '',
        pushDelay: '立即推送',
        recipients: [],
        channels: ['消息中心'],
        enabled: true,
      };
      setPushRules([...pushRules, newRule]);
      toast.success('推送规则已创建');
    }
    setShowRuleDialog(false);
  };

  // 推送记录操作
  const handleViewRecord = (record: WarningRecord) => {
    setSelectedRecord(record);
    setDisposalPlan(record.disposalPlan || '');
    setDisposalResult(record.disposalResult || '');
    setShowRecordDetail(true);
    
    // 如果是未查看状态，自动更新为已查看
    if (record.status === '未查看') {
      handleUpdateRecordStatus(record, '已查看');
    }
  };

  const handleStartProcess = (record: WarningRecord) => {
    // 更新状态为"处理中"
    const updatedRecords = warningRecords.map(r => {
      if (r.id === record.id) {
        const updated = { ...r, status: '处理中' as DisposalStatus };
        if (!r.viewTime) {
          updated.viewTime = new Date().toLocaleString('zh-CN');
        }
        return updated;
      }
      return r;
    });
    setWarningRecords(updatedRecords);
    toast.success('已开始处理，请填写处置方案');
    
    // 打开详情对话框
    const updatedRecord = updatedRecords.find(r => r.id === record.id);
    if (updatedRecord) {
      setSelectedRecord(updatedRecord);
      setDisposalPlan(updatedRecord.disposalPlan || '');
      setShowRecordDetail(true);
    }
  };

  const handleCompleteProcess = (record: WarningRecord) => {
    setSelectedRecord(record);
    setDisposalPlan(record.disposalPlan || '');
    setDisposalResult(record.disposalResult || '');
    setShowRecordDetail(true);
  };

  const handleUpdateRecordStatus = (record: WarningRecord, status: DisposalStatus) => {
    const updatedRecords = warningRecords.map(r => {
      if (r.id === record.id) {
        const updated = { ...r, status };
        if (status === '已查看' && !r.viewTime) {
          updated.viewTime = new Date().toLocaleString('zh-CN');
        }
        if (status === '处理中' && !r.viewTime) {
          updated.viewTime = new Date().toLocaleString('zh-CN');
        }
        return updated;
      }
      return r;
    });
    setWarningRecords(updatedRecords);
    toast.success(`状态已更新为：${status}`);
  };

  const handleSaveRecordDisposal = () => {
    if (!selectedRecord) return;

    const updatedRecords = warningRecords.map(r => {
      if (r.id === selectedRecord.id) {
        return {
          ...r,
          disposalPlan,
          disposalResult,
          status: disposalResult ? '已完��' : '处理中',
          completedTime: disposalResult ? new Date().toLocaleString('zh-CN') : r.completedTime,
        };
      }
      return r;
    });

    setWarningRecords(updatedRecords);
    setShowRecordDetail(false);
    toast.success('处置信息已保存');
  };

  const filteredRiskData = selectedField === 'all' 
    ? riskData 
    : riskData.filter(r => r.fieldId === selectedField);

  const filteredWarnings = selectedField === 'all'
    ? warningRecords
    : warningRecords.filter(w => w.fieldId === selectedField);

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h2 className="text-green-800">地块风险预警</h2>
          <p className="text-muted-foreground">
            实时风险监测、智能预警推送与处置跟踪闭环管理
          </p>
        </div>
        <div className="flex gap-2">
          <div className="flex items-center gap-2 px-4 py-2 bg-white rounded-lg border">
            <RefreshCw className="w-4 h-4 text-muted-foreground" />
            <span className="text-sm text-muted-foreground">自动刷新</span>
            <Switch checked={autoRefresh} onCheckedChange={setAutoRefresh} />
          </div>
          <Button variant="outline" onClick={handleRefresh}>
            <RefreshCw className="w-4 h-4 mr-2" />
            刷新数据
          </Button>
        </div>
      </div>

      {/* 地块筛选 */}
      <Card className="p-4">
        <div className="flex items-center gap-4">
          <label className="text-sm font-medium">筛选地块:</label>
          <Select value={selectedField} onValueChange={setSelectedField}>
            <SelectTrigger className="w-64">
              <SelectValue />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="all">全部地块</SelectItem>
              <SelectItem value="field-1">东区1号地</SelectItem>
              <SelectItem value="field-2">西区2号地</SelectItem>
              <SelectItem value="field-3">南区3号地</SelectItem>
              <SelectItem value="field-4">北区4号地</SelectItem>
            </SelectContent>
          </Select>
        </div>
      </Card>

      <Tabs value={activeTab} onValueChange={setActiveTab}>
        <TabsList className="grid w-full grid-cols-3">
          <TabsTrigger value="monitoring">实时风险监测</TabsTrigger>
          <TabsTrigger value="push">预警推送管理</TabsTrigger>
          <TabsTrigger value="disposal">预警处置跟踪</TabsTrigger>
        </TabsList>

        {/* 实时风险监测 */}
        <TabsContent value="monitoring" className="space-y-4">
          {/* 风险统计 */}
          <div className="grid grid-cols-4 gap-4">
            <Card className="p-6 bg-gradient-to-br from-red-50 to-red-100">
              <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">
                    {filteredRiskData.filter(r => r.riskLevel === '高度风险').length}
                  </p>
                </div>
                <AlertTriangle className="w-12 h-12 text-red-600 opacity-50" />
              </div>
            </Card>

            <Card className="p-6 bg-gradient-to-br from-orange-50 to-orange-100">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-xs text-muted-foreground">中度风险</p>
                  <p className="mt-2 text-3xl text-orange-600">
                    {filteredRiskData.filter(r => r.riskLevel === '中度风险').length}
                  </p>
                </div>
                <AlertCircle className="w-12 h-12 text-orange-600 opacity-50" />
              </div>
            </Card>

            <Card className="p-6 bg-gradient-to-br from-yellow-50 to-yellow-100">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-xs text-muted-foreground">轻度风险</p>
                  <p className="mt-2 text-3xl text-yellow-600">
                    {filteredRiskData.filter(r => r.riskLevel === '轻度风险').length}
                  </p>
                </div>
                <AlertTriangle className="w-12 h-12 text-yellow-600 opacity-50" />
              </div>
            </Card>

            <Card className="p-6 bg-gradient-to-br from-green-50 to-green-100">
              <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">
                    {filteredRiskData.filter(r => r.sensorStatus === 'online').length}/{filteredRiskData.length}
                  </p>
                </div>
                <Wifi className="w-12 h-12 text-green-600 opacity-50" />
              </div>
            </Card>
          </div>

          {/* 风险监测列表 */}
          <Card className="p-6">
            <h3 className="mb-4 flex items-center gap-2">
              <Activity className="w-5 h-5 text-blue-600" />
              实时风险监测
            </h3>
            <div className="space-y-4">
              {filteredRiskData.map(risk => (
                <Card key={risk.id} className="p-4 border-l-4" style={{
                  borderLeftColor: 
                    risk.riskLevel === '高度风险' ? '#ef4444' :
                    risk.riskLevel === '中度风险' ? '#f97316' :
                    risk.riskLevel === '轻度风险' ? '#eab308' : '#6b7280'
                }}>
                  <div className="flex items-start justify-between mb-3">
                    <div className="flex items-start gap-3">
                      <div className={`p-2 rounded-lg ${
                        risk.riskType === '干旱' ? 'bg-orange-100 text-orange-600' :
                        risk.riskType === '涝渍' ? 'bg-blue-100 text-blue-600' :
                        risk.riskType === '低温' ? 'bg-cyan-100 text-cyan-600' :
                        risk.riskType === '病虫害' ? 'bg-green-100 text-green-600' :
                        'bg-gray-100 text-gray-600'
                      }`}>
                        {getRiskTypeIcon(risk.riskType)}
                      </div>
                      <div>
                        <div className="flex items-center gap-2 mb-1">
                          <h4>{risk.fieldName}</h4>
                          <Badge className={getRiskLevelColor(risk.riskLevel)}>
                            {risk.riskLevel}
                          </Badge>
                          <Badge variant="outline" className="text-xs">
                            {risk.riskType}
                          </Badge>
                          {risk.sensorStatus === 'online' ? (
                            <Wifi className="w-4 h-4 text-green-500" />
                          ) : (
                            <WifiOff className="w-4 h-4 text-red-500" />
                          )}
                        </div>
                        <p className="text-sm text-muted-foreground flex items-center gap-2">
                          <MapPin className="w-3 h-3" />
                          {risk.location}
                        </p>
                      </div>
                    </div>
                    <div className="text-right">
                      <p className="text-xs text-muted-foreground">风险评分</p>
                      <p className="text-2xl font-medium text-red-600">{risk.riskScore}</p>
                    </div>
                  </div>

                  <div className="grid grid-cols-2 gap-4 mb-3">
                    <div className="p-3 bg-gray-50 rounded-lg">
                      <p className="text-xs text-muted-foreground mb-1">指标值</p>
                      <div className="flex items-center gap-2">
                        <Progress value={(risk.indexValue / risk.threshold) * 100} className="flex-1" />
                        <span className="text-sm font-medium">
                          {risk.indexValue.toFixed(2)}
                        </span>
                      </div>
                      <p className="text-xs text-muted-foreground mt-1">
                        阈值: {risk.threshold.toFixed(2)}
                      </p>
                    </div>
                    <div className="p-3 bg-gray-50 rounded-lg">
                      <p className="text-xs text-muted-foreground mb-1">更新时间</p>
                      <p className="text-sm font-medium flex items-center gap-1">
                        <Clock className="w-3 h-3" />
                        {risk.updateTime}
                      </p>
                    </div>
                  </div>

                  <div className="p-3 bg-orange-50 border border-orange-200 rounded-lg mb-3">
                    <p className="text-xs text-orange-900 mb-1 flex items-center gap-1">
                      <AlertTriangle className="w-3 h-3" />
                      预期影响
                    </p>
                    <p className="text-sm text-orange-800">{risk.expectedImpact}</p>
                  </div>

                  <div className="p-3 bg-green-50 border border-green-200 rounded-lg mb-3">
                    <p className="text-xs text-green-900 mb-2 flex items-center gap-1">
                      <Zap className="w-3 h-3" />
                      建议措施
                    </p>
                    <ul className="space-y-1">
                      {risk.suggestedActions.map((action, index) => (
                        <li key={index} className="text-sm text-green-800 flex items-start gap-2">
                          <CheckCircle2 className="w-4 h-4 mt-0.5 flex-shrink-0" />
                          <span>{action}</span>
                        </li>
                      ))}
                    </ul>
                  </div>
                </Card>
              ))}
            </div>
          </Card>

          {/* 风险趋势图 */}
          <Card className="p-6">
            <h3 className="mb-4 flex items-center gap-2">
              <TrendingUp className="w-5 h-5 text-purple-600" />
              风险指数趋势
            </h3>
            <div className="h-80">
              <ResponsiveContainer width="100%" height="100%">
                <AreaChart data={riskTrendData}>
                  <CartesianGrid strokeDasharray="3 3" />
                  <XAxis dataKey="time" />
                  <YAxis />
                  <Tooltip />
                  <Legend />
                  <Area type="monotone" dataKey="干旱指数" stroke="#f97316" fill="#fed7aa" />
                  <Area type="monotone" dataKey="涝渍指数" stroke="#3b82f6" fill="#bfdbfe" />
                </AreaChart>
              </ResponsiveContainer>
            </div>
          </Card>

          {/* 算法说明 */}
          <Card className="p-4 bg-blue-50 border-blue-200">
            <div className="flex items-start gap-2">
              <Zap 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>: 基于土壤湿度、降雨量、蒸发量计算，指数&lt;0.5触发预警</li>
                  <li>• <strong>涝渍指数</strong>: 基于降雨强度、土壤排水性、地表积水深度，指数&gt;0.7触发预警</li>
                  <li>• <strong>低温强度</strong>: 基于气温、持续时长、作物耐寒性，温度&lt;10°C触发预警</li>
                  <li>• <strong>病虫害风险</strong>: 基于温湿度、历史数据、作物生长期，综合评分&gt;50触发预警</li>
                  <li>• <strong>风险等级</strong>: 根据指数偏离阈值程度自动分级（轻度/中度/高度）</li>
                </ul>
              </div>
            </div>
          </Card>
        </TabsContent>

        {/* 预警推送管理 */}
        <TabsContent value="push" className="space-y-4">
          {/* 推送渠道配置 */}
          <Card className="p-6">
            <h3 className="mb-4 flex items-center gap-2">
              <Send className="w-5 h-5 text-green-600" />
              推送渠道配置
            </h3>
            <div className="grid grid-cols-3 gap-4">
              <div className="p-4 bg-blue-50 rounded-lg">
                <div className="flex items-center justify-between mb-3">
                  <div className="flex items-center gap-2">
                    <MessageSquare className="w-5 h-5 text-blue-600" />
                    <span className="font-medium">消息中心</span>
                  </div>
                  <Switch defaultChecked />
                </div>
                <p className="text-xs text-muted-foreground">实时推送至系统消息中心</p>
                <p className="text-xs text-blue-600 mt-2">✓ 已启用</p>
              </div>

              <div className="p-4 bg-green-50 rounded-lg">
                <div className="flex items-center justify-between mb-3">
                  <div className="flex items-center gap-2">
                    <Phone className="w-5 h-5 text-green-600" />
                    <span className="font-medium">短信通知</span>
                  </div>
                  <Switch defaultChecked />
                </div>
                <p className="text-xs text-muted-foreground">发送短信至责任人手机</p>
                <p className="text-xs text-green-600 mt-2">✓ 已启用</p>
              </div>

              <div className="p-4 bg-purple-50 rounded-lg">
                <div className="flex items-center justify-between mb-3">
                  <div className="flex items-center gap-2">
                    <Mail className="w-5 h-5 text-purple-600" />
                    <span className="font-medium">邮件通知</span>
                  </div>
                  <Switch defaultChecked />
                </div>
                <p className="text-xs text-muted-foreground">发送邮件至责任人邮箱</p>
                <p className="text-xs text-purple-600 mt-2">✓ 已启用</p>
              </div>
            </div>
          </Card>

          {/* 推送规则 */}
          <Card className="p-6">
            <div className="flex items-center justify-between mb-4">
              <h3 className="flex items-center gap-2">
                <Bell className="w-5 h-5 text-orange-600" />
                预警推送规则
              </h3>
              <Button onClick={handleAddRule} className="bg-green-600 hover:bg-green-700">
                <Bell className="w-4 h-4 mr-2" />
                新增规则
              </Button>
            </div>
            <div className="space-y-4">
              {pushRules.map(rule => (
                <div key={rule.id} className="p-4 bg-gray-50 rounded-lg">
                  <div className="flex items-center justify-between mb-3">
                    <div className="flex items-center gap-3">
                      <h4 className="flex items-center gap-2">
                        {rule.riskLevel === '高度风险' && <AlertTriangle className="w-4 h-4 text-red-500" />}
                        {rule.riskLevel === '中度风险' && <AlertCircle className="w-4 h-4 text-orange-500" />}
                        {rule.riskLevel === '轻度风险' && <AlertTriangle className="w-4 h-4 text-yellow-500" />}
                        {rule.name}
                      </h4>
                      <Badge className={getRiskLevelColor(rule.riskLevel)}>
                        {rule.riskLevel}
                      </Badge>
                      <Badge variant="outline" className="text-xs">
                        {rule.pushDelay}
                      </Badge>
                      {!rule.enabled && (
                        <Badge variant="outline" className="text-xs text-gray-500">
                          已禁用
                        </Badge>
                      )}
                    </div>
                    <div className="flex gap-2">
                      <Button size="sm" variant="outline" onClick={() => handleEditRule(rule)}>
                        编辑
                      </Button>
                      <Button 
                        size="sm" 
                        variant="outline" 
                        className="text-red-600 hover:text-red-700"
                        onClick={() => handleDeleteRule(rule.id)}
                      >
                        删除
                      </Button>
                    </div>
                  </div>
                  <p className="text-sm text-muted-foreground mb-2">
                    触发条件: {rule.condition}
                  </p>
                  <div className="grid grid-cols-2 gap-4">
                    <div className="text-sm">
                      <p className="text-xs text-muted-foreground mb-1">推送对象:</p>
                      <div className="flex gap-1 flex-wrap">
                        {rule.recipients.map((recipient, i) => (
                          <Badge key={i} variant="outline" className="text-xs">
                            {recipient}
                          </Badge>
                        ))}
                      </div>
                    </div>
                    <div className="text-sm">
                      <p className="text-xs text-muted-foreground mb-1">推送渠道:</p>
                      <div className="flex gap-1 flex-wrap">
                        {rule.channels.map((channel, i) => (
                          <Badge key={i} variant="outline" className="text-xs">
                            {channel}
                          </Badge>
                        ))}
                      </div>
                    </div>
                  </div>
                </div>
              ))}
            </div>
          </Card>

          {/* 最近推送记录 */}
          <Card className="p-6">
            <h3 className="mb-4 flex items-center gap-2">
              <CheckCheck className="w-5 h-5 text-blue-600" />
              最近推送记录
            </h3>
            <div className="overflow-x-auto">
              <table className="w-full">
                <thead className="bg-gray-50">
                  <tr>
                    <th className="px-4 py-3 text-left text-xs">推送时间</th>
                    <th className="px-4 py-3 text-left text-xs">地块</th>
                    <th className="px-4 py-3 text-left text-xs">风险类型</th>
                    <th className="px-4 py-3 text-center text-xs">风险等级</th>
                    <th className="px-4 py-3 text-left text-xs">推送渠道</th>
                    <th className="px-4 py-3 text-left text-xs">责任人</th>
                    <th className="px-4 py-3 text-center text-xs">状态</th>
                    <th className="px-4 py-3 text-center text-xs">操作</th>
                  </tr>
                </thead>
                <tbody>
                  {filteredWarnings.slice(0, 10).map(record => (
                    <tr key={record.id} className="border-t hover:bg-gray-50">
                      <td className="px-4 py-3 text-sm">{record.warningTime}</td>
                      <td className="px-4 py-3 text-sm">{record.fieldName}</td>
                      <td className="px-4 py-3 text-sm">
                        <div className="flex items-center gap-2">
                          {getRiskTypeIcon(record.riskType)}
                          {record.riskType}
                        </div>
                      </td>
                      <td className="px-4 py-3 text-center">
                        <Badge className={getRiskLevelColor(record.riskLevel)}>
                          {record.riskLevel}
                        </Badge>
                      </td>
                      <td className="px-4 py-3">
                        <div className="flex gap-1">
                          {record.channels.map((channel, i) => (
                            <Badge key={i} variant="outline" className="text-xs">
                              {channel}
                            </Badge>
                          ))}
                        </div>
                      </td>
                      <td className="px-4 py-3 text-sm">
                        {record.responsible}
                      </td>
                      <td className="px-4 py-3 text-center">
                        <div className={`inline-flex items-center gap-1 px-2 py-1 rounded-full ${getStatusColor(record.status)}`}>
                          {getStatusIcon(record.status)}
                          <span className="text-xs">{record.status}</span>
                        </div>
                      </td>
                      <td className="px-4 py-3">
                        <div className="flex gap-1 justify-center">
                          <Button 
                            size="sm" 
                            variant="outline"
                            onClick={() => handleViewRecord(record)}
                          >
                            <Eye className="w-3 h-3 mr-1" />
                            查看
                          </Button>
                        </div>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          </Card>
        </TabsContent>

        {/* 预警处置跟踪 */}
        <TabsContent value="disposal" className="space-y-4">
          {/* 处置状态统计 */}
          <div className="grid 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-red-600">
                    {filteredWarnings.filter(w => w.status === '未查看').length}
                  </p>
                </div>
                <AlertCircle 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-blue-600">
                    {filteredWarnings.filter(w => w.status === '已查看').length}
                  </p>
                </div>
                <Eye 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-orange-600">
                    {filteredWarnings.filter(w => w.status === '处理中').length}
                  </p>
                </div>
                <Activity className="w-12 h-12 text-orange-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">
                    {filteredWarnings.filter(w => w.status === '已完成').length}
                  </p>
                </div>
                <CheckCircle2 className="w-12 h-12 text-green-600 opacity-50" />
              </div>
            </Card>
          </div>

          {/* 预警处置列表 */}
          <Card className="p-6">
            <h3 className="mb-4 flex items-center gap-2">
              <Activity className="w-5 h-5 text-purple-600" />
              预警处置跟踪
            </h3>
            <div className="space-y-4">
              {filteredWarnings.map(warning => (
                <Card key={warning.id} className="p-4 hover:shadow-md transition-shadow">
                  <div className="flex items-start justify-between mb-3">
                    <div className="flex items-start gap-3">
                      <div className={`p-2 rounded-lg ${
                        warning.riskType === '干旱' ? 'bg-orange-100 text-orange-600' :
                        warning.riskType === '涝渍' ? 'bg-blue-100 text-blue-600' :
                        warning.riskType === '低温' ? 'bg-cyan-100 text-cyan-600' :
                        warning.riskType === '病虫害' ? 'bg-green-100 text-green-600' :
                        'bg-gray-100 text-gray-600'
                      }`}>
                        {getRiskTypeIcon(warning.riskType)}
                      </div>
                      <div>
                        <div className="flex items-center gap-2 mb-1">
                          <h4>{warning.fieldName}</h4>
                          <Badge className={getRiskLevelColor(warning.riskLevel)}>
                            {warning.riskLevel}
                          </Badge>
                          <Badge variant="outline" className="text-xs">
                            {warning.riskType}
                          </Badge>
                        </div>
                        <p className="text-sm text-muted-foreground">
                          预警时间: {warning.warningTime}
                        </p>
                      </div>
                    </div>
                    <div className={`px-3 py-1.5 rounded-full flex items-center gap-2 ${getStatusColor(warning.status)}`}>
                      {getStatusIcon(warning.status)}
                      <span className="text-sm font-medium">{warning.status}</span>
                    </div>
                  </div>

                  <div className="grid grid-cols-2 gap-4 mb-3">
                    <div className="p-3 bg-gray-50 rounded-lg">
                      <p className="text-xs text-muted-foreground mb-1">责任人</p>
                      <p className="text-sm font-medium flex items-center gap-1">
                        <User className="w-3 h-3" />
                        {warning.responsible}
                      </p>
                    </div>
                    <div className="p-3 bg-gray-50 rounded-lg">
                      <p className="text-xs text-muted-foreground mb-1">接收人</p>
                      <p className="text-sm">{warning.recipients.join(', ')}</p>
                    </div>
                  </div>

                  {/* 处置流程进度 */}
                  <div className="mb-3 p-4 bg-gray-50 rounded-lg">
                    <div className="flex items-center justify-between text-xs mb-2">
                      <span className="text-muted-foreground">处置进度</span>
                      <span className="text-purple-600 font-medium">
                        {warning.timeline?.length || 0} 个节点
                      </span>
                    </div>
                    <div className="flex items-center gap-2">
                      <div className={`flex-1 h-2 rounded-full ${
                        warning.status === '未查看' ? 'bg-red-200' :
                        warning.status === '已查看' ? 'bg-blue-200' :
                        warning.status === '处理中' ? 'bg-orange-200' :
                        'bg-green-200'
                      }`}>
                        <div className={`h-full rounded-full transition-all ${
                          warning.status === '未查看' ? 'w-[25%] bg-red-500' :
                          warning.status === '已查看' ? 'w-[50%] bg-blue-500' :
                          warning.status === '处理中' ? 'w-[75%] bg-orange-500' :
                          'w-full bg-green-500'
                        }`} />
                      </div>
                      <span className="text-xs font-medium">
                        {warning.status === '未查看' ? '25%' :
                         warning.status === '已查看' ? '50%' :
                         warning.status === '处理中' ? '75%' : '100%'}
                      </span>
                    </div>
                  </div>

                  {warning.viewTime && (
                    <div className="p-3 bg-blue-50 rounded-lg mb-3">
                      <p className="text-xs text-blue-900 mb-1 flex items-center gap-1">
                        <Eye className="w-3 h-3" />
                        查看时间
                      </p>
                      <p className="text-sm text-blue-800">{warning.viewTime}</p>
                    </div>
                  )}

                  {warning.disposalPlan && (
                    <div className="p-3 bg-orange-50 rounded-lg mb-3">
                      <p className="text-xs text-orange-900 mb-1 flex items-center gap-1">
                        <FileText className="w-3 h-3" />
                        处置方案
                      </p>
                      <p className="text-sm text-orange-800 line-clamp-2">{warning.disposalPlan}</p>
                      {warning.disposalPlanSubmitTime && (
                        <p className="text-xs text-orange-600 mt-1">
                          提交于: {warning.disposalPlanSubmitTime}
                        </p>
                      )}
                    </div>
                  )}

                  {warning.disposalResult && (
                    <div className="p-3 bg-green-50 rounded-lg mb-3">
                      <p className="text-xs text-green-900 mb-1 flex items-center gap-1">
                        <CheckCircle2 className="w-3 h-3" />
                        处置结果
                      </p>
                      <p className="text-sm text-green-800 line-clamp-2">{warning.disposalResult}</p>
                      <p className="text-xs text-green-700 mt-1">
                        完成时间: {warning.completedTime}
                      </p>
                      {warning.effectEvaluation && (
                        <div className="mt-2 pt-2 border-t border-green-200">
                          <p className="text-xs text-green-900 mb-1">效果评估</p>
                          <p className="text-sm text-green-800 line-clamp-1">{warning.effectEvaluation}</p>
                        </div>
                      )}
                    </div>
                  )}

                  <div className="flex gap-2">
                    <Button
                      size="sm"
                      variant="outline"
                      onClick={() => handleViewWarning(warning)}
                    >
                      <Eye className="w-4 h-4 mr-2" />
                      查看工作流
                    </Button>
                    {warning.timeline && warning.timeline.length > 0 && (
                      <Badge variant="outline" className="text-xs flex items-center gap-1">
                        <Clock className="w-3 h-3" />
                        {warning.timeline.length} 条记录
                      </Badge>
                    )}
                  </div>
                </Card>
              ))}
            </div>
          </Card>

          {/* 流程说明 */}
          <Card className="p-6 bg-gradient-to-r from-green-50 to-blue-50 border-green-200">
            <div className="space-y-4">
              <div className="flex items-center gap-2">
                <CheckCircle2 className="w-6 h-6 text-green-600" />
                <h3>预警处置工作流闭环管理</h3>
              </div>
              
              <div className="bg-white rounded-lg p-4">
                <p className="text-sm text-gray-700 mb-3">完整的处置流程：</p>
                <div className="flex items-center gap-2 flex-wrap">
                  <div className="flex items-center gap-2">
                    <div className="w-8 h-8 rounded-full bg-red-500 text-white flex items-center justify-center text-sm">1</div>
                    <span className="text-sm">预警发出</span>
                  </div>
                  <span className="text-gray-400">→</span>
                  <div className="flex items-center gap-2">
                    <div className="w-8 h-8 rounded-full bg-blue-500 text-white flex items-center justify-center text-sm">2</div>
                    <span className="text-sm">接收查看</span>
                  </div>
                  <span className="text-gray-400">→</span>
                  <div className="flex items-center gap-2">
                    <div className="w-8 h-8 rounded-full bg-orange-500 text-white flex items-center justify-center text-sm">3</div>
                    <span className="text-sm">提交方案</span>
                  </div>
                  <span className="text-gray-400">→</span>
                  <div className="flex items-center gap-2">
                    <div className="w-8 h-8 rounded-full bg-purple-500 text-white flex items-center justify-center text-sm">4</div>
                    <span className="text-sm">现场处置</span>
                  </div>
                  <span className="text-gray-400">→</span>
                  <div className="flex items-center gap-2">
                    <div className="w-8 h-8 rounded-full bg-green-500 text-white flex items-center justify-center text-sm">5</div>
                    <span className="text-sm">反馈结果</span>
                  </div>
                </div>
              </div>

              <div className="grid grid-cols-2 gap-4">
                <div className="bg-white rounded-lg p-3">
                  <h4 className="flex items-center gap-2 mb-2">
                    <Clock className="w-4 h-4 text-blue-600" />
                    时间线追踪
                  </h4>
                  <ul className="space-y-1 text-xs text-gray-600">
                    <li>• 完整记录每个处置节点的时间</li>
                    <li>• 记录操作人员和详细内容</li>
                    <li>• 支持全程追溯和审计</li>
                  </ul>
                </div>
                <div className="bg-white rounded-lg p-3">
                  <h4 className="flex items-center gap-2 mb-2">
                    <FileText className="w-4 h-4 text-orange-600" />
                    方案管理
                  </h4>
                  <ul className="space-y-1 text-xs text-gray-600">
                    <li>• 责任人提交详细处置方案</li>
                    <li>• 记录调用资源和实际成本</li>
                    <li>• 处置过程全程记录</li>
                  </ul>
                </div>
                <div className="bg-white rounded-lg p-3">
                  <h4 className="flex items-center gap-2 mb-2">
                    <Activity className="w-4 h-4 text-purple-600" />
                    状态跟踪
                  </h4>
                  <ul className="space-y-1 text-xs text-gray-600">
                    <li>• 实时更新处置状态</li>
                    <li>• 可视化进度展示</li>
                    <li>• 未处理预警自动提醒</li>
                  </ul>
                </div>
                <div className="bg-white rounded-lg p-3">
                  <h4 className="flex items-center gap-2 mb-2">
                    <CheckCheck className="w-4 h-4 text-green-600" />
                    效果评估
                  </h4>
                  <ul className="space-y-1 text-xs text-gray-600">
                    <li>• 处置完成后效果评估</li>
                    <li>• 成本收益分析</li>
                    <li>• 经验积累和改进</li>
                  </ul>
                </div>
              </div>

              <div className="bg-yellow-50 border border-yellow-200 rounded-lg p-3">
                <p className="text-xs text-yellow-900 flex items-start gap-2">
                  <AlertTriangle className="w-4 h-4 flex-shrink-0 mt-0.5" />
                  <span>
                    <strong>重要提示：</strong>
                    预警发出后需及时处理，未查看的预警将在30分钟后自动升级推送给系统管理员。
                    所有处置记录将永久保存，用于后续分析和决策优化。
                  </span>
                </p>
              </div>
            </div>
          </Card>
        </TabsContent>
      </Tabs>

      {/* 预警详情对话框 */}
      <Dialog open={showWarningDetail} onOpenChange={setShowWarningDetail}>
        <DialogContent className="max-w-4xl max-h-[90vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle>预警处置工作流</DialogTitle>
            <DialogDescription className="sr-only">
              查看和处理风险预警的详细信息
            </DialogDescription>
          </DialogHeader>
          {selectedWarning && (
            <div className="space-y-6">
              {/* 基本信息 */}
              <div className="p-4 bg-gray-50 rounded-lg">
                <div className="grid grid-cols-3 gap-4">
                  <div>
                    <p className="text-xs text-muted-foreground">地块名称</p>
                    <p className="text-sm font-medium mt-1">{selectedWarning.fieldName}</p>
                  </div>
                  <div>
                    <p className="text-xs text-muted-foreground">风险类型</p>
                    <div className="flex items-center gap-2 mt-1">
                      {getRiskTypeIcon(selectedWarning.riskType)}
                      <span className="text-sm font-medium">{selectedWarning.riskType}</span>
                    </div>
                  </div>
                  <div>
                    <p className="text-xs text-muted-foreground">风险等级</p>
                    <Badge className={`mt-1 ${getRiskLevelColor(selectedWarning.riskLevel)}`}>
                      {selectedWarning.riskLevel}
                    </Badge>
                  </div>
                  <div>
                    <p className="text-xs text-muted-foreground">预警时间</p>
                    <p className="text-sm font-medium mt-1">{selectedWarning.warningTime}</p>
                  </div>
                  <div>
                    <p className="text-xs text-muted-foreground">责任人</p>
                    <p className="text-sm font-medium mt-1 flex items-center gap-1">
                      <User className="w-3 h-3" />
                      {selectedWarning.responsible}
                    </p>
                  </div>
                  <div>
                    <p className="text-xs text-muted-foreground">当前状态</p>
                    <div className={`inline-flex items-center gap-1 px-2 py-1 rounded-full mt-1 ${getStatusColor(selectedWarning.status)}`}>
                      {getStatusIcon(selectedWarning.status)}
                      <span className="text-xs">{selectedWarning.status}</span>
                    </div>
                  </div>
                </div>
              </div>

              <Tabs defaultValue="process" className="w-full">
                <TabsList className="grid w-full grid-cols-3">
                  <TabsTrigger value="process">处置流程</TabsTrigger>
                  <TabsTrigger value="timeline">时间线</TabsTrigger>
                  <TabsTrigger value="details">详细信息</TabsTrigger>
                </TabsList>

                <TabsContent value="process" className="space-y-4 mt-4">
                  {/* 1. 查看确认 */}
                  <Card className={`p-4 ${selectedWarning.status !== '未查看' ? 'bg-blue-50' : ''}`}>
                    <div className="flex items-center gap-3 mb-3">
                      <div className={`w-8 h-8 rounded-full flex items-center justify-center ${
                        selectedWarning.status !== '未查看' ? 'bg-blue-600 text-white' : 'bg-gray-300 text-gray-600'
                      }`}>
                        1
                      </div>
                      <div>
                        <h4>接收查看</h4>
                        <p className="text-xs text-muted-foreground">责任人确认接收预警信息</p>
                      </div>
                    </div>
                    {selectedWarning.viewTime && (
                      <div className="ml-11 text-sm text-blue-600">
                        ✓ 已查看于 {selectedWarning.viewTime}
                      </div>
                    )}
                    {selectedWarning.status === '未查看' && (
                      <div className="ml-11">
                        <Button
                          size="sm"
                          className="bg-blue-600 hover:bg-blue-700"
                          onClick={() => handleUpdateStatus('已查看')}
                        >
                          <Eye className="w-4 h-4 mr-2" />
                          确认查看
                        </Button>
                      </div>
                    )}
                  </Card>

                  {/* 2. 制定方案 */}
                  <Card className={`p-4 ${selectedWarning.status === '处理中' || selectedWarning.status === '已完成' ? 'bg-orange-50' : ''}`}>
                    <div className="flex items-center gap-3 mb-3">
                      <div className={`w-8 h-8 rounded-full flex items-center justify-center ${
                        selectedWarning.status === '处理中' || selectedWarning.status === '已完成' ? 'bg-orange-600 text-white' : 'bg-gray-300 text-gray-600'
                      }`}>
                        2
                      </div>
                      <div>
                        <h4>制定方案</h4>
                        <p className="text-xs text-muted-foreground">提交详细的处置方案</p>
                      </div>
                    </div>
                    {selectedWarning.disposalPlan ? (
                      <div className="ml-11 space-y-2">
                        <div className="p-3 bg-white rounded border border-orange-200">
                          <p className="text-xs text-orange-900 mb-1">处置方案</p>
                          <p className="text-sm text-orange-800">{selectedWarning.disposalPlan}</p>
                        </div>
                        {selectedWarning.disposalPlanSubmitTime && (
                          <p className="text-xs text-orange-600">
                            ✓ 提交于 {selectedWarning.disposalPlanSubmitTime}
                          </p>
                        )}
                      </div>
                    ) : selectedWarning.status === '已查看' ? (
                      <div className="ml-11 space-y-3">
                        <div>
                          <label>处置方案</label>
                          <Textarea
                            value={disposalPlan}
                            onChange={(e) => setDisposalPlan(e.target.value)}
                            placeholder="请详细描述处置方案，包括具体措施、时间安排、人员分工等..."
                            rows={4}
                            className="mt-2"
                          />
                        </div>
                        <div className="grid grid-cols-2 gap-3">
                          <div>
                            <label>调用资源</label>
                            <Textarea
                              value={resources}
                              onChange={(e) => setResources(e.target.value)}
                              placeholder="人员、设备、物资等..."
                              rows={2}
                              className="mt-2"
                            />
                          </div>
                          <div>
                            <label>处置记录</label>
                            <Textarea
                              value={processingNotes}
                              onChange={(e) => setProcessingNotes(e.target.value)}
                              placeholder="现场处置过程记录..."
                              rows={2}
                              className="mt-2"
                            />
                          </div>
                        </div>
                        <Button
                          className="bg-orange-600 hover:bg-orange-700"
                          onClick={() => handleUpdateStatus('处理中')}
                          disabled={!disposalPlan.trim()}
                        >
                          <Activity className="w-4 h-4 mr-2" />
                          提交方案并开始处置
                        </Button>
                      </div>
                    ) : null}
                  </Card>

                  {/* 3. 现场处置 */}
                  <Card className={`p-4 ${selectedWarning.status === '已完成' ? 'bg-green-50' : ''}`}>
                    <div className="flex items-center gap-3 mb-3">
                      <div className={`w-8 h-8 rounded-full flex items-center justify-center ${
                        selectedWarning.status === '已完成' ? 'bg-green-600 text-white' : 'bg-gray-300 text-gray-600'
                      }`}>
                        3
                      </div>
                      <div>
                        <h4>处置完成</h4>
                        <p className="text-xs text-muted-foreground">记录处置结果和效果评估</p>
                      </div>
                    </div>
                    {selectedWarning.disposalResult ? (
                      <div className="ml-11 space-y-2">
                        <div className="p-3 bg-white rounded border border-green-200">
                          <p className="text-xs text-green-900 mb-1">处置结果</p>
                          <p className="text-sm text-green-800">{selectedWarning.disposalResult}</p>
                        </div>
                        {selectedWarning.actualCost && (
                          <div className="p-2 bg-white rounded border border-green-200">
                            <p className="text-xs text-green-900">实际成本：{selectedWarning.actualCost}</p>
                          </div>
                        )}
                        {selectedWarning.effectEvaluation && (
                          <div className="p-3 bg-white rounded border border-green-200">
                            <p className="text-xs text-green-900 mb-1">效果评估</p>
                            <p className="text-sm text-green-800">{selectedWarning.effectEvaluation}</p>
                          </div>
                        )}
                        <p className="text-xs text-green-600">
                          ✓ 完成于 {selectedWarning.completedTime}
                        </p>
                      </div>
                    ) : selectedWarning.status === '处理中' ? (
                      <div className="ml-11 space-y-3">
                        <div>
                          <label>处置结果</label>
                          <Textarea
                            value={disposalResult}
                            onChange={(e) => setDisposalResult(e.target.value)}
                            placeholder="请详细描述处置结果、解决情况、当前作物状态等..."
                            rows={4}
                            className="mt-2"
                          />
                        </div>
                        <div className="grid grid-cols-2 gap-3">
                          <div>
                            <label>实际成本</label>
                            <Textarea
                              value={actualCost}
                              onChange={(e) => setActualCost(e.target.value)}
                              placeholder="人工、材料等实际成本..."
                              rows={2}
                              className="mt-2"
                            />
                          </div>
                          <div>
                            <label>效果评估</label>
                            <Textarea
                              value={effectEvaluation}
                              onChange={(e) => setEffectEvaluation(e.target.value)}
                              placeholder="处置效果、作物恢复情况等..."
                              rows={2}
                              className="mt-2"
                            />
                          </div>
                        </div>
                        <Button
                          className="bg-green-600 hover:bg-green-700"
                          onClick={() => handleUpdateStatus('已完成')}
                          disabled={!disposalResult.trim()}
                        >
                          <CheckCircle2 className="w-4 h-4 mr-2" />
                          确认完成处置
                        </Button>
                      </div>
                    ) : null}
                  </Card>
                </TabsContent>

                <TabsContent value="timeline" className="mt-4">
                  <Card className="p-4">
                    <h4 className="mb-4 flex items-center gap-2">
                      <Clock className="w-5 h-5 text-purple-600" />
                      处置时间线
                    </h4>
                    {selectedWarning.timeline && selectedWarning.timeline.length > 0 ? (
                      <div className="space-y-4">
                        {selectedWarning.timeline.map((item, index) => (
                          <div key={index} className="flex gap-4">
                            <div className="flex flex-col items-center">
                              <div className={`w-3 h-3 rounded-full ${
                                index === 0 ? 'bg-red-500' :
                                index === selectedWarning.timeline!.length - 1 ? 'bg-green-500' :
                                'bg-blue-500'
                              }`} />
                              {index < selectedWarning.timeline!.length - 1 && (
                                <div className="w-0.5 h-12 bg-gray-300" />
                              )}
                            </div>
                            <div className="flex-1 pb-4">
                              <div className="flex items-center gap-2 mb-1">
                                <span className="text-sm font-medium">{item.action}</span>
                                <Badge variant="outline" className="text-xs">{item.operator}</Badge>
                              </div>
                              <p className="text-xs text-muted-foreground mb-1">{item.time}</p>
                              {item.details && (
                                <p className="text-sm text-gray-700 mt-2 p-2 bg-gray-50 rounded">
                                  {item.details}
                                </p>
                              )}
                            </div>
                          </div>
                        ))}
                      </div>
                    ) : (
                      <p className="text-sm text-muted-foreground text-center py-8">暂无时间线记录</p>
                    )}
                  </Card>
                </TabsContent>

                <TabsContent value="details" className="mt-4">
                  <div className="grid grid-cols-2 gap-4">
                    {selectedWarning.processingNotes && (
                      <Card className="p-4 col-span-2">
                        <label>处置过程记录</label>
                        <div className="field-value">{selectedWarning.processingNotes}</div>
                      </Card>
                    )}
                    {selectedWarning.resources && (
                      <Card className="p-4">
                        <label>调用资源</label>
                        <div className="field-value">{selectedWarning.resources}</div>
                      </Card>
                    )}
                    {selectedWarning.actualCost && (
                      <Card className="p-4">
                        <label>实际成本</label>
                        <div className="field-value">{selectedWarning.actualCost}</div>
                      </Card>
                    )}
                    <Card className="p-4">
                      <label>接收人员</label>
                      <div className="field-value">{selectedWarning.recipients.join(', ')}</div>
                    </Card>
                    <Card className="p-4">
                      <label>推送渠道</label>
                      <div className="field-value flex gap-1">
                        {selectedWarning.channels.map((ch, i) => (
                          <Badge key={i} variant="outline" className="text-xs">{ch}</Badge>
                        ))}
                      </div>
                    </Card>
                  </div>
                </TabsContent>
              </Tabs>

              <div className="flex gap-2 justify-end pt-4 border-t">
                <Button variant="outline" onClick={() => setShowWarningDetail(false)}>
                  关闭
                </Button>
              </div>
            </div>
          )}
        </DialogContent>
      </Dialog>

      {/* 推送记录详情对话框 */}
      <Dialog open={showRecordDetail} onOpenChange={setShowRecordDetail}>
        <DialogContent className="max-w-2xl">
          <DialogHeader>
            <DialogTitle>推送记录详情</DialogTitle>
            <DialogDescription>查看和处理预警推送记录</DialogDescription>
          </DialogHeader>
          {selectedRecord && (
            <div className="space-y-4">
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <label>地块名称</label>
                  <div className="field-value">{selectedRecord.fieldName}</div>
                </div>
                <div>
                  <label>风险类型</label>
                  <div className="field-value flex items-center gap-2">
                    {getRiskTypeIcon(selectedRecord.riskType)}
                    {selectedRecord.riskType}
                  </div>
                </div>
                <div>
                  <label>风险等级</label>
                  <div className="field-value">
                    <Badge className={getRiskLevelColor(selectedRecord.riskLevel)}>
                      {selectedRecord.riskLevel}
                    </Badge>
                  </div>
                </div>
                <div>
                  <label>推送时间</label>
                  <div className="field-value">{selectedRecord.warningTime}</div>
                </div>
                <div>
                  <label>责任人</label>
                  <div className="field-value">{selectedRecord.responsible}</div>
                </div>
                <div>
                  <label>当前状态</label>
                  <div className="field-value">
                    <div className={`inline-flex items-center gap-1 px-2 py-1 rounded-full ${getStatusColor(selectedRecord.status)}`}>
                      {getStatusIcon(selectedRecord.status)}
                      <span className="text-xs">{selectedRecord.status}</span>
                    </div>
                  </div>
                </div>
              </div>

              <div>
                <label>推送渠道</label>
                <div className="field-value flex gap-2">
                  {selectedRecord.channels.map((channel, i) => (
                    <Badge key={i} variant="outline">
                      {channel}
                    </Badge>
                  ))}
                </div>
              </div>

              {selectedRecord.viewTime && (
                <div>
                  <label>查看时间</label>
                  <div className="field-value">{selectedRecord.viewTime}</div>
                </div>
              )}

              <div>
                <label>处置方案</label>
                <Textarea
                  value={disposalPlan}
                  onChange={(e) => setDisposalPlan(e.target.value)}
                  placeholder="请输入处置方案..."
                  rows={4}
                  className="mt-2"
                />
              </div>

              {(selectedRecord.status === '处理中' || selectedRecord.status === '已完成') && (
                <div>
                  <label>处置结果</label>
                  <Textarea
                    value={disposalResult}
                    onChange={(e) => setDisposalResult(e.target.value)}
                    placeholder="请输入处置结果..."
                    rows={4}
                    className="mt-2"
                  />
                </div>
              )}

              {selectedRecord.completedTime && (
                <div>
                  <label>完成时间</label>
                  <div className="field-value">{selectedRecord.completedTime}</div>
                </div>
              )}

              <div className="flex gap-2 justify-end">
                <Button variant="outline" onClick={() => setShowRecordDetail(false)}>
                  取消
                </Button>
                {selectedRecord.status === '未查看' && (
                  <Button
                    className="bg-blue-600 hover:bg-blue-700"
                    onClick={() => {
                      handleUpdateRecordStatus(selectedRecord, '已查看');
                      setSelectedRecord({ ...selectedRecord, status: '已查看' });
                    }}
                  >
                    <Eye className="w-4 h-4 mr-2" />
                    标记已查看
                  </Button>
                )}
                {(selectedRecord.status === '未查看' || selectedRecord.status === '已查看') && (
                  <Button
                    className="bg-orange-600 hover:bg-orange-700"
                    onClick={() => {
                      const updatedRecords = warningRecords.map(r => {
                        if (r.id === selectedRecord.id) {
                          const updated = { ...r, status: '处理中' as DisposalStatus, disposalPlan };
                          if (!r.viewTime) {
                            updated.viewTime = new Date().toLocaleString('zh-CN');
                          }
                          return updated;
                        }
                        return r;
                      });
                      setWarningRecords(updatedRecords);
                      setSelectedRecord({ ...selectedRecord, status: '处理中', disposalPlan });
                      toast.success('状态已更新为：处理中');
                    }}
                  >
                    <Activity className="w-4 h-4 mr-2" />
                    开始处理
                  </Button>
                )}
                {selectedRecord.status === '处理中' && (
                  <Button
                    className="bg-green-600 hover:bg-green-700"
                    onClick={() => {
                      if (!disposalResult) {
                        toast.error('请填写处置结果');
                        return;
                      }
                      const updatedRecords = warningRecords.map(r => {
                        if (r.id === selectedRecord.id) {
                          return {
                            ...r,
                            disposalPlan,
                            disposalResult,
                            status: '已完成' as DisposalStatus,
                            completedTime: new Date().toLocaleString('zh-CN'),
                          };
                        }
                        return r;
                      });
                      setWarningRecords(updatedRecords);
                      setShowRecordDetail(false);
                      toast.success('处置已完成');
                    }}
                  >
                    <CheckCircle2 className="w-4 h-4 mr-2" />
                    完成处理
                  </Button>
                )}
                {selectedRecord.status !== '处理中' && selectedRecord.status !== '已完成' && (
                  <Button
                    className="bg-green-600 hover:bg-green-700"
                    onClick={handleSaveRecordDisposal}
                  >
                    <CheckCircle2 className="w-4 h-4 mr-2" />
                    保存
                  </Button>
                )}
              </div>
            </div>
          )}
        </DialogContent>
      </Dialog>

      {/* 推送规则编辑对话框 */}
      <Dialog open={showRuleDialog} onOpenChange={setShowRuleDialog}>
        <DialogContent className="max-w-2xl">
          <DialogHeader>
            <DialogTitle>{editingRule ? '编辑推送规则' : '新增推送规则'}</DialogTitle>
            <DialogDescription>配置预警推送规则参数</DialogDescription>
          </DialogHeader>
          <div className="space-y-4">
            <div>
              <label>规则名称</label>
              <input
                type="text"
                className="mt-2 w-full px-3 py-2 border rounded-md"
                placeholder="请输入规则名称"
                defaultValue={editingRule?.name || ''}
              />
            </div>

            <div className="grid grid-cols-2 gap-4">
              <div>
                <label>风险等级</label>
                <Select defaultValue={editingRule?.riskLevel || '中度风险'}>
                  <SelectTrigger className="mt-2">
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="高度风险">高度风险</SelectItem>
                    <SelectItem value="中度风险">中度风险</SelectItem>
                    <SelectItem value="轻度风险">轻度风险</SelectItem>
                  </SelectContent>
                </Select>
              </div>

              <div>
                <label>推送延迟</label>
                <Select defaultValue={editingRule?.pushDelay || '立即推送'}>
                  <SelectTrigger className="mt-2">
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="立即推送">立即推送</SelectItem>
                    <SelectItem value="5分钟内推送">5分钟内推送</SelectItem>
                    <SelectItem value="15分钟内推送">15分钟内推送</SelectItem>
                    <SelectItem value="30分钟内推送">30分钟内推送</SelectItem>
                  </SelectContent>
                </Select>
              </div>
            </div>

            <div>
              <label>触发条件</label>
              <Select defaultValue={editingRule?.condition || '风险评分 ≥ 60'}>
                <SelectTrigger className="mt-2">
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="风险评分 ≥ 80">风险评分 ≥ 80</SelectItem>
                  <SelectItem value="风险评分 ≥ 70">风险评分 ≥ 70</SelectItem>
                  <SelectItem value="风险评分 ≥ 60">风险评分 ≥ 60</SelectItem>
                  <SelectItem value="风险评分 ≥ 50">风险评分 ≥ 50</SelectItem>
                  <SelectItem value="风险评分 ≥ 40">风险评分 ≥ 40</SelectItem>
                  <SelectItem value="指数超阈值 50%以上">指数超阈值 50%以上</SelectItem>
                  <SelectItem value="指数超阈值 30%以上">指数超阈值 30%以上</SelectItem>
                  <SelectItem value="指数超阈值 20%以上">指数超阈值 20%以上</SelectItem>
                  <SelectItem value="指数超阈值 10%以上">指数超阈值 10%以上</SelectItem>
                </SelectContent>
              </Select>
            </div>

            <div>
              <label>推送对象</label>
              <div className="mt-2 space-y-2">
                <div className="flex items-center gap-2">
                  <Checkbox id="recipient-1" defaultChecked />
                  <label htmlFor="recipient-1" className="text-sm cursor-pointer">地块责任人</label>
                </div>
                <div className="flex items-center gap-2">
                  <Checkbox id="recipient-2" />
                  <label htmlFor="recipient-2" className="text-sm cursor-pointer">系统管理员</label>
                </div>
              </div>
            </div>

            <div>
              <label>推送渠道</label>
              <div className="mt-2 space-y-2">
                <div className="flex items-center gap-2">
                  <Checkbox id="channel-1" defaultChecked />
                  <label htmlFor="channel-1" className="text-sm cursor-pointer">消息中心</label>
                </div>
                <div className="flex items-center gap-2">
                  <Checkbox id="channel-2" defaultChecked />
                  <label htmlFor="channel-2" className="text-sm cursor-pointer">短信通知</label>
                </div>
                <div className="flex items-center gap-2">
                  <Checkbox id="channel-3" />
                  <label htmlFor="channel-3" className="text-sm cursor-pointer">邮件通知</label>
                </div>
              </div>
            </div>

            <div className="flex items-center gap-2">
              <Checkbox id="enabled" defaultChecked={editingRule?.enabled ?? true} />
              <label htmlFor="enabled" className="text-sm cursor-pointer">启用此规则</label>
            </div>

            <div className="flex gap-2 justify-end">
              <Button variant="outline" onClick={() => setShowRuleDialog(false)}>
                取消
              </Button>
              <Button
                className="bg-green-600 hover:bg-green-700"
                onClick={handleSaveRule}
              >
                <CheckCircle2 className="w-4 h-4 mr-2" />
                保存
              </Button>
            </div>
          </div>
        </DialogContent>
      </Dialog>
    </div>
  );
}
