import { useState } from 'react';
import { Card } from '../ui/card';
import { Button } from '../ui/button';
import { Badge } from '../ui/badge';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '../ui/select';
import { Input } from '../ui/input';
import { Label } from '../ui/label';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription, DialogFooter } from '../ui/dialog';
import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle } from '../ui/alert-dialog';
import { Progress } from '../ui/progress';
import { Slider } from '../ui/slider';
import {
  Droplets,
  Zap,
  Play,
  Pause,
  StopCircle,
  Clock,
  Gauge,
  Activity,
  TrendingUp,
  AlertCircle,
  CheckCircle,
  Settings,
  Calendar,
  Download,
  Eye,
  RefreshCw,
  Power,
  Waves,
  BarChart3,
  LineChart as LineChartIcon,
  Filter,
  MapPin,
  Leaf,
  Brain,
  User,
  Plus,
  Sparkles,
  Edit,
  Trash2,
  History,
} from 'lucide-react';
import { toast } from 'sonner@2.0.3';
import { IrrigationModelConfig } from './IrrigationModelConfig';
import {
  LineChart,
  Line,
  AreaChart,
  Area,
  XAxis,
  YAxis,
  CartesianGrid,
  Tooltip as RechartsTooltip,
  Legend,
  ResponsiveContainer,
} from 'recharts';

interface SmartIrrigationProps {
  activePath?: string;
}

type IrrigationModel = '经验灌溉模型' | 'AI决策灌溉模型';
type IrrigationStatus = '运行中' | '已停止' | '等待中' | '故障';
type ValveStatus = '开启' | '关闭' | '故障';

interface IrrigationTask {
  id: string;
  fieldId: string;
  fieldName: string;
  deviceId: string;
  deviceName: string;
  modelId: string;
  modelName: string;
  model: IrrigationModel;
  status: IrrigationStatus;
  startTime?: string;
  duration: number;
  waterPressure: number;
  flowRate: number;
  totalVolume: number;
  valveStatus: ValveStatus;
  pumpStatus: '运行' | '停止';
}

// 历史灌溉记录接口
interface IrrigationHistory {
  id: string;
  taskId: string;
  executionDate: string;
  startTime: string;
  endTime: string;
  duration: number; // 分钟
  waterVolume: number; // 升
  avgPressure: number; // bar
  avgFlowRate: number; // L/min
  status: '成功' | '异常' | '中断';
  remark?: string;
}

// 地块数据接口
interface FieldData {
  id: string;
  code: string;
  name: string;
  area: number;
  cropType?: string;
}

// 水肥机设备接口
interface DeviceData {
  id: string;
  deviceNo: string;
  deviceName: string;
  fieldId: string;
  status: '正常' | '停用';
}

// 灌溉模型接口
interface ModelData {
  id: string;
  modelNo: string;
  modelName: string;
  modelType: '经验灌溉模型' | 'AI决策模型';
  crop?: string;
  status: '启用' | '停用' | '测试中';
}

interface RealtimeData {
  time: string;
  pressure: number;
  flowRate: number;
  totalVolume: number;
}

// 水肥机实时状态接口
interface DeviceRealtimeStatus {
  deviceId: string;
  deviceName: string;
  fieldName: string;
  status: '运行中' | '待机' | '离线';
  currentPressure: number;
  currentFlowRate: number;
  accumulatedVolume2h: number; // 近2小时累计流量
}

// 多设备实时数据接口
interface MultiDeviceRealtimeData {
  time: string;
  [key: string]: number | string; // 支持动态设备ID
}

// 设备历史统计接口
interface DeviceHistorySummary {
  deviceId: string;
  deviceName: string;
  fieldName: string;
  avgPressure: number; // 平均水压
  avgFlowRate: number; // 平均流量
  totalVolume: number; // 累计用水量
  runningDays: number; // 运行天数
}

interface HistoryData {
  date: string;
  avgPressure: number;
  avgFlowRate: number;
  totalVolume: number;
}

export function SmartIrrigation({ activePath }: SmartIrrigationProps) {
  const [showStartDialog, setShowStartDialog] = useState(false);
  const [showManualDialog, setShowManualDialog] = useState(false);
  const [showModelConfigDialog, setShowModelConfigDialog] = useState(false);
  const [showDetailDialog, setShowDetailDialog] = useState(false);
  const [showEditDialog, setShowEditDialog] = useState(false);
  const [showDeleteDialog, setShowDeleteDialog] = useState(false);
  const [showManualHistoryDialog, setShowManualHistoryDialog] = useState(false);
  const [selectedTask, setSelectedTask] = useState<IrrigationTask | null>(null);
  const [selectedManualHistory, setSelectedManualHistory] = useState<IrrigationHistory | null>(null);
  const [selectedField, setSelectedField] = useState('');
  const [selectedDevice, setSelectedDevice] = useState('');
  const [selectedModel, setSelectedModel] = useState('');
  const [selectedManualDevice, setSelectedManualDevice] = useState('');
  const [manualPressure, setManualPressure] = useState([2.5]);
  const [manualDuration, setManualDuration] = useState(30);
  const [historyDateRange, setHistoryDateRange] = useState('7');
  const [customDateRange, setCustomDateRange] = useState(false);
  const [startDate, setStartDate] = useState('');
  const [endDate, setEndDate] = useState('');
  
  // 人工灌溉历史记录
  const [manualIrrigationHistory, setManualIrrigationHistory] = useState<IrrigationHistory[]>([]);

  // 地块数据（从地块管理获取）
  const [fieldsList] = useState<FieldData[]>([
    { id: 'field_001', code: 'F-001', name: '1号温室大棚', area: 2.5, cropType: '番茄' },
    { id: 'field_002', code: 'F-002', name: '2号露天田块', area: 3.0, cropType: '黄瓜' },
    { id: 'field_003', code: 'F-003', name: '3号田块', area: 5.0, cropType: '小麦' },
    { id: 'field_004', code: 'F-004', name: '4号智能温室', area: 4.2, cropType: '西红柿' },
  ]);

  // 水肥机设备数据
  const [devicesList] = useState<DeviceData[]>([
    { id: 'dev-001', deviceNo: 'WF-2024-001', deviceName: '1号大棚水肥一体机', fieldId: 'field_001', status: '正常' },
    { id: 'dev-002', deviceNo: 'WF-2024-002', deviceName: '2号田块智能水肥机', fieldId: 'field_002', status: '正常' },
    { id: 'dev-003', deviceNo: 'WF-2024-003', deviceName: '3号田块水肥设备', fieldId: 'field_003', status: '正常' },
    { id: 'dev-004', deviceNo: 'WF-2024-004', deviceName: '4号温室水肥系统', fieldId: 'field_004', status: '正常' },
    { id: 'dev-005', deviceNo: 'WF-2024-005', deviceName: '1号温室备用设备', fieldId: 'field_001', status: '正常' },
  ]);

  // 灌溉模型数据（从模型配置获取）
  const [modelsList] = useState<ModelData[]>([
    { id: 'model-1', modelNo: 'MODEL-2024-001', modelName: '番茄AI智能灌溉模型', modelType: 'AI决策模型', crop: '番茄', status: '启用' },
    { id: 'model-2', modelNo: 'MODEL-2024-002', modelName: '黄瓜经验灌溉模型', modelType: '经验灌溉模型', crop: '黄瓜', status: '启用' },
    { id: 'model-3', modelNo: 'MODEL-2024-003', modelName: '小麦AI灌溉决策', modelType: 'AI决策模型', crop: '小麦', status: '启用' },
    { id: 'model-4', modelNo: 'MODEL-2024-004', modelName: '西红柿经验模型', modelType: '经验灌溉模型', crop: '西红柿', status: '启用' },
  ]);

  // 根据选中的地块筛选设备
  const availableDevices = selectedField 
    ? devicesList.filter(dev => dev.fieldId === selectedField && dev.status === '正常')
    : [];

  // 智能灌溉任务
  const [autoTasks] = useState<IrrigationTask[]>([
    {
      id: 'task-1',
      fieldId: 'field_001',
      fieldName: '1号温室大棚',
      deviceId: 'dev-001',
      deviceName: '1号大棚水肥一体机',
      modelId: 'model-1',
      modelName: '番茄AI智能灌溉模型',
      model: 'AI决策灌溉模型',
      status: '运行中',
      startTime: '2024-10-15 14:30:00',
      duration: 45,
      waterPressure: 2.8,
      flowRate: 25.6,
      totalVolume: 580,
      valveStatus: '开启',
      pumpStatus: '运行',
    },
    {
      id: 'task-2',
      fieldId: 'field_002',
      fieldName: '2号露天田块',
      deviceId: 'dev-002',
      deviceName: '2号田块智能水肥机',
      modelId: 'model-2',
      modelName: '黄瓜经验灌溉模型',
      model: '经验灌溉模型',
      status: '已停止',
      startTime: '2024-10-15 10:00:00',
      duration: 60,
      waterPressure: 2.5,
      flowRate: 0,
      totalVolume: 1420,
      valveStatus: '关闭',
      pumpStatus: '停止',
    },
    {
      id: 'task-3',
      fieldId: 'field_003',
      fieldName: '3号田块',
      deviceId: 'dev-003',
      deviceName: '3号田块水肥设备',
      modelId: 'model-3',
      modelName: '小麦AI灌溉决策',
      model: 'AI决策灌溉模型',
      status: '等待中',
      duration: 0,
      waterPressure: 0,
      flowRate: 0,
      totalVolume: 0,
      valveStatus: '关闭',
      pumpStatus: '停止',
    },
  ]);

  // 实时监测数据（最近2小时）
  const [realtimeData] = useState<RealtimeData[]>(() => {
    const data: RealtimeData[] = [];
    const now = new Date();
    for (let i = 120; i >= 0; i -= 5) {
      const time = new Date(now.getTime() - i * 60 * 1000);
      data.push({
        time: `${time.getHours().toString().padStart(2, '0')}:${time.getMinutes().toString().padStart(2, '0')}`,
        pressure: 2.3 + Math.random() * 0.8,
        flowRate: 20 + Math.random() * 10,
        totalVolume: Math.floor(500 + (120 - i) * 8),
      });
    }
    return data;
  });

  // 水肥机实时状态数据
  const [deviceRealtimeStatus] = useState<DeviceRealtimeStatus[]>([
    {
      deviceId: 'dev-001',
      deviceName: '1号大棚水肥一体机',
      fieldName: '1号温室大棚',
      status: '运行中',
      currentPressure: 2.8,
      currentFlowRate: 25.6,
      accumulatedVolume2h: 2850,
    },
    {
      deviceId: 'dev-002',
      deviceName: '2号田块智能水肥机',
      fieldName: '2号露天田块',
      status: '待机',
      currentPressure: 0,
      currentFlowRate: 0,
      accumulatedVolume2h: 0,
    },
    {
      deviceId: 'dev-003',
      deviceName: '3号田块水肥设备',
      fieldName: '3号田块',
      status: '运行中',
      currentPressure: 3.2,
      currentFlowRate: 28.4,
      accumulatedVolume2h: 3180,
    },
    {
      deviceId: 'dev-004',
      deviceName: '4号温室水肥系统',
      fieldName: '4号智能温室',
      status: '待机',
      currentPressure: 0,
      currentFlowRate: 0,
      accumulatedVolume2h: 0,
    },
  ]);

  // 多设备实时监测数据（近2小时）
  const [multiDeviceRealtimeData] = useState<MultiDeviceRealtimeData[]>(() => {
    const data: MultiDeviceRealtimeData[] = [];
    const now = new Date();
    
    for (let i = 120; i >= 0; i -= 5) {
      const time = new Date(now.getTime() - i * 60 * 1000);
      const timeStr = `${time.getHours().toString().padStart(2, '0')}:${time.getMinutes().toString().padStart(2, '0')}`;
      
      const dataPoint: MultiDeviceRealtimeData = {
        time: timeStr,
        // 设备1 - 运行中
        'dev-001-pressure': 2.6 + Math.random() * 0.4,
        'dev-001-flowRate': 24 + Math.random() * 4,
        'dev-001-volume': Math.floor(500 + (120 - i) * 23),
        // 设备2 - 待机
        'dev-002-pressure': 0,
        'dev-002-flowRate': 0,
        'dev-002-volume': 0,
        // 设备3 - 运行中
        'dev-003-pressure': 3.0 + Math.random() * 0.4,
        'dev-003-flowRate': 26 + Math.random() * 5,
        'dev-003-volume': Math.floor(600 + (120 - i) * 26),
        // 设备4 - 待机
        'dev-004-pressure': 0,
        'dev-004-flowRate': 0,
        'dev-004-volume': 0,
      };
      
      data.push(dataPoint);
    }
    return data;
  });

  // 历史监测数据（最近7天）
  const [historyData] = useState<HistoryData[]>([
    { date: '10-09', avgPressure: 2.4, avgFlowRate: 24.5, totalVolume: 3250 },
    { date: '10-10', avgPressure: 2.6, avgFlowRate: 26.8, totalVolume: 3580 },
    { date: '10-11', avgPressure: 2.5, avgFlowRate: 25.2, totalVolume: 3420 },
    { date: '10-12', avgPressure: 2.7, avgFlowRate: 27.5, totalVolume: 3680 },
    { date: '10-13', avgPressure: 2.3, avgFlowRate: 23.8, totalVolume: 3150 },
    { date: '10-14', avgPressure: 2.8, avgFlowRate: 28.2, totalVolume: 3820 },
    { date: '10-15', avgPressure: 2.6, avgFlowRate: 26.5, totalVolume: 3550 },
  ]);

  // 设备历史统计数据（根据选择的时间范围）
  const [deviceHistorySummary] = useState<DeviceHistorySummary[]>([
    {
      deviceId: 'dev-001',
      deviceName: '1号大棚水肥一体机',
      fieldName: '1号温室大棚',
      avgPressure: 2.65,
      avgFlowRate: 25.8,
      totalVolume: 18500,
      runningDays: 7,
    },
    {
      deviceId: 'dev-002',
      deviceName: '2号田块智能水肥机',
      fieldName: '2号露天田块',
      avgPressure: 2.45,
      avgFlowRate: 23.2,
      totalVolume: 12800,
      runningDays: 5,
    },
    {
      deviceId: 'dev-003',
      deviceName: '3号田块水肥设备',
      fieldName: '3号田块',
      avgPressure: 3.15,
      avgFlowRate: 28.6,
      totalVolume: 22100,
      runningDays: 7,
    },
    {
      deviceId: 'dev-004',
      deviceName: '4号温室水肥系统',
      fieldName: '4号智能温室',
      avgPressure: 2.85,
      avgFlowRate: 26.4,
      totalVolume: 15600,
      runningDays: 6,
    },
  ]);

  // 多设备历史监测数据（根据时间范围生成）
  const generateMultiDeviceHistoryData = (days: number): MultiDeviceRealtimeData[] => {
    const data: MultiDeviceRealtimeData[] = [];
    const now = new Date();
    
    for (let i = days - 1; i >= 0; i--) {
      const date = new Date(now.getTime() - i * 24 * 60 * 60 * 1000);
      const dateStr = `${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}`;
      
      const dataPoint: MultiDeviceRealtimeData = {
        time: dateStr,
        // 设备1 - 每天都运行
        'dev-001-pressure': 2.5 + Math.random() * 0.4,
        'dev-001-flowRate': 24 + Math.random() * 4,
        'dev-001-volume': Math.floor(2400 + Math.random() * 400),
        // 设备2 - 部分时间运行
        'dev-002-pressure': i % 3 === 0 ? 0 : 2.3 + Math.random() * 0.4,
        'dev-002-flowRate': i % 3 === 0 ? 0 : 22 + Math.random() * 3,
        'dev-002-volume': i % 3 === 0 ? 0 : Math.floor(2000 + Math.random() * 300),
        // 设备3 - 每天都运行
        'dev-003-pressure': 3.0 + Math.random() * 0.4,
        'dev-003-flowRate': 27 + Math.random() * 4,
        'dev-003-volume': Math.floor(2800 + Math.random() * 500),
        // 设备4 - 部分时间运行
        'dev-004-pressure': i % 4 !== 0 ? 2.7 + Math.random() * 0.4 : 0,
        'dev-004-flowRate': i % 4 !== 0 ? 25 + Math.random() * 4 : 0,
        'dev-004-volume': i % 4 !== 0 ? Math.floor(2200 + Math.random() * 400) : 0,
      };
      
      data.push(dataPoint);
    }
    return data;
  };

  const [multiDeviceHistoryData, setMultiDeviceHistoryData] = useState<MultiDeviceRealtimeData[]>(
    () => generateMultiDeviceHistoryData(7)
  );

  // 生成任务的历史灌溉记录
  const getTaskHistory = (taskId: string): IrrigationHistory[] => {
    // 根据任务ID生成不同数量的历史记录（3-8条）
    const count = 3 + Math.floor(Math.random() * 6);
    const history: IrrigationHistory[] = [];
    const now = new Date();
    
    for (let i = 0; i < count; i++) {
      const daysAgo = i + 1;
      const executionDate = new Date(now.getTime() - daysAgo * 24 * 60 * 60 * 1000);
      const startHour = 6 + Math.floor(Math.random() * 6); // 6-12点开始
      const startMinute = Math.floor(Math.random() * 60);
      const duration = 30 + Math.floor(Math.random() * 60); // 30-90分钟
      
      const startTime = `${startHour.toString().padStart(2, '0')}:${startMinute.toString().padStart(2, '0')}`;
      const endHour = startHour + Math.floor(duration / 60);
      const endMinute = (startMinute + (duration % 60)) % 60;
      const endTime = `${endHour.toString().padStart(2, '0')}:${endMinute.toString().padStart(2, '0')}`;
      
      const waterVolume = Math.floor(duration * (20 + Math.random() * 15));
      const avgPressure = 2.2 + Math.random() * 0.8;
      const avgFlowRate = 20 + Math.random() * 15;
      
      // 95%成功率
      const status: '成功' | '异常' | '中断' = Math.random() > 0.95 ? (Math.random() > 0.5 ? '异常' : '中断') : '成功';
      
      history.push({
        id: `history-${taskId}-${i}`,
        taskId,
        executionDate: `${executionDate.getFullYear()}-${(executionDate.getMonth() + 1).toString().padStart(2, '0')}-${executionDate.getDate().toString().padStart(2, '0')}`,
        startTime,
        endTime,
        duration,
        waterVolume,
        avgPressure: Number(avgPressure.toFixed(1)),
        avgFlowRate: Number(avgFlowRate.toFixed(1)),
        status,
        remark: status === '成功' ? undefined : (status === '异常' ? '水压异常波动' : '人工中断'),
      });
    }
    
    return history.sort((a, b) => b.executionDate.localeCompare(a.executionDate));
  };

  const getStatusColor = (status: IrrigationStatus) => {
    switch (status) {
      case '运行中': return 'bg-success-muted text-success-muted-foreground';
      case '已停止': return 'bg-muted text-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 getValveStatusColor = (status: ValveStatus) => {
    switch (status) {
      case '开启': return 'bg-success-muted text-success-muted-foreground';
      case '关闭': return 'bg-muted text-muted-foreground';
      case '故障': return 'bg-error-muted text-error-muted-foreground';
      default: return 'bg-muted text-muted-foreground';
    }
  };

  const getHistoryStatusColor = (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-gray-100 text-gray-700';
    }
  };

  // 处理时间范围变化
  const handleDateRangeChange = (value: string) => {
    setHistoryDateRange(value);
    if (value === 'custom') {
      setCustomDateRange(true);
    } else {
      setCustomDateRange(false);
      const days = parseInt(value);
      setMultiDeviceHistoryData(generateMultiDeviceHistoryData(days));
    }
  };

  // 处理自定义时间查询
  const handleCustomDateQuery = () => {
    if (!startDate || !endDate) {
      toast.error('请选择开始和结束日期');
      return;
    }
    
    const start = new Date(startDate);
    const end = new Date(endDate);
    const daysDiff = Math.ceil((end.getTime() - start.getTime()) / (1000 * 60 * 60 * 24)) + 1;
    
    if (daysDiff <= 0) {
      toast.error('结束日期必须大于开始日期');
      return;
    }
    
    if (daysDiff > 90) {
      toast.error('查询时间范围不能超过90天');
      return;
    }
    
    setMultiDeviceHistoryData(generateMultiDeviceHistoryData(daysDiff));
    toast.success(`已加载${daysDiff}天的历史数据`);
  };

  const handleStartAutoIrrigation = () => {
    if (!selectedField) {
      toast.error('请选择地块');
      return;
    }
    if (!selectedDevice) {
      toast.error('请选择水肥机设备');
      return;
    }
    if (!selectedModel) {
      toast.error('请选择灌溉模型');
      return;
    }
    
    const field = fieldsList.find(f => f.id === selectedField);
    const device = devicesList.find(d => d.id === selectedDevice);
    const model = modelsList.find(m => m.id === selectedModel);
    
    toast.success(`已创建 ${field?.name} 的智能灌溉任务`);
    setShowStartDialog(false);
    // 重置选择
    setSelectedField('');
    setSelectedDevice('');
    setSelectedModel('');
  };

  const handleStartManualIrrigation = () => {
    if (!selectedField) {
      toast.error('请选择灌溉地块');
      return;
    }
    
    if (!selectedManualDevice) {
      toast.error('请选择水肥机设备');
      return;
    }
    
    // 检查阀门状态
    const valveOpen = Math.random() > 0.3; // 模拟检测
    if (!valveOpen) {
      toast.error('目标地块电动阀未开启，请先手动打开阀门！', {
        duration: 5000,
        action: {
          label: '了解',
          onClick: () => {},
        },
      });
      return;
    }

    // 获取地块和设备名称
    const field = fieldsList.find(f => f.id === selectedField);
    const device = devicesList.find(d => d.id === selectedManualDevice);

    // 生成历史灌溉记录
    const now = new Date();
    const startHour = now.getHours();
    const startMinute = now.getMinutes();
    const endMinute = (startMinute + manualDuration) % 60;
    const endHour = startHour + Math.floor((startMinute + manualDuration) / 60);
    
    const newHistory: IrrigationHistory = {
      id: `manual-${Date.now()}`,
      taskId: 'manual-irrigation',
      executionDate: `${now.getFullYear()}-${(now.getMonth() + 1).toString().padStart(2, '0')}-${now.getDate().toString().padStart(2, '0')}`,
      startTime: `${startHour.toString().padStart(2, '0')}:${startMinute.toString().padStart(2, '0')}`,
      endTime: `${endHour.toString().padStart(2, '0')}:${endMinute.toString().padStart(2, '0')}`,
      duration: manualDuration,
      waterVolume: Math.floor(manualPressure[0] * 10 * manualDuration),
      avgPressure: manualPressure[0],
      avgFlowRate: Number((manualPressure[0] * 10).toFixed(1)),
      status: '成功',
      remark: `地块: ${field?.name || selectedField}, 设备: ${device?.deviceName || '未知'}, 人工灌溉`,
    };

    // 添加到历史记录（最新的在前面）
    setManualIrrigationHistory(prev => [newHistory, ...prev]);

    toast.success(`已启动${field?.name || selectedField}的人工灌溉任务`);
    setShowManualDialog(false);
    
    // 重置参数
    setSelectedField('');
    setSelectedManualDevice('');
    setManualPressure([2.5]);
    setManualDuration(30);
  };

  const handleStopTask = (taskId: string, fieldName: string) => {
    toast.success(`已停止${fieldName}的灌溉任务`);
  };

  const handlePauseTask = (taskId: string, fieldName: string) => {
    toast.success(`已暂停${fieldName}的灌溉任务`);
  };

  // 查看详情
  const handleViewDetail = (task: IrrigationTask) => {
    setSelectedTask(task);
    setShowDetailDialog(true);
  };

  // 编辑任务
  const handleEditTask = (task: IrrigationTask) => {
    setSelectedTask(task);
    setSelectedField(task.fieldId);
    setSelectedDevice(task.deviceId);
    setSelectedModel(task.modelId);
    setShowEditDialog(true);
  };

  // 保存编辑
  const handleSaveEdit = () => {
    if (!selectedField || !selectedDevice || !selectedModel) {
      toast.error('请完整填写任务信息');
      return;
    }
    
    const field = fieldsList.find(f => f.id === selectedField);
    toast.success(`已更新 ${field?.name} 的智能灌溉任务`);
    setShowEditDialog(false);
    setSelectedTask(null);
    setSelectedField('');
    setSelectedDevice('');
    setSelectedModel('');
  };

  // 删除任务
  const handleDeleteTask = (task: IrrigationTask) => {
    setSelectedTask(task);
    setShowDeleteDialog(true);
  };

  // 确认删除
  const handleConfirmDelete = () => {
    if (selectedTask) {
      toast.success(`已删除 ${selectedTask.fieldName} 的灌溉任务`);
      setShowDeleteDialog(false);
      setSelectedTask(null);
    }
  };

  // 根据路径判断当前页面
  const getCurrentPage = () => {
    if (!activePath) return 'auto';
    if (activePath.includes('/smart/auto')) return 'auto';
    if (activePath.includes('/smart/manual')) return 'manual';
    if (activePath.includes('/smart/realtime')) return 'realtime';
    if (activePath.includes('/smart/history')) return 'history';
    return 'auto';
  };

  const currentPage = getCurrentPage();

  // 获取页面标题和描述
  const getPageInfo = () => {
    switch (currentPage) {
      case 'auto':
        return {
          title: '智能灌溉',
          description: '基于AI和经验模型的智能灌溉决策系统',
        };
      case 'manual':
        return {
          title: '人工灌溉',
          description: '手动控制灌溉参数，灵活应对特殊场景',
        };
      case 'realtime':
        return {
          title: '水肥机实时监测数据',
          description: '实时监控水肥机运行状态和关键参数',
        };
      case 'history':
        return {
          title: '水肥机历史监测数据',
          description: '查看和分析历史监测数据，优化灌溉策略',
        };
      default:
        return {
          title: '智能灌溉',
          description: '智能决策，精准灌溉，提升水效利用',
        };
    }
  };

  const pageInfo = getPageInfo();

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h2 className="text-green-800">{pageInfo.title}</h2>
          <p className="text-sm text-muted-foreground mt-1">
            {pageInfo.description}
          </p>
        </div>
        <div className="flex gap-2">
          {currentPage === 'auto' && (
            <Button 
              variant="outline" 
              className="border-green-300 text-green-700 hover:bg-green-50"
              onClick={() => setShowModelConfigDialog(true)}
            >
              <Brain className="w-4 h-4 mr-2" />
              模型配置
            </Button>
          )}
        </div>
      </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-green-600">
                {autoTasks.filter(t => t.status === '运行中').length}
              </p>
              <p className="text-xs text-green-600 mt-1">个灌溉任务</p>
            </div>
            <Activity 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-blue-600">
                {autoTasks.filter(t => t.status === '等待中').length}
              </p>
              <p className="text-xs text-blue-600 mt-1">个等待任务</p>
            </div>
            <Clock 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-purple-600">
                {autoTasks.reduce((sum, task) => sum + (task.totalVolume || 0), 0).toLocaleString()}
              </p>
              <p className="text-xs text-purple-600 mt-1">升</p>
            </div>
            <Droplets className="w-12 h-12 text-purple-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">
                {new Set(autoTasks.filter(t => t.status === '运行中').map(t => t.deviceId)).size}
              </p>
              <p className="text-xs text-orange-600 mt-1">台水肥机</p>
            </div>
            <Settings className="w-12 h-12 text-orange-600 opacity-50" />
          </div>
        </Card>
      </div>

      {/* 智能灌溉页面 */}
      {currentPage === 'auto' && (
        <div className="space-y-6">
          <div className="flex items-center justify-between">
            <div className="flex items-center gap-2">
              <Brain className="w-5 h-5 text-green-600" />
              <h3 className="text-green-700">智能灌溉任务</h3>
            </div>
            <Button className="bg-green-600 hover:bg-green-700" onClick={() => setShowStartDialog(true)}>
              <Plus className="w-4 h-4 mr-2" />
              新增智能灌溉
            </Button>
          </div>

          <Card className="p-6 bg-gradient-to-r from-blue-50 to-green-50 border-blue-200">
            <div className="flex items-start gap-3">
              <Sparkles className="w-6 h-6 text-blue-600 flex-shrink-0 mt-1" />
              <div>
                <h4 className="text-blue-900 mb-2">智能灌溉说明</h4>
                <p className="text-sm text-blue-800">
                  系统会根据选择的灌溉模型（AI决策模型或经验模型）、实时土壤湿度、天气预报、作物生长阶段等因素，
                  自动计算最优灌溉方案并执行。灌溉过程中会持续监控各项参数，确保灌溉效果。
                </p>
              </div>
            </div>
          </Card>

          <div className="space-y-4">
            {autoTasks.map((task) => (
              <Card key={task.id} className="p-6">
                <div className="flex items-center justify-between mb-4">
                  <div className="flex items-center gap-3">
                    <MapPin className="w-5 h-5 text-green-600" />
                    <div>
                      <h4>{task.fieldName}</h4>
                      <div className="flex items-center gap-2 mt-1 flex-wrap">
                        <Badge variant="outline" className="text-xs">
                          {task.model === 'AI决策灌溉模型' ? (
                            <><Brain className="w-3 h-3 mr-1" />{task.modelName}</>
                          ) : (
                            <><Leaf className="w-3 h-3 mr-1" />{task.modelName}</>
                          )}
                        </Badge>
                        <Badge variant="outline" className="text-xs bg-blue-50">
                          {task.deviceName}
                        </Badge>
                        <Badge className={getStatusColor(task.status)}>
                          {task.status}
                        </Badge>
                      </div>
                    </div>
                  </div>
                  <div className="flex gap-2">
                    <Button size="sm" variant="outline" onClick={() => handleViewDetail(task)}>
                      <Eye className="w-3 h-3 mr-1" />
                      详情
                    </Button>
                    {task.status !== '运行中' && (
                      <>
                        <Button size="sm" variant="outline" onClick={() => handleEditTask(task)}>
                          <Edit className="w-3 h-3 mr-1" />
                          编辑
                        </Button>
                        <Button 
                          size="sm" 
                          variant="outline" 
                          className="text-red-600 hover:text-red-700 hover:border-red-600"
                          onClick={() => handleDeleteTask(task)}
                        >
                          <Trash2 className="w-3 h-3 mr-1" />
                          删除
                        </Button>
                      </>
                    )}
                    {task.status === '运行中' && (
                      <>
                        <Button size="sm" variant="outline" onClick={() => handlePauseTask(task.id, task.fieldName)}>
                          <Pause className="w-3 h-3 mr-1" />
                          暂停
                        </Button>
                        <Button 
                          size="sm" 
                          variant="outline" 
                          className="text-red-600 hover:text-red-700"
                          onClick={() => handleStopTask(task.id, task.fieldName)}
                        >
                          <StopCircle className="w-3 h-3 mr-1" />
                          停止
                        </Button>
                      </>
                    )}
                    {task.status === '等待中' && (
                      <Button size="sm" className="bg-green-600 hover:bg-green-700">
                        <Play className="w-3 h-3 mr-1" />
                        启动
                      </Button>
                    )}
                  </div>
                </div>

                <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
                  <div className="flex items-center gap-2">
                    <Gauge className="w-4 h-4 text-blue-600" />
                    <div className="text-sm">
                      <div className="text-muted-foreground">水压</div>
                      <div className="font-medium">{task.waterPressure} bar</div>
                    </div>
                  </div>
                  <div className="flex items-center gap-2">
                    <Waves className="w-4 h-4 text-purple-600" />
                    <div className="text-sm">
                      <div className="text-muted-foreground">流量</div>
                      <div className="font-medium">{task.flowRate} L/min</div>
                    </div>
                  </div>
                  <div className="flex items-center gap-2">
                    <Droplets className="w-4 h-4 text-orange-600" />
                    <div className="text-sm">
                      <div className="text-muted-foreground">累计水量</div>
                      <div className="font-medium">{task.totalVolume} L</div>
                    </div>
                  </div>
                  <div className="flex items-center gap-2">
                    <Clock className="w-4 h-4 text-gray-600" />
                    <div className="text-sm">
                      <div className="text-muted-foreground">持续时间</div>
                      <div className="font-medium">{task.duration} 分钟</div>
                    </div>
                  </div>
                </div>

                {task.status === '运行中' && task.startTime && (
                  <div className="mt-4 pt-4 border-t">
                    <div className="flex items-center justify-between text-sm">
                      <div className="flex items-center gap-2 text-muted-foreground">
                        <Clock className="w-4 h-4" />
                        <span>开始时间: {task.startTime}</span>
                      </div>
                      <div className="flex items-center gap-4">
                        <div className="flex items-center gap-2">
                          <span className="text-muted-foreground">阀门:</span>
                          <Badge className={getValveStatusColor(task.valveStatus)} variant="outline">
                            {task.valveStatus}
                          </Badge>
                        </div>
                        <div className="flex items-center gap-2">
                          <span className="text-muted-foreground">水泵:</span>
                          <Badge 
                            className={task.pumpStatus === '运行' ? 'bg-green-100 text-green-700' : 'bg-gray-100 text-gray-700'}
                            variant="outline"
                          >
                            {task.pumpStatus}
                          </Badge>
                        </div>
                      </div>
                    </div>
                  </div>
                )}
              </Card>
            ))}
          </div>
        </div>
      )}

      {/* 人工灌溉页面 */}
      {currentPage === 'manual' && (
        <div className="space-y-6">
          <Card className="p-6 bg-gradient-to-r from-yellow-50 to-orange-50 border-yellow-200">
            <div className="flex items-start gap-3">
              <AlertCircle className="w-6 h-6 text-yellow-600 flex-shrink-0 mt-1" />
              <div>
                <h4 className="text-yellow-900 mb-2">人工灌溉注意事项</h4>
                <ul className="text-sm text-yellow-800 space-y-1">
                  <li>• 启动前系统会自动检测目标地块的电动阀状态</li>
                  <li>• 如电动阀未开启，需手动打开后方可启动灌溉</li>
                  <li>• 请根据实际情况合理设置灌溉参数</li>
                  <li>• 灌溉过程中可随时调整参数或停止</li>
                </ul>
              </div>
            </div>
          </Card>

          <Card className="p-6">
            <h3 className="mb-6 text-green-700">灌溉参数设置</h3>
            <div className="space-y-6">
              <div>
                <Label>选择地块</Label>
                <Select 
                  value={selectedField} 
                  onValueChange={(value) => {
                    setSelectedField(value);
                    // 切换地块时清空已选设备
                    setSelectedManualDevice('');
                  }}
                >
                  <SelectTrigger className="mt-2">
                    <SelectValue placeholder="请选择要灌溉的地块" />
                  </SelectTrigger>
                  <SelectContent>
                    {fieldsList.map(field => (
                      <SelectItem key={field.id} value={field.id}>
                        {field.name}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>

              {/* 水肥机设备选择 */}
              <div>
                <Label>选择水肥机设备</Label>
                <Select 
                  value={selectedManualDevice} 
                  onValueChange={setSelectedManualDevice}
                  disabled={!selectedField}
                >
                  <SelectTrigger className="mt-2">
                    <SelectValue placeholder={selectedField ? "请选择水肥机设备" : "请先选择地块"} />
                  </SelectTrigger>
                  <SelectContent>
                    {devicesList
                      .filter(device => device.fieldId === selectedField)
                      .map(device => (
                        <SelectItem key={device.id} value={device.id}>
                          <div className="flex items-center gap-2">
                            <span>{device.deviceName}</span>
                            <Badge variant="outline" className="text-xs">
                              {device.deviceNo}
                            </Badge>
                          </div>
                        </SelectItem>
                      ))}
                  </SelectContent>
                </Select>
                {selectedField && devicesList.filter(d => d.fieldId === selectedField).length === 0 && (
                  <p className="text-xs text-orange-600 mt-2">该地块暂无可用的水肥机设备</p>
                )}
              </div>

              <div>
                <Label>灌溉水压 (bar)</Label>
                <div className="mt-4">
                  <Slider
                    value={manualPressure}
                    onValueChange={setManualPressure}
                    min={1}
                    max={5}
                    step={0.1}
                    className="mb-2"
                  />
                  <div className="flex justify-between text-sm text-muted-foreground">
                    <span>1 bar</span>
                    <span className="font-medium text-foreground">{manualPressure[0].toFixed(1)} bar</span>
                    <span>5 bar</span>
                  </div>
                </div>
              </div>

              <div>
                <Label>灌溉时长 (分钟)</Label>
                <Input
                  type="number"
                  value={manualDuration}
                  onChange={(e) => setManualDuration(Number(e.target.value))}
                  min={1}
                  max={180}
                  className="mt-2"
                />
              </div>

              <div className="bg-blue-50 border border-blue-200 rounded-lg p-4">
                <h4 className="mb-3 text-blue-900">预计灌溉参数</h4>
                <div className="grid grid-cols-2 gap-4 text-sm">
                  <div className="flex justify-between">
                    <span className="text-blue-700">水压:</span>
                    <span className="font-medium text-blue-900">{manualPressure[0].toFixed(1)} bar</span>
                  </div>
                  <div className="flex justify-between">
                    <span className="text-blue-700">时长:</span>
                    <span className="font-medium text-blue-900">{manualDuration} 分钟</span>
                  </div>
                  <div className="flex justify-between">
                    <span className="text-blue-700">预计流量:</span>
                    <span className="font-medium text-blue-900">{(manualPressure[0] * 10).toFixed(1)} L/min</span>
                  </div>
                  <div className="flex justify-between">
                    <span className="text-blue-700">预计水量:</span>
                    <span className="font-medium text-blue-900">{Math.floor(manualPressure[0] * 10 * manualDuration)} L</span>
                  </div>
                </div>
              </div>

              <div className="flex gap-3">
                <Button
                  className="flex-1 bg-blue-600 hover:bg-blue-700"
                  onClick={() => setShowManualDialog(true)}
                  disabled={!selectedField || !selectedManualDevice}
                >
                  <Zap className="w-4 h-4 mr-2" />
                  启动灌溉
                </Button>
                <Button
                  variant="outline"
                  className="flex-1"
                  onClick={() => {
                    setSelectedField('');
                    setSelectedManualDevice('');
                    setManualPressure([2.5]);
                    setManualDuration(30);
                  }}
                >
                  重置参数
                </Button>
              </div>
            </div>
          </Card>

          {/* 人工灌溉历史记录 */}
          <Card className="p-6">
            <div className="flex items-center justify-between mb-6">
              <div className="flex items-center gap-2">
                <History className="w-5 h-5 text-green-600" />
                <h3 className="text-green-700">灌溉历史记录</h3>
              </div>
              <Badge variant="outline" className="text-sm">
                共 {manualIrrigationHistory.length} 次灌溉
              </Badge>
            </div>

            {manualIrrigationHistory.length === 0 ? (
              <div className="text-center py-12">
                <History className="w-16 h-16 text-gray-300 mx-auto mb-4" />
                <p className="text-muted-foreground mb-2">暂无灌溉历史记录</p>
                <p className="text-sm text-muted-foreground">启动人工灌溉后，历史记录将显示在这里</p>
              </div>
            ) : (
              <div className="space-y-3">
                {manualIrrigationHistory.map((record, index) => (
                  <Card 
                    key={record.id} 
                    className="p-4 hover:bg-gray-50 transition-colors cursor-pointer border-l-4 border-l-blue-500"
                    onClick={() => {
                      setSelectedManualHistory(record);
                      setShowManualHistoryDialog(true);
                    }}
                  >
                    <div className="flex items-center justify-between mb-3">
                      <div className="flex items-center gap-3">
                        <div className="w-10 h-10 rounded-full bg-blue-100 text-blue-700 flex items-center justify-center">
                          {index + 1}
                        </div>
                        <div>
                          <div className="flex items-center gap-2">
                            <Calendar className="w-4 h-4 text-gray-500" />
                            <span className="text-sm">{record.executionDate}</span>
                            <Badge className={getHistoryStatusColor(record.status)} variant="outline">
                              {record.status}
                            </Badge>
                          </div>
                          <div className="flex items-center gap-2 mt-1">
                            <Clock className="w-4 h-4 text-gray-500" />
                            <span className="text-xs text-muted-foreground">
                              {record.startTime} - {record.endTime}
                            </span>
                          </div>
                        </div>
                      </div>
                      <Button variant="ghost" size="sm" onClick={(e) => {
                        e.stopPropagation();
                        setSelectedManualHistory(record);
                        setShowManualHistoryDialog(true);
                      }}>
                        <Eye className="w-4 h-4 mr-2" />
                        查看详情
                      </Button>
                    </div>

                    <div className="grid grid-cols-4 gap-3">
                      <div className="bg-blue-50 rounded p-2">
                        <div className="text-xs text-muted-foreground mb-1">持续时间</div>
                        <div className="text-sm text-blue-700">{record.duration} 分钟</div>
                      </div>
                      <div className="bg-purple-50 rounded p-2">
                        <div className="text-xs text-muted-foreground mb-1">用水量</div>
                        <div className="text-sm text-purple-700">{record.waterVolume.toLocaleString()} L</div>
                      </div>
                      <div className="bg-orange-50 rounded p-2">
                        <div className="text-xs text-muted-foreground mb-1">平均水压</div>
                        <div className="text-sm text-orange-700">{record.avgPressure.toFixed(1)} bar</div>
                      </div>
                      <div className="bg-green-50 rounded p-2">
                        <div className="text-xs text-muted-foreground mb-1">平均流量</div>
                        <div className="text-sm text-green-700">{record.avgFlowRate} L/min</div>
                      </div>
                    </div>

                    {record.remark && (
                      <div className="mt-3 pt-3 border-t text-sm text-muted-foreground">
                        {record.remark}
                      </div>
                    )}
                  </Card>
                ))}
              </div>
            )}
          </Card>
        </div>
      )}

      {/* 实时监测数据页面 */}
      {currentPage === 'realtime' && (
        <div className="space-y-6">
          {/* 设备状态卡片 */}
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
            {deviceRealtimeStatus.map((device) => (
              <Card key={device.deviceId} className="p-4">
                <div className="space-y-3">
                  {/* 设备名称和状态 */}
                  <div className="flex items-start justify-between">
                    <div>
                      <h4 className="text-sm text-green-700 mb-1">{device.deviceName}</h4>
                      <p className="text-xs text-muted-foreground">{device.fieldName}</p>
                    </div>
                    <Badge 
                      className={
                        device.status === '运行中' 
                          ? 'bg-green-100 text-green-700' 
                          : device.status === '待机'
                          ? 'bg-blue-100 text-blue-700'
                          : 'bg-gray-100 text-gray-700'
                      }
                      variant="outline"
                    >
                      {device.status}
                    </Badge>
                  </div>

                  {/* 实时数据 */}
                  <div className="space-y-2">
                    <div className="flex items-center justify-between p-2 bg-blue-50 rounded">
                      <div className="flex items-center gap-2">
                        <Gauge className="w-4 h-4 text-blue-600" />
                        <span className="text-xs text-muted-foreground">水压</span>
                      </div>
                      <span className="text-blue-700">{device.currentPressure.toFixed(1)} bar</span>
                    </div>

                    <div className="flex items-center justify-between p-2 bg-purple-50 rounded">
                      <div className="flex items-center gap-2">
                        <Waves className="w-4 h-4 text-purple-600" />
                        <span className="text-xs text-muted-foreground">瞬时流量</span>
                      </div>
                      <span className="text-purple-700">{device.currentFlowRate.toFixed(1)} L/min</span>
                    </div>

                    <div className="flex items-center justify-between p-2 bg-orange-50 rounded">
                      <div className="flex items-center gap-2">
                        <Droplets className="w-4 h-4 text-orange-600" />
                        <span className="text-xs text-muted-foreground">近2h累计</span>
                      </div>
                      <span className="text-orange-700">{device.accumulatedVolume2h.toLocaleString()} L</span>
                    </div>
                  </div>
                </div>
              </Card>
            ))}
          </div>

          {/* 水压变化趋势 */}
          <Card className="p-6">
            <div className="flex items-center justify-between mb-6">
              <h3 className="text-green-700">水压变化趋势（最近2小时）</h3>
              <Badge variant="outline">实时更新中</Badge>
            </div>
            <ResponsiveContainer width="100%" height={350}>
              <LineChart data={multiDeviceRealtimeData}>
                <CartesianGrid strokeDasharray="3 3" />
                <XAxis dataKey="time" />
                <YAxis label={{ value: '水压 (bar)', angle: -90, position: 'insideLeft' }} />
                <RechartsTooltip />
                <Legend />
                <Line 
                  type="monotone" 
                  dataKey="dev-001-pressure" 
                  stroke="#3b82f6" 
                  strokeWidth={2}
                  name="1号大棚设备"
                  dot={false}
                />
                <Line 
                  type="monotone" 
                  dataKey="dev-002-pressure" 
                  stroke="#10b981" 
                  strokeWidth={2}
                  name="2号田块设备"
                  dot={false}
                />
                <Line 
                  type="monotone" 
                  dataKey="dev-003-pressure" 
                  stroke="#f59e0b" 
                  strokeWidth={2}
                  name="3号田块设备"
                  dot={false}
                />
                <Line 
                  type="monotone" 
                  dataKey="dev-004-pressure" 
                  stroke="#8b5cf6" 
                  strokeWidth={2}
                  name="4号温室设备"
                  dot={false}
                />
              </LineChart>
            </ResponsiveContainer>
          </Card>

          {/* 流量变化趋势 */}
          <Card className="p-6">
            <div className="flex items-center justify-between mb-6">
              <h3 className="text-green-700">流量变化趋势（最近2小时）</h3>
              <Badge variant="outline">实时更新中</Badge>
            </div>
            <ResponsiveContainer width="100%" height={350}>
              <LineChart data={multiDeviceRealtimeData}>
                <CartesianGrid strokeDasharray="3 3" />
                <XAxis dataKey="time" />
                <YAxis label={{ value: '流量 (L/min)', angle: -90, position: 'insideLeft' }} />
                <RechartsTooltip />
                <Legend />
                <Line 
                  type="monotone" 
                  dataKey="dev-001-flowRate" 
                  stroke="#3b82f6" 
                  strokeWidth={2}
                  name="1号大棚设备"
                  dot={false}
                />
                <Line 
                  type="monotone" 
                  dataKey="dev-002-flowRate" 
                  stroke="#10b981" 
                  strokeWidth={2}
                  name="2号田块设备"
                  dot={false}
                />
                <Line 
                  type="monotone" 
                  dataKey="dev-003-flowRate" 
                  stroke="#f59e0b" 
                  strokeWidth={2}
                  name="3号田块设备"
                  dot={false}
                />
                <Line 
                  type="monotone" 
                  dataKey="dev-004-flowRate" 
                  stroke="#8b5cf6" 
                  strokeWidth={2}
                  name="4号温室设备"
                  dot={false}
                />
              </LineChart>
            </ResponsiveContainer>
          </Card>

          {/* 累计水量趋势 */}
          <Card className="p-6">
            <div className="flex items-center justify-between mb-6">
              <h3 className="text-green-700">累计水量趋势（最近2小时）</h3>
              <Badge variant="outline">实时更新中</Badge>
            </div>
            <ResponsiveContainer width="100%" height={350}>
              <LineChart data={multiDeviceRealtimeData}>
                <CartesianGrid strokeDasharray="3 3" />
                <XAxis dataKey="time" />
                <YAxis label={{ value: '累计水量 (L)', angle: -90, position: 'insideLeft' }} />
                <RechartsTooltip />
                <Legend />
                <Line 
                  type="monotone" 
                  dataKey="dev-001-volume" 
                  stroke="#3b82f6" 
                  strokeWidth={2}
                  name="1号大棚设备"
                  dot={false}
                />
                <Line 
                  type="monotone" 
                  dataKey="dev-002-volume" 
                  stroke="#10b981" 
                  strokeWidth={2}
                  name="2号田块设备"
                  dot={false}
                />
                <Line 
                  type="monotone" 
                  dataKey="dev-003-volume" 
                  stroke="#f59e0b" 
                  strokeWidth={2}
                  name="3号田块设备"
                  dot={false}
                />
                <Line 
                  type="monotone" 
                  dataKey="dev-004-volume" 
                  stroke="#8b5cf6" 
                  strokeWidth={2}
                  name="4号温室设备"
                  dot={false}
                />
              </LineChart>
            </ResponsiveContainer>
          </Card>
        </div>
      )}

      {/* 历史监测数据页面 */}
      {currentPage === 'history' && (
        <div className="space-y-6">
          {/* 时间范围选择 */}
          <Card className="p-4">
            <div className="flex flex-wrap items-end gap-4">
              <div>
                <Label>时间范围</Label>
                <Select value={historyDateRange} onValueChange={handleDateRangeChange}>
                  <SelectTrigger className="w-48 mt-2">
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="7">最近7天</SelectItem>
                    <SelectItem value="15">最近15天</SelectItem>
                    <SelectItem value="30">最近30天</SelectItem>
                    <SelectItem value="custom">自定义时间段</SelectItem>
                  </SelectContent>
                </Select>
              </div>
              
              {customDateRange && (
                <>
                  <div>
                    <Label>开始日期</Label>
                    <Input
                      type="date"
                      value={startDate}
                      onChange={(e) => setStartDate(e.target.value)}
                      className="mt-2 w-48"
                    />
                  </div>
                  <div>
                    <Label>结束日期</Label>
                    <Input
                      type="date"
                      value={endDate}
                      onChange={(e) => setEndDate(e.target.value)}
                      className="mt-2 w-48"
                    />
                  </div>
                  <Button onClick={handleCustomDateQuery} className="bg-green-600 hover:bg-green-700">
                    查询
                  </Button>
                </>
              )}
              
              <div className="ml-auto text-sm text-muted-foreground">
                当前显示：{multiDeviceHistoryData.length} 天数据
              </div>
            </div>
          </Card>

          {/* 设备统计卡片 */}
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
            {deviceHistorySummary.map((device) => (
              <Card key={device.deviceId} className="p-4">
                <div className="space-y-3">
                  {/* 设备名称 */}
                  <div>
                    <h4 className="text-sm text-green-700 mb-1">{device.deviceName}</h4>
                    <p className="text-xs text-muted-foreground">{device.fieldName}</p>
                  </div>

                  {/* 统计数据 */}
                  <div className="space-y-2">
                    <div className="flex items-center justify-between p-2 bg-blue-50 rounded">
                      <div className="flex items-center gap-2">
                        <Gauge className="w-4 h-4 text-blue-600" />
                        <span className="text-xs text-muted-foreground">平均水压</span>
                      </div>
                      <span className="text-blue-700">{device.avgPressure.toFixed(2)} bar</span>
                    </div>

                    <div className="flex items-center justify-between p-2 bg-purple-50 rounded">
                      <div className="flex items-center gap-2">
                        <Waves className="w-4 h-4 text-purple-600" />
                        <span className="text-xs text-muted-foreground">平均流量</span>
                      </div>
                      <span className="text-purple-700">{device.avgFlowRate.toFixed(1)} L/min</span>
                    </div>

                    <div className="flex items-center justify-between p-2 bg-orange-50 rounded">
                      <div className="flex items-center gap-2">
                        <Droplets className="w-4 h-4 text-orange-600" />
                        <span className="text-xs text-muted-foreground">累计用水</span>
                      </div>
                      <span className="text-orange-700">{device.totalVolume.toLocaleString()} L</span>
                    </div>

                    <div className="flex items-center justify-between p-2 bg-green-50 rounded">
                      <div className="flex items-center gap-2">
                        <Calendar className="w-4 h-4 text-green-600" />
                        <span className="text-xs text-muted-foreground">运行天数</span>
                      </div>
                      <span className="text-green-700">{device.runningDays} 天</span>
                    </div>
                  </div>
                </div>
              </Card>
            ))}
          </div>

          {/* 水压变化趋势 */}
          <Card className="p-6">
            <div className="flex items-center justify-between mb-6">
              <h3 className="text-green-700">水压变化趋势</h3>
              <Badge variant="outline">历史数据</Badge>
            </div>
            <ResponsiveContainer width="100%" height={350}>
              <LineChart data={multiDeviceHistoryData}>
                <CartesianGrid strokeDasharray="3 3" />
                <XAxis dataKey="time" />
                <YAxis label={{ value: '平均水压 (bar)', angle: -90, position: 'insideLeft' }} />
                <RechartsTooltip />
                <Legend />
                <Line 
                  type="monotone" 
                  dataKey="dev-001-pressure" 
                  stroke="#3b82f6" 
                  strokeWidth={2}
                  name="1号大棚设备"
                  dot={false}
                />
                <Line 
                  type="monotone" 
                  dataKey="dev-002-pressure" 
                  stroke="#10b981" 
                  strokeWidth={2}
                  name="2号田块设备"
                  dot={false}
                />
                <Line 
                  type="monotone" 
                  dataKey="dev-003-pressure" 
                  stroke="#f59e0b" 
                  strokeWidth={2}
                  name="3号田块设备"
                  dot={false}
                />
                <Line 
                  type="monotone" 
                  dataKey="dev-004-pressure" 
                  stroke="#8b5cf6" 
                  strokeWidth={2}
                  name="4号温室设备"
                  dot={false}
                />
              </LineChart>
            </ResponsiveContainer>
          </Card>

          {/* 流量变化趋势 */}
          <Card className="p-6">
            <div className="flex items-center justify-between mb-6">
              <h3 className="text-green-700">流量变化趋势</h3>
              <Badge variant="outline">历史数据</Badge>
            </div>
            <ResponsiveContainer width="100%" height={350}>
              <LineChart data={multiDeviceHistoryData}>
                <CartesianGrid strokeDasharray="3 3" />
                <XAxis dataKey="time" />
                <YAxis label={{ value: '平均流量 (L/min)', angle: -90, position: 'insideLeft' }} />
                <RechartsTooltip />
                <Legend />
                <Line 
                  type="monotone" 
                  dataKey="dev-001-flowRate" 
                  stroke="#3b82f6" 
                  strokeWidth={2}
                  name="1号大棚设备"
                  dot={false}
                />
                <Line 
                  type="monotone" 
                  dataKey="dev-002-flowRate" 
                  stroke="#10b981" 
                  strokeWidth={2}
                  name="2号田块设备"
                  dot={false}
                />
                <Line 
                  type="monotone" 
                  dataKey="dev-003-flowRate" 
                  stroke="#f59e0b" 
                  strokeWidth={2}
                  name="3号田块设备"
                  dot={false}
                />
                <Line 
                  type="monotone" 
                  dataKey="dev-004-flowRate" 
                  stroke="#8b5cf6" 
                  strokeWidth={2}
                  name="4号温室设备"
                  dot={false}
                />
              </LineChart>
            </ResponsiveContainer>
          </Card>

          {/* 日累计水量趋势 */}
          <Card className="p-6">
            <div className="flex items-center justify-between mb-6">
              <h3 className="text-green-700">日累计水量趋势</h3>
              <Badge variant="outline">历史数据</Badge>
            </div>
            <ResponsiveContainer width="100%" height={350}>
              <LineChart data={multiDeviceHistoryData}>
                <CartesianGrid strokeDasharray="3 3" />
                <XAxis dataKey="time" />
                <YAxis label={{ value: '日累计水量 (L)', angle: -90, position: 'insideLeft' }} />
                <RechartsTooltip />
                <Legend />
                <Line 
                  type="monotone" 
                  dataKey="dev-001-volume" 
                  stroke="#3b82f6" 
                  strokeWidth={2}
                  name="1号大棚设备"
                  dot={false}
                />
                <Line 
                  type="monotone" 
                  dataKey="dev-002-volume" 
                  stroke="#10b981" 
                  strokeWidth={2}
                  name="2号田块设备"
                  dot={false}
                />
                <Line 
                  type="monotone" 
                  dataKey="dev-003-volume" 
                  stroke="#f59e0b" 
                  strokeWidth={2}
                  name="3号田块设备"
                  dot={false}
                />
                <Line 
                  type="monotone" 
                  dataKey="dev-004-volume" 
                  stroke="#8b5cf6" 
                  strokeWidth={2}
                  name="4号温室设备"
                  dot={false}
                />
              </LineChart>
            </ResponsiveContainer>
          </Card>
        </div>
      )}

      {/* 新增智能灌溉对话框 */}
      <Dialog open={showStartDialog} onOpenChange={setShowStartDialog}>
        <DialogContent className="max-w-2xl">
          <DialogHeader>
            <DialogTitle>新增智能灌溉任务</DialogTitle>
            <DialogDescription>
              按照步骤选择地块、水肥机设备和灌溉模型，创建智能灌溉任务
            </DialogDescription>
          </DialogHeader>

          <div className="space-y-5">
            {/* 步骤1：选择地块 */}
            <div>
              <div className="flex items-center gap-2 mb-2">
                <div className="w-6 h-6 rounded-full bg-green-600 text-white flex items-center justify-center text-sm">1</div>
                <Label className="text-base">选择地块</Label>
              </div>
              <Select value={selectedField} onValueChange={(value) => {
                setSelectedField(value);
                setSelectedDevice(''); // 重置设备选择
              }}>
                <SelectTrigger className="mt-2">
                  <SelectValue placeholder="请选择要灌溉的地块" />
                </SelectTrigger>
                <SelectContent>
                  {fieldsList.map((field) => (
                    <SelectItem key={field.id} value={field.id}>
                      <div className="flex items-center justify-between w-full">
                        <span>{field.name}</span>
                        <span className="text-xs text-muted-foreground ml-4">
                          {field.area}亩 · {field.cropType}
                        </span>
                      </div>
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>

            {/* 步骤2：选择水肥机设备 */}
            <div>
              <div className="flex items-center gap-2 mb-2">
                <div className={`w-6 h-6 rounded-full ${selectedField ? 'bg-green-600' : 'bg-gray-300'} text-white flex items-center justify-center text-sm`}>2</div>
                <Label className="text-base">选择水肥机设备</Label>
              </div>
              <Select 
                value={selectedDevice} 
                onValueChange={setSelectedDevice}
                disabled={!selectedField}
              >
                <SelectTrigger className="mt-2">
                  <SelectValue placeholder={selectedField ? "请选择水肥机设备" : "请先选择地块"} />
                </SelectTrigger>
                <SelectContent>
                  {availableDevices.length > 0 ? (
                    availableDevices.map((device) => (
                      <SelectItem key={device.id} value={device.id}>
                        <div className="flex items-center justify-between w-full">
                          <span>{device.deviceName}</span>
                          <span className="text-xs text-muted-foreground ml-4">
                            {device.deviceNo}
                          </span>
                        </div>
                      </SelectItem>
                    ))
                  ) : selectedField ? (
                    <SelectItem value="none" disabled>该地块暂无可用设备</SelectItem>
                  ) : null}
                </SelectContent>
              </Select>
              {selectedField && availableDevices.length > 0 && (
                <p className="text-xs text-muted-foreground mt-2">
                  找到 {availableDevices.length} 台可用设备
                </p>
              )}
            </div>

            {/* 步骤3：选择灌溉模型 */}
            <div>
              <div className="flex items-center gap-2 mb-2">
                <div className={`w-6 h-6 rounded-full ${selectedDevice ? 'bg-green-600' : 'bg-gray-300'} text-white flex items-center justify-center text-sm`}>3</div>
                <Label className="text-base">选择灌溉模型</Label>
              </div>
              <Select 
                value={selectedModel} 
                onValueChange={setSelectedModel}
                disabled={!selectedDevice}
              >
                <SelectTrigger className="mt-2">
                  <SelectValue placeholder={selectedDevice ? "请选择灌溉模型" : "请先选择设备"} />
                </SelectTrigger>
                <SelectContent>
                  {modelsList.filter(m => m.status === '启用').map((model) => (
                    <SelectItem key={model.id} value={model.id}>
                      <div className="flex items-center gap-2">
                        {model.modelType === 'AI决策模型' ? (
                          <Brain className="w-4 h-4 text-purple-600" />
                        ) : (
                          <Leaf className="w-4 h-4 text-orange-600" />
                        )}
                        <div className="flex flex-col">
                          <span>{model.modelName}</span>
                          <span className="text-xs text-muted-foreground">
                            {model.modelType} · {model.crop}
                          </span>
                        </div>
                      </div>
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
              {selectedModel && (() => {
                const model = modelsList.find(m => m.id === selectedModel);
                return model ? (
                  <div className="mt-3 p-3 bg-blue-50 border border-blue-200 rounded-lg">
                    <p className="text-xs text-blue-900">
                      {model.modelType === 'AI决策模型' 
                        ? '✨ AI模型将根据土壤湿度、天气预报、作物需水量自动计算最优灌溉方案'
                        : '📋 基于历史经验和专家规则，适用于常规灌溉场景'
                      }
                    </p>
                  </div>
                ) : null;
              })()}
            </div>

            {/* 任务摘要 */}
            {selectedField && selectedDevice && selectedModel && (
              <Card className="p-4 bg-green-50 border-green-200">
                <h4 className="mb-3 text-green-900">任务信息确认</h4>
                <div className="space-y-2 text-sm">
                  <div className="flex justify-between">
                    <span className="text-green-700">地块:</span>
                    <span className="text-green-900">{fieldsList.find(f => f.id === selectedField)?.name}</span>
                  </div>
                  <div className="flex justify-between">
                    <span className="text-green-700">设备:</span>
                    <span className="text-green-900">{devicesList.find(d => d.id === selectedDevice)?.deviceName}</span>
                  </div>
                  <div className="flex justify-between">
                    <span className="text-green-700">模型:</span>
                    <span className="text-green-900">{modelsList.find(m => m.id === selectedModel)?.modelName}</span>
                  </div>
                </div>
              </Card>
            )}
          </div>

          <DialogFooter>
            <Button variant="outline" onClick={() => {
              setShowStartDialog(false);
              setSelectedField('');
              setSelectedDevice('');
              setSelectedModel('');
            }}>
              取消
            </Button>
            <Button 
              className="bg-green-600 hover:bg-green-700" 
              onClick={handleStartAutoIrrigation}
              disabled={!selectedField || !selectedDevice || !selectedModel}
            >
              <Plus className="w-4 h-4 mr-2" />
              创建任务
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* 启动人工灌溉确认对话框 */}
      <Dialog open={showManualDialog} onOpenChange={setShowManualDialog}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>启动人工灌溉</DialogTitle>
            <DialogDescription>
              系统将检测阀门状态并启动灌溉
            </DialogDescription>
          </DialogHeader>

          <div className="space-y-4">
            <div className="bg-blue-50 border border-blue-200 rounded-lg p-4">
              <h4 className="mb-2">灌溉参数确认</h4>
              <div className="space-y-2 text-sm">
                <div className="flex justify-between">
                  <span className="text-muted-foreground">地块:</span>
                  <span>{fieldsList.find(f => f.id === selectedField)?.name || selectedField}</span>
                </div>
                <div className="flex justify-between">
                  <span className="text-muted-foreground">设备:</span>
                  <span>{devicesList.find(d => d.id === selectedManualDevice)?.deviceName || '未选择'}</span>
                </div>
                <div className="flex justify-between">
                  <span className="text-muted-foreground">水压:</span>
                  <span>{manualPressure[0]} bar</span>
                </div>
                <div className="flex justify-between">
                  <span className="text-muted-foreground">时长:</span>
                  <span>{manualDuration} 分钟</span>
                </div>
                <div className="flex justify-between">
                  <span className="text-muted-foreground">预计水量:</span>
                  <span>{Math.floor(manualPressure[0] * 10 * manualDuration)} L</span>
                </div>
              </div>
            </div>

            <div className="bg-yellow-50 border border-yellow-200 rounded-lg p-4">
              <div className="flex items-start gap-2">
                <AlertCircle className="w-5 h-5 text-yellow-600 flex-shrink-0 mt-0.5" />
                <div className="text-sm text-yellow-900">
                  <p>系统将在启动前自动检测目标地块电动阀状态</p>
                  <p className="text-xs mt-1">如阀门未开启，请根据提示手动打开后重试</p>
                </div>
              </div>
            </div>
          </div>

          <DialogFooter>
            <Button variant="outline" onClick={() => setShowManualDialog(false)}>
              取消
            </Button>
            <Button className="bg-blue-600 hover:bg-blue-700" onClick={handleStartManualIrrigation}>
              <Zap className="w-4 h-4 mr-2" />
              启动灌溉
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* 模型配置弹窗 */}
      <Dialog open={showModelConfigDialog} onOpenChange={setShowModelConfigDialog}>
        <DialogContent className="max-w-7xl max-h-[95vh] overflow-hidden p-0">
          <DialogHeader className="px-6 pt-6 pb-4 border-b">
            <DialogTitle className="flex items-center gap-2">
              <Brain className="w-5 h-5 text-green-600" />
              灌溉模型配置
            </DialogTitle>
            <DialogDescription>
              配置和管理智能灌溉模型，包括AI决策模型和经验灌溉模型
            </DialogDescription>
          </DialogHeader>
          <div className="overflow-y-auto" style={{ maxHeight: 'calc(95vh - 140px)' }}>
            <IrrigationModelConfig />
          </div>
        </DialogContent>
      </Dialog>

      {/* 查看详情对话框 */}
      <Dialog open={showDetailDialog} onOpenChange={setShowDetailDialog}>
        <DialogContent className="max-w-3xl">
          <DialogHeader>
            <DialogTitle className="flex items-center gap-2">
              <Eye className="w-5 h-5 text-green-600" />
              智能灌溉任务详情
            </DialogTitle>
            <DialogDescription>
              查看灌溉任务的完整信息和执行情况
            </DialogDescription>
          </DialogHeader>

          {selectedTask && (
            <div className="space-y-6">
              {/* 基本信息 */}
              <Card className="p-4">
                <h4 className="mb-3 text-green-700">基本信息</h4>
                <div className="grid grid-cols-2 gap-4">
                  <div>
                    <Label>任务编号</Label>
                    <p className="field-value">{selectedTask.id}</p>
                  </div>
                  <div>
                    <Label>任务状态</Label>
                    <div className="mt-2">
                      <Badge className={getStatusColor(selectedTask.status)}>
                        {selectedTask.status}
                      </Badge>
                    </div>
                  </div>
                  <div>
                    <Label>地块名称</Label>
                    <p className="field-value">{selectedTask.fieldName}</p>
                  </div>
                  <div>
                    <Label>水肥机设备</Label>
                    <p className="field-value">{selectedTask.deviceName}</p>
                  </div>
                  <div>
                    <Label>灌溉模型</Label>
                    <div className="mt-2">
                      <Badge variant="outline" className="text-xs">
                        {selectedTask.model === 'AI决策灌溉模型' ? (
                          <><Brain className="w-3 h-3 mr-1" />{selectedTask.modelName}</>
                        ) : (
                          <><Leaf className="w-3 h-3 mr-1" />{selectedTask.modelName}</>
                        )}
                      </Badge>
                    </div>
                  </div>
                  <div>
                    <Label>模型类型</Label>
                    <p className="field-value">{selectedTask.model}</p>
                  </div>
                </div>
              </Card>

              {/* 运行数据图表（仅运行中的任务） */}
              {selectedTask.status === '运行中' && (
                <Card className="p-4">
                  <h4 className="mb-3 text-green-700">实时监测数据</h4>
                  <div className="grid grid-cols-3 gap-4">
                    <div className="text-center p-4 bg-blue-50 rounded-lg">
                      <Gauge className="w-8 h-8 text-blue-600 mx-auto mb-2" />
                      <div className="text-2xl text-blue-600">{selectedTask.waterPressure}</div>
                      <div className="text-sm text-muted-foreground mt-1">水压 (bar)</div>
                    </div>
                    <div className="text-center p-4 bg-purple-50 rounded-lg">
                      <Waves className="w-8 h-8 text-purple-600 mx-auto mb-2" />
                      <div className="text-2xl text-purple-600">{selectedTask.flowRate}</div>
                      <div className="text-sm text-muted-foreground mt-1">流量 (L/min)</div>
                    </div>
                    <div className="text-center p-4 bg-orange-50 rounded-lg">
                      <Droplets className="w-8 h-8 text-orange-600 mx-auto mb-2" />
                      <div className="text-2xl text-orange-600">{selectedTask.totalVolume}</div>
                      <div className="text-sm text-muted-foreground mt-1">累计水量 (L)</div>
                    </div>
                  </div>
                </Card>
              )}

              {/* 历史灌溉记录 */}
              <Card className="p-4">
                <div className="flex items-center gap-2 mb-3">
                  <History className="w-5 h-5 text-green-600" />
                  <h4 className="text-green-700">历史灌溉记录</h4>
                  <Badge variant="outline" className="ml-auto">
                    共 {getTaskHistory(selectedTask.id).length} 次
                  </Badge>
                </div>
                
                <div className="space-y-3 max-h-80 overflow-y-auto">
                  {getTaskHistory(selectedTask.id).map((record, index) => (
                    <div 
                      key={record.id} 
                      className="border rounded-lg p-4 hover:bg-gray-50 transition-colors"
                    >
                      <div className="flex items-center justify-between mb-3">
                        <div className="flex items-center gap-2">
                          <div className="w-8 h-8 rounded-full bg-green-100 text-green-700 flex items-center justify-center text-sm">
                            {index + 1}
                          </div>
                          <div>
                            <div className="flex items-center gap-2">
                              <Calendar className="w-4 h-4 text-gray-500" />
                              <span className="text-sm">{record.executionDate}</span>
                            </div>
                            <div className="flex items-center gap-2 mt-1">
                              <Clock className="w-4 h-4 text-gray-500" />
                              <span className="text-xs text-muted-foreground">
                                {record.startTime} - {record.endTime}
                              </span>
                            </div>
                          </div>
                        </div>
                        <Badge className={getHistoryStatusColor(record.status)}>
                          {record.status}
                        </Badge>
                      </div>
                      
                      <div className="grid grid-cols-4 gap-3">
                        <div className="bg-blue-50 rounded p-2">
                          <div className="text-xs text-muted-foreground mb-1">持续时间</div>
                          <div className="text-sm text-blue-700">{record.duration} 分钟</div>
                        </div>
                        <div className="bg-purple-50 rounded p-2">
                          <div className="text-xs text-muted-foreground mb-1">用水量</div>
                          <div className="text-sm text-purple-700">{record.waterVolume.toLocaleString()} L</div>
                        </div>
                        <div className="bg-orange-50 rounded p-2">
                          <div className="text-xs text-muted-foreground mb-1">平均水压</div>
                          <div className="text-sm text-orange-700">{record.avgPressure} bar</div>
                        </div>
                        <div className="bg-green-50 rounded p-2">
                          <div className="text-xs text-muted-foreground mb-1">平均流量</div>
                          <div className="text-sm text-green-700">{record.avgFlowRate} L/min</div>
                        </div>
                      </div>
                      
                      {record.remark && (
                        <div className="mt-3 pt-3 border-t">
                          <div className="flex items-start gap-2">
                            <AlertCircle className="w-4 h-4 text-orange-600 flex-shrink-0 mt-0.5" />
                            <span className="text-xs text-orange-700">{record.remark}</span>
                          </div>
                        </div>
                      )}
                    </div>
                  ))}
                </div>

                {/* 统计汇总 */}
                <div className="mt-4 pt-4 border-t">
                  <div className="grid grid-cols-3 gap-4">
                    <div className="text-center">
                      <div className="text-xs text-muted-foreground mb-1">总灌溉次数</div>
                      <div className="text-lg text-green-600">
                        {getTaskHistory(selectedTask.id).length} 次
                      </div>
                    </div>
                    <div className="text-center">
                      <div className="text-xs text-muted-foreground mb-1">累计用水量</div>
                      <div className="text-lg text-blue-600">
                        {getTaskHistory(selectedTask.id)
                          .reduce((sum, r) => sum + r.waterVolume, 0)
                          .toLocaleString()} L
                      </div>
                    </div>
                    <div className="text-center">
                      <div className="text-xs text-muted-foreground mb-1">成功率</div>
                      <div className="text-lg text-purple-600">
                        {(
                          (getTaskHistory(selectedTask.id).filter(r => r.status === '成功').length / 
                          getTaskHistory(selectedTask.id).length) * 100
                        ).toFixed(0)}%
                      </div>
                    </div>
                  </div>
                </div>
              </Card>
            </div>
          )}

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

      {/* 编辑任务对��框 */}
      <Dialog open={showEditDialog} onOpenChange={setShowEditDialog}>
        <DialogContent className="max-w-2xl">
          <DialogHeader>
            <DialogTitle className="flex items-center gap-2">
              <Edit className="w-5 h-5 text-green-600" />
              编辑智能灌溉任务
            </DialogTitle>
            <DialogDescription>
              修改灌溉任务的地块、设备或模型配置
            </DialogDescription>
          </DialogHeader>

          <div className="space-y-5">
            {/* 步骤1：选择地块 */}
            <div>
              <div className="flex items-center gap-2 mb-2">
                <div className="w-6 h-6 rounded-full bg-green-600 text-white flex items-center justify-center text-sm">1</div>
                <Label className="text-base">选择地块</Label>
              </div>
              <Select value={selectedField} onValueChange={(value) => {
                setSelectedField(value);
                setSelectedDevice('');
              }}>
                <SelectTrigger className="mt-2">
                  <SelectValue placeholder="请选择要灌溉的地块" />
                </SelectTrigger>
                <SelectContent>
                  {fieldsList.map((field) => (
                    <SelectItem key={field.id} value={field.id}>
                      <div className="flex items-center justify-between w-full">
                        <span>{field.name}</span>
                        <span className="text-xs text-muted-foreground ml-4">
                          {field.area}亩 · {field.cropType}
                        </span>
                      </div>
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>

            {/* 步骤2：选择水肥机设备 */}
            <div>
              <div className="flex items-center gap-2 mb-2">
                <div className={`w-6 h-6 rounded-full ${selectedField ? 'bg-green-600' : 'bg-gray-300'} text-white flex items-center justify-center text-sm`}>2</div>
                <Label className="text-base">选择水肥机设备</Label>
              </div>
              <Select 
                value={selectedDevice} 
                onValueChange={setSelectedDevice}
                disabled={!selectedField}
              >
                <SelectTrigger className="mt-2">
                  <SelectValue placeholder={selectedField ? "请选择水肥机设备" : "请先选择地块"} />
                </SelectTrigger>
                <SelectContent>
                  {availableDevices.length > 0 ? (
                    availableDevices.map((device) => (
                      <SelectItem key={device.id} value={device.id}>
                        <div className="flex items-center justify-between w-full">
                          <span>{device.deviceName}</span>
                          <span className="text-xs text-muted-foreground ml-4">
                            {device.deviceNo}
                          </span>
                        </div>
                      </SelectItem>
                    ))
                  ) : selectedField ? (
                    <SelectItem value="none" disabled>该地块暂无可用设备</SelectItem>
                  ) : null}
                </SelectContent>
              </Select>
            </div>

            {/* 步骤3：选择灌溉模型 */}
            <div>
              <div className="flex items-center gap-2 mb-2">
                <div className={`w-6 h-6 rounded-full ${selectedDevice ? 'bg-green-600' : 'bg-gray-300'} text-white flex items-center justify-center text-sm`}>3</div>
                <Label className="text-base">选择灌溉模型</Label>
              </div>
              <Select 
                value={selectedModel} 
                onValueChange={setSelectedModel}
                disabled={!selectedDevice}
              >
                <SelectTrigger className="mt-2">
                  <SelectValue placeholder={selectedDevice ? "请选择灌溉模型" : "请先选择设备"} />
                </SelectTrigger>
                <SelectContent>
                  {modelsList.filter(m => m.status === '启用').map((model) => (
                    <SelectItem key={model.id} value={model.id}>
                      <div className="flex items-center gap-2">
                        {model.modelType === 'AI决策模型' ? (
                          <Brain className="w-4 h-4 text-purple-600" />
                        ) : (
                          <Leaf className="w-4 h-4 text-orange-600" />
                        )}
                        <div className="flex flex-col">
                          <span>{model.modelName}</span>
                          <span className="text-xs text-muted-foreground">
                            {model.modelType} · {model.crop}
                          </span>
                        </div>
                      </div>
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>
          </div>

          <DialogFooter>
            <Button variant="outline" onClick={() => {
              setShowEditDialog(false);
              setSelectedTask(null);
              setSelectedField('');
              setSelectedDevice('');
              setSelectedModel('');
            }}>
              取消
            </Button>
            <Button 
              className="bg-green-600 hover:bg-green-700" 
              onClick={handleSaveEdit}
              disabled={!selectedField || !selectedDevice || !selectedModel}
            >
              <CheckCircle className="w-4 h-4 mr-2" />
              保存修改
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* 删除确认对话框 */}
      <AlertDialog open={showDeleteDialog} onOpenChange={setShowDeleteDialog}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle className="flex items-center gap-2">
              <AlertCircle className="w-5 h-5 text-red-600" />
              确认删除灌溉任务
            </AlertDialogTitle>
            <AlertDialogDescription>
              您确定要删除该灌溉任务吗？此操作无法撤销。
            </AlertDialogDescription>
          </AlertDialogHeader>

          {selectedTask && (
            <Card className="p-4 bg-red-50 border-red-200">
              <div className="space-y-2 text-sm">
                <div className="flex justify-between">
                  <span className="text-muted-foreground">任务编号:</span>
                  <span>{selectedTask.id}</span>
                </div>
                <div className="flex justify-between">
                  <span className="text-muted-foreground">地块:</span>
                  <span>{selectedTask.fieldName}</span>
                </div>
                <div className="flex justify-between">
                  <span className="text-muted-foreground">设备:</span>
                  <span>{selectedTask.deviceName}</span>
                </div>
                <div className="flex justify-between">
                  <span className="text-muted-foreground">模型:</span>
                  <span>{selectedTask.modelName}</span>
                </div>
                <div className="flex justify-between">
                  <span className="text-muted-foreground">状态:</span>
                  <Badge className={getStatusColor(selectedTask.status)}>
                    {selectedTask.status}
                  </Badge>
                </div>
              </div>
            </Card>
          )}

          <AlertDialogFooter>
            <AlertDialogCancel onClick={() => {
              setShowDeleteDialog(false);
              setSelectedTask(null);
            }}>
              取消
            </AlertDialogCancel>
            <AlertDialogAction
              onClick={handleConfirmDelete}
              className="bg-red-600 hover:bg-red-700"
            >
              <Trash2 className="w-4 h-4 mr-2" />
              确认删除
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>

      {/* 人工灌溉历史详情对话框 */}
      <Dialog open={showManualHistoryDialog} onOpenChange={setShowManualHistoryDialog}>
        <DialogContent className="max-w-3xl max-h-[90vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle className="flex items-center gap-2">
              <History className="w-5 h-5 text-blue-600" />
              人工灌溉历史详情
            </DialogTitle>
            <DialogDescription>
              查看此次人工灌溉的详细信息
            </DialogDescription>
          </DialogHeader>

          {selectedManualHistory && (
            <div className="space-y-4">
              {/* 基本信息 */}
              <Card className="p-4 bg-gradient-to-r from-blue-50 to-green-50">
                <h4 className="mb-3 text-green-700">基本信息</h4>
                <div className="grid grid-cols-2 gap-4">
                  <div>
                    <Label>记录编号</Label>
                    <p className="field-value">{selectedManualHistory.id}</p>
                  </div>
                  <div>
                    <Label>执行状态</Label>
                    <div className="mt-2">
                      <Badge className={getHistoryStatusColor(selectedManualHistory.status)}>
                        {selectedManualHistory.status}
                      </Badge>
                    </div>
                  </div>
                  <div>
                    <Label>执行日期</Label>
                    <div className="flex items-center gap-2 mt-2">
                      <Calendar className="w-4 h-4 text-gray-500" />
                      <p className="field-value-inline">{selectedManualHistory.executionDate}</p>
                    </div>
                  </div>
                  <div>
                    <Label>执行时间</Label>
                    <div className="flex items-center gap-2 mt-2">
                      <Clock className="w-4 h-4 text-gray-500" />
                      <p className="field-value-inline">
                        {selectedManualHistory.startTime} - {selectedManualHistory.endTime}
                      </p>
                    </div>
                  </div>
                </div>
              </Card>

              {/* 灌溉参数 */}
              <Card className="p-4">
                <h4 className="mb-3 text-green-700">灌溉参数</h4>
                <div className="grid grid-cols-2 gap-4">
                  <div>
                    <Label>持续时间</Label>
                    <p className="field-value">{selectedManualHistory.duration} 分钟</p>
                  </div>
                  <div>
                    <Label>用水量</Label>
                    <p className="field-value">{selectedManualHistory.waterVolume.toLocaleString()} 升</p>
                  </div>
                  <div>
                    <Label>平均水压</Label>
                    <p className="field-value">{selectedManualHistory.avgPressure.toFixed(1)} bar</p>
                  </div>
                  <div>
                    <Label>平均流量</Label>
                    <p className="field-value">{selectedManualHistory.avgFlowRate} L/min</p>
                  </div>
                </div>
              </Card>

              {/* 关键指标 */}
              <Card className="p-4">
                <h4 className="mb-3 text-green-700">关键指标</h4>
                <div className="grid grid-cols-4 gap-3">
                  <div className="text-center p-4 bg-blue-50 rounded-lg">
                    <Clock className="w-8 h-8 text-blue-600 mx-auto mb-2" />
                    <div className="text-2xl text-blue-600">{selectedManualHistory.duration}</div>
                    <div className="text-sm text-muted-foreground mt-1">分钟</div>
                  </div>
                  <div className="text-center p-4 bg-purple-50 rounded-lg">
                    <Droplets className="w-8 h-8 text-purple-600 mx-auto mb-2" />
                    <div className="text-2xl text-purple-600">{selectedManualHistory.waterVolume.toLocaleString()}</div>
                    <div className="text-sm text-muted-foreground mt-1">用水量 (L)</div>
                  </div>
                  <div className="text-center p-4 bg-orange-50 rounded-lg">
                    <Gauge className="w-8 h-8 text-orange-600 mx-auto mb-2" />
                    <div className="text-2xl text-orange-600">{selectedManualHistory.avgPressure.toFixed(1)}</div>
                    <div className="text-sm text-muted-foreground mt-1">水压 (bar)</div>
                  </div>
                  <div className="text-center p-4 bg-green-50 rounded-lg">
                    <Waves className="w-8 h-8 text-green-600 mx-auto mb-2" />
                    <div className="text-2xl text-green-600">{selectedManualHistory.avgFlowRate}</div>
                    <div className="text-sm text-muted-foreground mt-1">流量 (L/min)</div>
                  </div>
                </div>
              </Card>

              {/* 备注信息 */}
              {selectedManualHistory.remark && (
                <Card className="p-4 bg-yellow-50 border-yellow-200">
                  <div className="flex items-start gap-2">
                    <AlertCircle className="w-5 h-5 text-yellow-600 flex-shrink-0 mt-0.5" />
                    <div>
                      <h4 className="text-yellow-900 mb-2">备注信息</h4>
                      <p className="text-sm text-yellow-800">{selectedManualHistory.remark}</p>
                    </div>
                  </div>
                </Card>
              )}

              {/* 操作记录 */}
              <Card className="p-4">
                <h4 className="mb-3 text-green-700">操作记录</h4>
                <div className="space-y-2 text-sm">
                  <div className="flex items-center gap-2 p-2 bg-gray-50 rounded">
                    <CheckCircle className="w-4 h-4 text-green-600" />
                    <span className="text-muted-foreground">灌溉任务创建</span>
                    <span className="ml-auto">{selectedManualHistory.startTime}</span>
                  </div>
                  <div className="flex items-center gap-2 p-2 bg-gray-50 rounded">
                    <CheckCircle className="w-4 h-4 text-green-600" />
                    <span className="text-muted-foreground">灌溉任务执行</span>
                    <span className="ml-auto">{selectedManualHistory.startTime}</span>
                  </div>
                  <div className="flex items-center gap-2 p-2 bg-gray-50 rounded">
                    <CheckCircle className="w-4 h-4 text-green-600" />
                    <span className="text-muted-foreground">灌溉任务完成</span>
                    <span className="ml-auto">{selectedManualHistory.endTime}</span>
                  </div>
                </div>
              </Card>
            </div>
          )}

          <DialogFooter>
            <Button variant="outline" onClick={() => {
              setShowManualHistoryDialog(false);
              setSelectedManualHistory(null);
            }}>
              关闭
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
}
