import { useState, useEffect } from 'react';
import { Card } from '../ui/card';
import { Button } from '../ui/button';
import { Badge } from '../ui/badge';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '../ui/tabs';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '../ui/select';
import { Input } from '../ui/input';
import { Progress } from '../ui/progress';
import { Switch } from '../ui/switch';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription, DialogFooter } from '../ui/dialog';
import {
  Zap,
  Activity,
  CheckCircle,
  XCircle,
  Clock,
  AlertTriangle,
  Settings,
  Eye,
  Send,
  RefreshCw,
  Download,
  Filter,
  Search,
  RotateCcw,
  ChevronRight,
  ChevronDown,
  Droplets,
  Wind,
  Sun,
  Thermometer,
  Power,
  Database,
  FileText,
  Info,
  MapPin,
  Leaf,
  Loader2,
  CheckCheck,
  ArrowRight,
  Target,
  Calendar,
  User,
  Wifi,
  WifiOff,
  PlayCircle,
  Radio,
} from 'lucide-react';
import { toast } from 'sonner@2.0.3';
import {
  LineChart,
  Line,
  BarChart,
  Bar,
  XAxis,
  YAxis,
  CartesianGrid,
  Tooltip as RechartsTooltip,
  Legend,
  ResponsiveContainer,
  PieChart,
  Pie,
  Cell,
} from 'recharts';

interface AIDeviceControlProps {
  activePath?: string;
}

// 设备类型
type DeviceType = 'irrigation' | 'curtain' | 'fan' | 'heater' | 'light' | 'pump';

// 指令状态
type CommandStatus = 'pending' | 'auto_executing' | 'sent' | 'executing' | 'completed' | 'failed' | 'timeout';

// 设备状态
type DeviceStatus = 'online' | 'offline' | 'busy' | 'error';

// 执行模式
type ExecutionMode = 'auto' | 'manual';

// 控制指令
interface ControlCommand {
  id: string;
  commandNo: string;
  decisionId: string;
  decisionTitle: string;
  deviceType: DeviceType;
  deviceId: string;
  deviceName: string;
  fieldName: string;
  
  // 执行模式
  executionMode: ExecutionMode; // 自动执行或手动执行
  
  // 指令内容
  action: string;
  parameters: {
    [key: string]: any;
  };
  
  // 状态追踪
  status: CommandStatus;
  createdAt: string;
  sentAt?: string;
  executedAt?: string;
  completedAt?: string;
  
  // 执行信息
  progress?: number;
  expectedDuration?: number;
  actualDuration?: number;
  
  // 反馈信息
  deviceFeedback?: {
    status: string;
    message: string;
    data?: any;
  };
  
  // 结果
  result?: {
    success: boolean;
    message: string;
    beforeValue?: any;
    afterValue?: any;
  };
  
  // IoT平台信息
  iotPlatform?: string;
  iotCommandId?: string;
  
  // 重试信息
  retryCount?: number;
  maxRetries?: number;
  
  // 执行日志
  logs: {
    timestamp: string;
    event: string;
    details: string;
  }[];
}

// 设备信息
interface DeviceInfo {
  id: string;
  name: string;
  type: DeviceType;
  status: DeviceStatus;
  fieldId: string;
  fieldName: string;
  location: string;
  
  // 设备参数
  model: string;
  manufacturer: string;
  installedAt: string;
  
  // 当前状态
  currentState: {
    [key: string]: any;
  };
  
  // 能力
  capabilities: string[];
  
  // 连接信息
  iotPlatform: string;
  deviceKey: string;
  lastOnlineAt: string;
  
  // 统计
  totalCommands: number;
  successCommands: number;
  failedCommands: number;
}

export function AIDeviceControl({ activePath }: AIDeviceControlProps) {
  const [selectedCommand, setSelectedCommand] = useState<ControlCommand | null>(null);
  const [showCommandDetail, setShowCommandDetail] = useState(false);
  const [showManualSendDialog, setShowManualSendDialog] = useState(false);
  const [manualSendingCommand, setManualSendingCommand] = useState<ControlCommand | null>(null);
  const [autoMode, setAutoMode] = useState(true);
  
  // 筛选条件
  const [filters, setFilters] = useState({
    deviceType: 'all',
    status: 'all',
    executionMode: 'all',
    deviceId: 'all',
    dateRange: 'all',
    searchText: '',
  });

  // 模拟控制指令数据
  const [commands, setCommands] = useState<ControlCommand[]>([
    {
      id: 'cmd_001',
      commandNo: 'CMD-20241023-001',
      decisionId: 'dec_001',
      decisionTitle: '1号大棚番茄开花期灌溉决策',
      deviceType: 'irrigation',
      deviceId: 'dev_irr_001',
      deviceName: '水肥机-01',
      fieldName: '1号大棚',
      executionMode: 'auto',
      action: '开启灌溉',
      parameters: {
        duration: 45,
        waterAmount: 120,
        startTime: '17:00',
        flowRate: 2.67,
      },
      status: 'completed',
      createdAt: '2025-10-23 16:55:00',
      sentAt: '2025-10-23 16:55:05',
      executedAt: '2025-10-23 17:00:00',
      completedAt: '2025-10-23 17:43:00',
      progress: 100,
      expectedDuration: 45,
      actualDuration: 43,
      iotPlatform: 'AliCloud IoT',
      iotCommandId: 'iot_cmd_2024102316550001',
      deviceFeedback: {
        status: 'success',
        message: '灌溉完成',
        data: {
          actualWater: 118,
          avgFlowRate: 2.74,
        },
      },
      result: {
        success: true,
        message: '灌溉任务成功完成，实际用水118升',
        beforeValue: { soilMoisture: 35 },
        afterValue: { soilMoisture: 63 },
      },
      logs: [
        { timestamp: '2024-10-23 16:55:00', event: '指令生成', details: '系统根据决策自动生成标准控制指令' },
        { timestamp: '2024-10-23 16:55:02', event: '参数校验', details: '校验指令参数：duration=45min, waterAmount=120L' },
        { timestamp: '2024-10-23 16:55:05', event: '指令下发', details: '通过AliCloud IoT平台下发至水肥机-01' },
        { timestamp: '2024-10-23 16:55:10', event: '设备响应', details: '设备确认接收指令，指令ID: iot_cmd_2024102316550001' },
        { timestamp: '2024-10-23 17:00:00', event: '开始执行', details: '开启灌溉阀门，开始供水' },
        { timestamp: '2024-10-23 17:20:00', event: '执行中', details: '已完成50%，用水60升，流量正常' },
        { timestamp: '2024-10-23 17:43:00', event: '执行完成', details: '灌溉完成，关闭阀门，实际用水118升' },
        { timestamp: '2024-10-23 17:43:05', event: '结果反馈', details: '土壤湿度从35%提升至63%，灌溉效果良好' },
      ],
    },
    {
      id: 'cmd_002',
      commandNo: 'CMD-20241023-002',
      decisionId: 'dec_002',
      decisionTitle: '2号大棚温度调控决策',
      deviceType: 'curtain',
      deviceId: 'dev_cur_002',
      deviceName: '卷帘机-02',
      fieldName: '2号大棚',
      executionMode: 'auto',
      action: '卷帘升起',
      parameters: {
        openPercentage: 50,
        speed: 'normal',
        reason: '降温通风',
      },
      status: 'auto_executing',
      createdAt: '2024-10-23 14:30:00',
      sentAt: '2024-10-23 14:30:08',
      executedAt: '2024-10-23 14:30:15',
      progress: 75,
      expectedDuration: 5,
      iotPlatform: 'AliCloud IoT',
      iotCommandId: 'iot_cmd_2024102314300001',
      deviceFeedback: {
        status: 'executing',
        message: '正在执行',
        data: {
          currentPosition: 37.5,
        },
      },
      logs: [
        { timestamp: '2024-10-23 14:30:00', event: '指令生成', details: '温度超过35℃阈值，自动生成降温指令' },
        { timestamp: '2024-10-23 14:30:05', event: '参数配置', details: '开启比例50%，速度normal' },
        { timestamp: '2024-10-23 14:30:08', event: '指令下发', details: '通过AliCloud IoT下发至卷帘机-02' },
        { timestamp: '2024-10-23 14:30:15', event: '开始执行', details: '卷帘开始上升，目标位置50%' },
        { timestamp: '2024-10-23 14:31:30', event: '执行中', details: '当前位置37.5%，预计还需60秒' },
      ],
    },
    {
      id: 'cmd_003',
      commandNo: 'CMD-20241023-003',
      decisionId: 'dec_003',
      decisionTitle: '3号大棚通风决策',
      deviceType: 'fan',
      deviceId: 'dev_fan_003',
      deviceName: '排风扇-03',
      fieldName: '3号大棚',
      executionMode: 'auto',
      action: '开启风扇',
      parameters: {
        speed: 3,
        duration: 30,
        mode: 'auto',
      },
      status: 'sent',
      createdAt: '2024-10-23 15:20:00',
      sentAt: '2024-10-23 15:20:03',
      progress: 0,
      expectedDuration: 30,
      iotPlatform: 'AliCloud IoT',
      iotCommandId: 'iot_cmd_2024102315200001',
      logs: [
        { timestamp: '2024-10-23 15:20:00', event: '指令生成', details: '湿度过高，系统自动生成通风指令' },
        { timestamp: '2024-10-23 15:20:03', event: '指令下发', details: '通过IoT平台下发，等待设备响应' },
      ],
    },
    {
      id: 'cmd_004',
      commandNo: 'CMD-20241023-004',
      decisionId: 'dec_004',
      decisionTitle: '4号大棚补光决策',
      deviceType: 'light',
      deviceId: 'dev_light_004',
      deviceName: '补光灯-04',
      fieldName: '4号大棚',
      executionMode: 'auto',
      action: '开启补光',
      parameters: {
        intensity: 70,
        duration: 180,
        spectrum: 'full',
      },
      status: 'failed',
      createdAt: '2024-10-23 06:00:00',
      sentAt: '2024-10-23 06:00:05',
      progress: 0,
      retryCount: 0,
      maxRetries: 3,
      iotPlatform: 'AliCloud IoT',
      iotCommandId: 'iot_cmd_2024102306000001',
      deviceFeedback: {
        status: 'error',
        message: '设备离线',
        data: {
          errorCode: 'DEVICE_OFFLINE',
          errorDetail: '设备未响应心跳包，可能断电或网络故障',
        },
      },
      result: {
        success: false,
        message: '自动执行失败：设备离线，无法建立连接',
      },
      logs: [
        { timestamp: '2024-10-23 06:00:00', event: '指令生成', details: '光照不足，系统自动生成补光指令' },
        { timestamp: '2024-10-23 06:00:05', event: '指令下发', details: '通过IoT平台下发至补光灯-04' },
        { timestamp: '2024-10-23 06:00:15', event: '超时等待', details: '设备未响应，等待30秒后重试' },
        { timestamp: '2024-10-23 06:00:45', event: '执行失败', details: '设备离线(DEVICE_OFFLINE)，自动执行失败' },
        { timestamp: '2024-10-23 06:00:46', event: '等待手动', details: '等待用户手动下发指令' },
      ],
    },
    {
      id: 'cmd_005',
      commandNo: 'CMD-20241023-005',
      decisionId: 'dec_005',
      decisionTitle: '5号大棚加温决策',
      deviceType: 'heater',
      deviceId: 'dev_heat_005',
      deviceName: '加温设备-05',
      fieldName: '5号大棚',
      executionMode: 'auto',
      action: '开启加温',
      parameters: {
        targetTemp: 18,
        duration: 120,
        power: 80,
      },
      status: 'failed',
      createdAt: '2024-10-23 18:00:00',
      sentAt: '2024-10-23 18:00:03',
      progress: 0,
      retryCount: 2,
      maxRetries: 3,
      iotPlatform: 'AliCloud IoT',
      iotCommandId: 'iot_cmd_2024102318000003',
      deviceFeedback: {
        status: 'error',
        message: '设备故障',
        data: {
          errorCode: 'DEVICE_ERROR',
          errorDetail: '温度传感器异常，无法启动加温',
        },
      },
      result: {
        success: false,
        message: '自动执行失败：设备温度传感器故障，已重试2次',
      },
      logs: [
        { timestamp: '2024-10-23 18:00:00', event: '指令生成', details: '温度低于阈值，系统自动生成加温指令' },
        { timestamp: '2024-10-23 18:00:03', event: '指令下发', details: '第1次尝试：通过IoT平台下发' },
        { timestamp: '2024-10-23 18:00:15', event: '第1次失败', details: '设备响应错误，准备重试' },
        { timestamp: '2024-10-23 18:01:00', event: '自动重试', details: '第2次尝试：重新下发指令' },
        { timestamp: '2024-10-23 18:01:15', event: '第2次失败', details: '温度传感器异常(DEVICE_ERROR)' },
        { timestamp: '2024-10-23 18:02:00', event: '自动重试', details: '第3次尝试：重新下发指令' },
        { timestamp: '2024-10-23 18:02:15', event: '第3次失败', details: '达到最大重试次数，自动执行失败' },
        { timestamp: '2024-10-23 18:02:16', event: '等待手动', details: '等待用户检查设备后手动下发' },
      ],
    },
    {
      id: 'cmd_006',
      commandNo: 'CMD-20241023-006',
      decisionId: 'dec_006',
      decisionTitle: '6号大棚灌溉决策',
      deviceType: 'irrigation',
      deviceId: 'dev_irr_006',
      deviceName: '水肥机-06',
      fieldName: '6号大棚',
      executionMode: 'manual',
      action: '开启灌溉',
      parameters: {
        duration: 30,
        waterAmount: 80,
        flowRate: 2.67,
      },
      status: 'pending',
      createdAt: '2024-10-23 16:30:00',
      progress: 0,
      expectedDuration: 30,
      logs: [
        { timestamp: '2024-10-23 16:30:00', event: '指令生成', details: '手动添加的决策，等待用户确认执行' },
      ],
    },
    // 成功案例 #2
    {
      id: 'cmd_007',
      commandNo: 'CMD-20241023-007',
      decisionId: 'dec_007',
      decisionTitle: '7号大棚通风降温决策',
      deviceType: 'fan',
      deviceId: 'dev_fan_007',
      deviceName: '排风扇-07',
      fieldName: '7号大棚',
      executionMode: 'auto',
      action: '开启排风',
      parameters: {
        speed: 5,
        duration: 60,
        mode: 'continuous',
        targetTemp: 26,
      },
      status: 'completed',
      createdAt: '2024-10-23 13:10:00',
      sentAt: '2024-10-23 13:10:02',
      executedAt: '2024-10-23 13:10:08',
      completedAt: '2024-10-23 14:10:08',
      progress: 100,
      expectedDuration: 60,
      actualDuration: 60,
      iotPlatform: 'Huawei Cloud IoT',
      iotCommandId: 'iot_cmd_2024102313100001',
      deviceFeedback: {
        status: 'success',
        message: '排风任务完成',
        data: {
          avgSpeed: 4.8,
          powerConsumption: 2.4,
        },
      },
      result: {
        success: true,
        message: '通风降温成功，温度已降至目标范围',
        beforeValue: { temperature: 32 },
        afterValue: { temperature: 26 },
      },
      logs: [
        { timestamp: '2024-10-23 13:10:00', event: '指令生成', details: '温度32℃超过阈值，自动生成通风指令' },
        { timestamp: '2024-10-23 13:10:02', event: '指令下发', details: '通过Huawei Cloud IoT下发至排风扇-07' },
        { timestamp: '2024-10-23 13:10:08', event: '开始执行', details: '排风扇启动，5档风速运行' },
        { timestamp: '2024-10-23 13:40:08', event: '执行中', details: '已运行30分钟，温度下降至28℃' },
        { timestamp: '2024-10-23 14:10:08', event: '执行完成', details: '运行60分钟，温度降至26℃，任务完成' },
        { timestamp: '2024-10-23 14:10:10', event: '结果反馈', details: '通风效果良好，耗电2.4kWh' },
      ],
    },
    // 失败案例 #2 - 通信超时
    {
      id: 'cmd_008',
      commandNo: 'CMD-20241023-008',
      decisionId: 'dec_008',
      decisionTitle: '8号大棚遮阳决策',
      deviceType: 'curtain',
      deviceId: 'dev_cur_008',
      deviceName: '遮阳网-08',
      fieldName: '8号大棚',
      executionMode: 'auto',
      action: '展开遮阳网',
      parameters: {
        openPercentage: 80,
        speed: 'slow',
        reason: '强光遮挡',
      },
      status: 'timeout',
      createdAt: '2024-10-23 11:00:00',
      sentAt: '2024-10-23 11:00:03',
      progress: 0,
      retryCount: 1,
      maxRetries: 3,
      iotPlatform: 'Tencent Cloud IoT',
      iotCommandId: 'iot_cmd_2024102311000001',
      deviceFeedback: {
        status: 'error',
        message: '指令超时',
        data: {
          errorCode: 'TIMEOUT',
          errorDetail: 'IoT平台响应超时，未收到设备确认',
          timeout: 120,
        },
      },
      result: {
        success: false,
        message: '自动执行超时：IoT平台未响应，可能网络异常',
      },
      logs: [
        { timestamp: '2024-10-23 11:00:00', event: '指令生成', details: '光照强度过高，系统自动生成遮阳指令' },
        { timestamp: '2024-10-23 11:00:03', event: '指令下发', details: '通过Tencent Cloud IoT下发' },
        { timestamp: '2024-10-23 11:00:33', event: '等待响应', details: '等待设备确认，30秒无响应' },
        { timestamp: '2024-10-23 11:01:03', event: '超时重试', details: '60秒超时，第1次重试' },
        { timestamp: '2024-10-23 11:02:03', event: '再次超时', details: '第2次超时，IoT平台可能网络异常' },
        { timestamp: '2024-10-23 11:02:04', event: '执行超时', details: '达到超时阈值(TIMEOUT)，自动执行失败' },
        { timestamp: '2024-10-23 11:02:05', event: '等待手动', details: '建议检查网络后手动重试' },
      ],
    },
    // 成功案例 #3
    {
      id: 'cmd_009',
      commandNo: 'CMD-20241023-009',
      decisionId: 'dec_009',
      decisionTitle: '9号大棚水肥一体化决策',
      deviceType: 'pump',
      deviceId: 'dev_pump_009',
      deviceName: '水肥泵-09',
      fieldName: '9号大棚',
      executionMode: 'auto',
      action: '启动水肥',
      parameters: {
        waterAmount: 150,
        fertilizerRatio: 0.3,
        duration: 50,
        flowRate: 3.0,
        npkRatio: '15-5-20',
      },
      status: 'completed',
      createdAt: '2024-10-23 08:00:00',
      sentAt: '2024-10-23 08:00:04',
      executedAt: '2024-10-23 08:00:10',
      completedAt: '2024-10-23 08:50:10',
      progress: 100,
      expectedDuration: 50,
      actualDuration: 50,
      iotPlatform: 'AliCloud IoT',
      iotCommandId: 'iot_cmd_2024102308000001',
      deviceFeedback: {
        status: 'success',
        message: '水肥施用完成',
        data: {
          actualWater: 148,
          actualFertilizer: 44.4,
          avgFlowRate: 2.96,
          npkDistribution: { n: 6.66, p: 2.22, k: 8.88 },
        },
      },
      result: {
        success: true,
        message: '水肥一体化施用成功，实际用水148L，肥料44.4L',
        beforeValue: { soilEC: 1.2, soilMoisture: 40 },
        afterValue: { soilEC: 1.8, soilMoisture: 68 },
      },
      logs: [
        { timestamp: '2024-10-23 08:00:00', event: '指令生成', details: '作物需肥期，系统自动生成水肥指令' },
        { timestamp: '2024-10-23 08:00:01', event: '参数校验', details: 'NPK比例15-5-20，浓度0.3%，符合规范' },
        { timestamp: '2024-10-23 08:00:04', event: '指令下发', details: '通过AliCloud IoT下发至水肥泵-09' },
        { timestamp: '2024-10-23 08:00:10', event: '开始执行', details: '启动水泵，开始混肥供水' },
        { timestamp: '2024-10-23 08:25:10', event: '执行中', details: '已完成50%，用水74L，肥料22.2L' },
        { timestamp: '2024-10-23 08:50:10', event: '执行完成', details: '水肥施用完成，关闭水泵' },
        { timestamp: '2024-10-23 08:50:15', event: '结果反馈', details: 'EC值从1.2提升至1.8，湿度从40%提升至68%' },
      ],
    },
    // 失败案例 #3 - 参数异常
    {
      id: 'cmd_010',
      commandNo: 'CMD-20241023-010',
      decisionId: 'dec_010',
      decisionTitle: '10号大棚加湿决策',
      deviceType: 'pump',
      deviceId: 'dev_mist_010',
      deviceName: '喷雾设备-10',
      fieldName: '10号大棚',
      executionMode: 'auto',
      action: '开启喷雾',
      parameters: {
        duration: 15,
        interval: 5,
        intensity: 85,
        targetHumidity: 75,
      },
      status: 'failed',
      createdAt: '2024-10-23 10:30:00',
      sentAt: '2024-10-23 10:30:03',
      executedAt: '2024-10-23 10:30:10',
      progress: 20,
      retryCount: 0,
      maxRetries: 3,
      iotPlatform: 'AliCloud IoT',
      iotCommandId: 'iot_cmd_2024102310300001',
      deviceFeedback: {
        status: 'error',
        message: '参数异常',
        data: {
          errorCode: 'PARAM_ERROR',
          errorDetail: '水压不足，实际压力0.8MPa低于要求的1.5MPa',
          requiredPressure: 1.5,
          actualPressure: 0.8,
        },
      },
      result: {
        success: false,
        message: '自动执行失败：设备水压不足，无法达到喷雾效果',
      },
      logs: [
        { timestamp: '2024-10-23 10:30:00', event: '指令生成', details: '湿度低于60%，系统自动生成加湿指令' },
        { timestamp: '2024-10-23 10:30:03', event: '指令下发', details: '通过IoT平台下发至喷雾设备-10' },
        { timestamp: '2024-10-23 10:30:10', event: '开始执行', details: '启动喷雾泵' },
        { timestamp: '2024-10-23 10:30:15', event: '参数异常', details: '检测到水压仅0.8MPa，低于1.5MPa要求' },
        { timestamp: '2024-10-23 10:30:20', event: '执行失败', details: '参数异常(PARAM_ERROR)，喷雾效果不达标，停止执行' },
        { timestamp: '2024-10-23 10:30:21', event: '等待手动', details: '建议检查水源压力后重新执行' },
      ],
    },
    // 执行中案例
    {
      id: 'cmd_011',
      commandNo: 'CMD-20241023-011',
      decisionId: 'dec_011',
      decisionTitle: '11号大棚CO2补充决策',
      deviceType: 'pump',
      deviceId: 'dev_co2_011',
      deviceName: 'CO2发生器-11',
      fieldName: '11号大棚',
      executionMode: 'auto',
      action: '补充CO2',
      parameters: {
        targetConcentration: 1000,
        duration: 120,
        flowRate: 5,
      },
      status: 'executing',
      createdAt: '2024-10-23 09:00:00',
      sentAt: '2024-10-23 09:00:02',
      executedAt: '2024-10-23 09:00:08',
      progress: 65,
      expectedDuration: 120,
      iotPlatform: 'Huawei Cloud IoT',
      iotCommandId: 'iot_cmd_2024102309000001',
      deviceFeedback: {
        status: 'executing',
        message: '正在补充CO2',
        data: {
          currentConcentration: 820,
          targetConcentration: 1000,
          flowRate: 4.8,
        },
      },
      logs: [
        { timestamp: '2024-10-23 09:00:00', event: '指令生成', details: 'CO2浓度400ppm，低于最佳值，自动生成补充指令' },
        { timestamp: '2024-10-23 09:00:02', event: '指令下发', details: '通过Huawei Cloud IoT下发' },
        { timestamp: '2024-10-23 09:00:08', event: '开始执行', details: '启动CO2发生器，目标浓度1000ppm' },
        { timestamp: '2024-10-23 09:40:00', event: '执行中', details: '已运行40分钟，当前浓度680ppm' },
        { timestamp: '2024-10-23 10:18:00', event: '执行中', details: '已运行78分钟(65%)，当前浓度820ppm，预计22分钟完成' },
      ],
    },
    // 失败案例 #4 - 设备繁忙
    {
      id: 'cmd_012',
      commandNo: 'CMD-20241023-012',
      decisionId: 'dec_012',
      decisionTitle: '12号大棚灌溉决策',
      deviceType: 'irrigation',
      deviceId: 'dev_irr_012',
      deviceName: '水肥机-12',
      fieldName: '12号大棚',
      executionMode: 'auto',
      action: '开启灌溉',
      parameters: {
        duration: 40,
        waterAmount: 100,
        flowRate: 2.5,
      },
      status: 'failed',
      createdAt: '2024-10-23 14:00:00',
      sentAt: '2024-10-23 14:00:03',
      progress: 0,
      retryCount: 1,
      maxRetries: 3,
      iotPlatform: 'Tencent Cloud IoT',
      iotCommandId: 'iot_cmd_2024102314000001',
      deviceFeedback: {
        status: 'error',
        message: '设备繁忙',
        data: {
          errorCode: 'DEVICE_BUSY',
          errorDetail: '设备正在执行其他任务，无法同时响应新指令',
          currentTask: 'MANUAL_IRRIGATION_TASK_001',
        },
      },
      result: {
        success: false,
        message: '自动执行失败：设备正在执行手动灌溉任务，无法响应',
      },
      logs: [
        { timestamp: '2024-10-23 14:00:00', event: '指令生成', details: '土壤湿度低，系统自动生成灌溉指令' },
        { timestamp: '2024-10-23 14:00:03', event: '指令下发', details: '通过Tencent Cloud IoT下发' },
        { timestamp: '2024-10-23 14:00:08', event: '设备响应', details: '设备返回繁忙状态(DEVICE_BUSY)' },
        { timestamp: '2024-10-23 14:01:00', event: '自动重试', details: '等待1分钟后第1次重试' },
        { timestamp: '2024-10-23 14:01:05', event: '仍然繁忙', details: '设备仍在执行手动任务MANUAL_IRRIGATION_TASK_001' },
        { timestamp: '2024-10-23 14:01:06', event: '执行失败', details: '设备繁忙，自动执行失败，建议等待当前任务完成后手动执行' },
      ],
    },
    // 成功案例 #4 - 手动执行成功
    {
      id: 'cmd_013',
      commandNo: 'CMD-20241023-013',
      decisionId: 'dec_013',
      decisionTitle: '13号大棚降温决策',
      deviceType: 'curtain',
      deviceId: 'dev_cur_013',
      deviceName: '卷帘机-13',
      fieldName: '13号大棚',
      executionMode: 'manual',
      action: '卷帘升起',
      parameters: {
        openPercentage: 100,
        speed: 'fast',
        reason: '高温通风',
      },
      status: 'completed',
      createdAt: '2024-10-23 12:00:00',
      sentAt: '2024-10-23 12:05:00',
      executedAt: '2024-10-23 12:05:05',
      completedAt: '2024-10-23 12:08:05',
      progress: 100,
      expectedDuration: 3,
      actualDuration: 3,
      iotPlatform: 'AliCloud IoT',
      iotCommandId: 'iot_cmd_2024102312050001',
      deviceFeedback: {
        status: 'success',
        message: '卷帘升起完成',
        data: {
          currentPosition: 100,
          motorTemp: 45,
        },
      },
      result: {
        success: true,
        message: '手动执行成功，卷帘已完全升起',
        beforeValue: { position: 0, temperature: 34 },
        afterValue: { position: 100, temperature: 30 },
      },
      logs: [
        { timestamp: '2024-10-23 12:00:00', event: '指令生成', details: '用户手动添加降温决策' },
        { timestamp: '2024-10-23 12:05:00', event: '用户确认', details: '用户确认执行，开始下发指令' },
        { timestamp: '2024-10-23 12:05:00', event: '指令下发', details: '通过AliCloud IoT下发至卷帘机-13' },
        { timestamp: '2024-10-23 12:05:05', event: '开始执行', details: '卷帘开始上升，快速模式' },
        { timestamp: '2024-10-23 12:08:05', event: '执行完成', details: '卷帘完全升起(100%)，温度开始下降' },
        { timestamp: '2024-10-23 12:08:10', event: '结果反馈', details: '手动执行成功，温度从34℃降至30℃' },
      ],
    },
    // 成功案例 #5 - 夜间加热成功
    {
      id: 'cmd_014',
      commandNo: 'CMD-20241023-014',
      decisionId: 'dec_014',
      decisionTitle: '14号大棚夜间保温决策',
      deviceType: 'heater',
      deviceId: 'dev_heat_014',
      deviceName: '加温设备-14',
      fieldName: '14号大棚',
      executionMode: 'auto',
      action: '开启加温',
      parameters: {
        targetTemp: 16,
        duration: 180,
        power: 60,
        mode: 'eco',
      },
      status: 'completed',
      createdAt: '2024-10-23 22:00:00',
      sentAt: '2024-10-23 22:00:03',
      executedAt: '2024-10-23 22:00:10',
      completedAt: '2024-10-24 01:00:10',
      progress: 100,
      expectedDuration: 180,
      actualDuration: 180,
      iotPlatform: 'Tencent Cloud IoT',
      iotCommandId: 'iot_cmd_2024102322000001',
      deviceFeedback: {
        status: 'success',
        message: '加温任务完成',
        data: {
          avgTemp: 16.2,
          powerConsumption: 10.8,
          efficiency: 0.95,
        },
      },
      result: {
        success: true,
        message: '夜间保温成功，温度稳定在16℃±1℃，耗电10.8kWh',
        beforeValue: { temperature: 12 },
        afterValue: { temperature: 16.5 },
      },
      logs: [
        { timestamp: '2024-10-23 22:00:00', event: '指令生成', details: '夜间温度降至12℃，系统自动生成保温指令' },
        { timestamp: '2024-10-23 22:00:03', event: '指令下发', details: '通过Tencent Cloud IoT下发至加温设备-14' },
        { timestamp: '2024-10-23 22:00:10', event: '开始执行', details: '启动加温设备，节能模式，功率60%' },
        { timestamp: '2024-10-23 23:00:10', event: '执行中', details: '运行1小时，温度15.2℃，耗电3.6kWh' },
        { timestamp: '2024-10-24 00:00:10', event: '执行中', details: '运行2小时，温度16.0℃，耗电7.2kWh' },
        { timestamp: '2024-10-24 01:00:10', event: '执行完成', details: '运行3小时，温度稳定在16.5℃，总耗电10.8kWh' },
        { timestamp: '2024-10-24 01:00:15', event: '结果反馈', details: '保温效果良好，能效比0.95，运行正常' },
      ],
    },
    // 失败案例 #5 - 网络连接失败
    {
      id: 'cmd_015',
      commandNo: 'CMD-20241023-015',
      decisionId: 'dec_015',
      decisionTitle: '15号大棚紧急降温决策',
      deviceType: 'fan',
      deviceId: 'dev_fan_015',
      deviceName: '排风扇-15',
      fieldName: '15号大棚',
      executionMode: 'auto',
      action: '开启排风',
      parameters: {
        speed: 5,
        duration: 45,
        mode: 'emergency',
      },
      status: 'failed',
      createdAt: '2024-10-23 15:30:00',
      sentAt: '2024-10-23 15:30:02',
      progress: 0,
      retryCount: 3,
      maxRetries: 3,
      iotPlatform: 'AliCloud IoT',
      iotCommandId: 'iot_cmd_2024102315300001',
      deviceFeedback: {
        status: 'error',
        message: '网络连接失败',
        data: {
          errorCode: 'NETWORK_ERROR',
          errorDetail: '无法连接到IoT平台，网络连接中断',
          lastPing: '2024-10-23 15:15:00',
        },
      },
      result: {
        success: false,
        message: '自动执行失败：网络连接中断，无法下发指令至IoT平台',
      },
      logs: [
        { timestamp: '2024-10-23 15:30:00', event: '指令生成', details: '温度38℃，系统自动生成紧急降温指令' },
        { timestamp: '2024-10-23 15:30:02', event: '下发失败', details: '网络连接失败，无法连接IoT平台' },
        { timestamp: '2024-10-23 15:30:30', event: '第1次重试', details: '尝试重新连接，失败' },
        { timestamp: '2024-10-23 15:31:00', event: '第2次重试', details: '尝试重新连接，失败' },
        { timestamp: '2024-10-23 15:31:30', event: '第3次重试', details: '尝试重新连接，失败' },
        { timestamp: '2024-10-23 15:31:31', event: '执行失败', details: '网络连接异常(NETWORK_ERROR)，达到最大重试次数' },
        { timestamp: '2024-10-23 15:31:32', event: '等待手动', details: '建议检查网络后手动执行或联系技术支持' },
      ],
    },
    // 成功案例 #6 - 精确控制成功
    {
      id: 'cmd_016',
      commandNo: 'CMD-20241023-016',
      decisionId: 'dec_016',
      decisionTitle: '16号大棚精准遮阳决策',
      deviceType: 'curtain',
      deviceId: 'dev_cur_016',
      deviceName: '遮阳网-16',
      fieldName: '16号大棚',
      executionMode: 'auto',
      action: '调节遮阳',
      parameters: {
        openPercentage: 35,
        speed: 'slow',
        reason: '光照优化',
        lightIntensity: 45000,
      },
      status: 'completed',
      createdAt: '2024-10-23 10:15:00',
      sentAt: '2024-10-23 10:15:02',
      executedAt: '2024-10-23 10:15:08',
      completedAt: '2024-10-23 10:19:08',
      progress: 100,
      expectedDuration: 4,
      actualDuration: 4,
      iotPlatform: 'Huawei Cloud IoT',
      iotCommandId: 'iot_cmd_2024102310150001',
      deviceFeedback: {
        status: 'success',
        message: '遮阳调节完成',
        data: {
          currentPosition: 35,
          lightReduction: 0.42,
          motorCycles: 280,
        },
      },
      result: {
        success: true,
        message: '精准遮阳成功，光照强度从75000lux降至43500lux',
        beforeValue: { lightIntensity: 75000, position: 0 },
        afterValue: { lightIntensity: 43500, position: 35 },
      },
      logs: [
        { timestamp: '2024-10-23 10:15:00', event: '指令生成', details: '光照75000lux，超过作物最佳值，自动生成遮阳指令' },
        { timestamp: '2024-10-23 10:15:02', event: '指令下发', details: '通过Huawei Cloud IoT下发至遮阳网-16' },
        { timestamp: '2024-10-23 10:15:08', event: '开始执行', details: '遮阳网开始展开，目标位置35%，慢速模式' },
        { timestamp: '2024-10-23 10:17:08', event: '执行中', details: '已展开20%，光照降至60000lux' },
        { timestamp: '2024-10-23 10:19:08', event: '执行完成', details: '遮阳网展开至35%，光照降至43500lux，达到预期' },
        { timestamp: '2024-10-23 10:19:12', event: '结果反馈', details: '光照优化成功，减光率42%，电机运行280个周期' },
      ],
    },
    // 失败案例 #6 - 指令格式错误
    {
      id: 'cmd_017',
      commandNo: 'CMD-20241023-017',
      decisionId: 'dec_017',
      decisionTitle: '17号大棚智能补光决策',
      deviceType: 'light',
      deviceId: 'dev_light_017',
      deviceName: '补光灯-17',
      fieldName: '17号大棚',
      executionMode: 'auto',
      action: '开启补光',
      parameters: {
        intensity: 85,
        duration: 240,
        spectrum: 'red-blue',
        timing: 'sunrise',
      },
      status: 'failed',
      createdAt: '2024-10-23 05:30:00',
      sentAt: '2024-10-23 05:30:02',
      progress: 0,
      retryCount: 0,
      maxRetries: 3,
      iotPlatform: 'Tencent Cloud IoT',
      iotCommandId: 'iot_cmd_2024102305300001',
      deviceFeedback: {
        status: 'error',
        message: '指令格式错误',
        data: {
          errorCode: 'INVALID_COMMAND',
          errorDetail: '参数spectrum值"red-blue"不支持，设备仅支持"full"或"custom"模式',
          supportedValues: ['full', 'custom'],
        },
      },
      result: {
        success: false,
        message: '自动执行失败：指令参数不匹配，设备不支持该光谱模式',
      },
      logs: [
        { timestamp: '2024-10-23 05:30:00', event: '指令生成', details: '日出前补光，系统自动生成补光指令' },
        { timestamp: '2024-10-23 05:30:02', event: '指令下发', details: '通过Tencent Cloud IoT下发至补光灯-17' },
        { timestamp: '2024-10-23 05:30:05', event: '设备响应', details: '设备返回参数错误(INVALID_COMMAND)' },
        { timestamp: '2024-10-23 05:30:06', event: '执行失败', details: '光谱参数"red-blue"不支持，设备仅支持full/custom模式' },
        { timestamp: '2024-10-23 05:30:07', event: '等待手动', details: '建议修改光谱参数后重新执行' },
      ],
    },
    // 执行中案例 #2 - 长时间灌溉
    {
      id: 'cmd_018',
      commandNo: 'CMD-20241023-018',
      decisionId: 'dec_018',
      decisionTitle: '18号大棚深层灌溉决策',
      deviceType: 'irrigation',
      deviceId: 'dev_irr_018',
      deviceName: '水肥机-18',
      fieldName: '18号大棚',
      executionMode: 'auto',
      action: '深层灌溉',
      parameters: {
        duration: 90,
        waterAmount: 200,
        flowRate: 2.22,
        depth: 'deep',
      },
      status: 'executing',
      createdAt: '2024-10-23 07:00:00',
      sentAt: '2024-10-23 07:00:04',
      executedAt: '2024-10-23 07:00:10',
      progress: 42,
      expectedDuration: 90,
      iotPlatform: 'AliCloud IoT',
      iotCommandId: 'iot_cmd_2024102307000001',
      deviceFeedback: {
        status: 'executing',
        message: '正在深层灌溉',
        data: {
          currentWater: 84,
          currentFlow: 2.18,
          soilPenetration: 25,
        },
      },
      logs: [
        { timestamp: '2024-10-23 07:00:00', event: '指令生成', details: '土壤深层干燥，系统自动生成深层灌溉指令' },
        { timestamp: '2024-10-23 07:00:04', event: '指令下发', details: '通过AliCloud IoT下发至水肥机-18' },
        { timestamp: '2024-10-23 07:00:10', event: '开始执行', details: '启动深层灌溉，目标用水200L，预计90分钟' },
        { timestamp: '2024-10-23 07:30:10', event: '执行中', details: '已运行30分钟，用水67L，土壤渗透深度18cm' },
        { timestamp: '2024-10-23 08:08:00', event: '执行中', details: '已运行68分钟(42%)，用水84L，渗透深度25cm，预计还需52分钟' },
      ],
    },
    // 失败案例 #7 - 设备过载
    {
      id: 'cmd_019',
      commandNo: 'CMD-20241023-019',
      decisionId: 'dec_019',
      decisionTitle: '19号大棚紧急通风决策',
      deviceType: 'fan',
      deviceId: 'dev_fan_019',
      deviceName: '排风扇-19',
      fieldName: '19号大棚',
      executionMode: 'auto',
      action: '开启排风',
      parameters: {
        speed: 5,
        duration: 60,
        mode: 'max',
      },
      status: 'failed',
      createdAt: '2024-10-23 16:20:00',
      sentAt: '2024-10-23 16:20:02',
      executedAt: '2024-10-23 16:20:08',
      progress: 15,
      retryCount: 0,
      maxRetries: 3,
      iotPlatform: 'Huawei Cloud IoT',
      iotCommandId: 'iot_cmd_2024102316200001',
      deviceFeedback: {
        status: 'error',
        message: '设备过载',
        data: {
          errorCode: 'DEVICE_OVERLOAD',
          errorDetail: '电机温度95℃，超过安全阈值85℃，自动保护停机',
          motorTemp: 95,
          safetyThreshold: 85,
          runTime: 9,
        },
      },
      result: {
        success: false,
        message: '自动执行失败：设备电机过热，触发安全保护机制',
      },
      logs: [
        { timestamp: '2024-10-23 16:20:00', event: '指令生成', details: '湿度90%，温度36℃，系统生成紧急通风指令' },
        { timestamp: '2024-10-23 16:20:02', event: '指令下发', details: '通过Huawei Cloud IoT下发至排风扇-19' },
        { timestamp: '2024-10-23 16:20:08', event: '开始执行', details: '启动排风扇，最大功率模式' },
        { timestamp: '2024-10-23 16:25:00', event: '温度告警', details: '检测到电机温度78℃，接近阈值' },
        { timestamp: '2024-10-23 16:29:00', event: '过载保护', details: '电机温度95℃，超过安全阈值85℃' },
        { timestamp: '2024-10-23 16:29:01', event: '执行失败', details: '设备过载(DEVICE_OVERLOAD)，自动保护停机，已运行9分钟' },
        { timestamp: '2024-10-23 16:29:02', event: '等待手动', details: '建议设备冷却后降低功率重新执行' },
      ],
    },
    // 成功案例 #7 - 多阶段执行成功
    {
      id: 'cmd_020',
      commandNo: 'CMD-20241023-020',
      decisionId: 'dec_020',
      decisionTitle: '20号大棚分段补光决策',
      deviceType: 'light',
      deviceId: 'dev_light_020',
      deviceName: '补光灯-20',
      fieldName: '20号大棚',
      executionMode: 'auto',
      action: '分段补光',
      parameters: {
        totalDuration: 120,
        stages: [
          { duration: 40, intensity: 50, spectrum: 'full' },
          { duration: 40, intensity: 70, spectrum: 'full' },
          { duration: 40, intensity: 90, spectrum: 'full' },
        ],
      },
      status: 'completed',
      createdAt: '2024-10-23 06:00:00',
      sentAt: '2024-10-23 06:00:03',
      executedAt: '2024-10-23 06:00:08',
      completedAt: '2024-10-23 08:00:08',
      progress: 100,
      expectedDuration: 120,
      actualDuration: 120,
      iotPlatform: 'Tencent Cloud IoT',
      iotCommandId: 'iot_cmd_2024102306000002',
      deviceFeedback: {
        status: 'success',
        message: '分段补光完成',
        data: {
          totalEnergy: 14.4,
          avgIntensity: 70,
          stageCompleted: 3,
        },
      },
      result: {
        success: true,
        message: '分段补光成功，3个阶段均正常完成，总耗电14.4kWh',
        beforeValue: { lightAccumulation: 0 },
        afterValue: { lightAccumulation: 8400 },
      },
      logs: [
        { timestamp: '2024-10-23 06:00:00', event: '指令生成', details: '日出前补光，系统生成3段式补光指令' },
        { timestamp: '2024-10-23 06:00:03', event: '指令下发', details: '通过Tencent Cloud IoT下发至补光灯-20' },
        { timestamp: '2024-10-23 06:00:08', event: '开始执行', details: '启动第1阶段：强度50%，时长40分钟' },
        { timestamp: '2024-10-23 06:40:08', event: '阶段切换', details: '第1阶段完成，切换至第2阶段：强度70%' },
        { timestamp: '2024-10-23 07:20:08', event: '阶段切换', details: '第2阶段完成，切换至第3阶段：强度90%' },
        { timestamp: '2024-10-23 08:00:08', event: '执行完成', details: '第3阶段完成，所有阶段均正常，累计光照8400lux·h' },
        { timestamp: '2024-10-23 08:00:12', event: '结果反馈', details: '分段补光成功，总耗电14.4kWh，平均强度70%' },
      ],
    },
    // 新增：成功案例 #8 - 智能水肥配比成功
    {
      id: 'cmd_021',
      commandNo: 'CMD-20241023-021',
      decisionId: 'dec_021',
      decisionTitle: '21号大棚精准水肥配比决策',
      deviceType: 'irrigation',
      deviceId: 'dev_irr_021',
      deviceName: '水肥机-21',
      fieldName: '21号大棚',
      executionMode: 'auto',
      action: '精准施肥',
      parameters: {
        waterAmount: 180,
        fertilizerType: 'NPK',
        npkRatio: '20-10-15',
        concentration: 0.4,
        duration: 60,
        flowRate: 3.0,
        phTarget: 6.5,
      },
      status: 'completed',
      createdAt: '2024-10-23 09:30:00',
      sentAt: '2024-10-23 09:30:02',
      executedAt: '2024-10-23 09:30:08',
      completedAt: '2024-10-23 10:30:08',
      progress: 100,
      expectedDuration: 60,
      actualDuration: 60,
      iotPlatform: 'AliCloud IoT',
      iotCommandId: 'iot_cmd_2024102309300001',
      deviceFeedback: {
        status: 'success',
        message: '精准施肥完成',
        data: {
          actualWater: 178,
          actualFertilizer: 71.2,
          actualConcentration: 0.39,
          finalPH: 6.48,
          ec: 2.1,
        },
      },
      result: {
        success: true,
        message: '精准水肥配比成功，实际用水178L，肥料71.2L，pH值6.48',
        beforeValue: { soilEC: 1.5, soilPH: 6.8, soilMoisture: 45 },
        afterValue: { soilEC: 2.1, soilPH: 6.5, soilMoisture: 72 },
      },
      logs: [
        { timestamp: '2024-10-23 09:30:00', event: '指令生成', details: '作物生长期营养需求分析，生成精准施肥指令' },
        { timestamp: '2024-10-23 09:30:01', event: '参数计算', details: 'NPK比例20-10-15，浓度0.4%，目标pH 6.5' },
        { timestamp: '2024-10-23 09:30:02', event: '指令下发', details: '通过AliCloud IoT下发至水肥机-21' },
        { timestamp: '2024-10-23 09:30:08', event: '开始执行', details: '启动水肥一体化系统，开始混配' },
        { timestamp: '2024-10-23 10:00:08', event: '执行中', details: '已完成50%，pH监测6.52，EC值1.8' },
        { timestamp: '2024-10-23 10:30:08', event: '执行完成', details: '施肥完成，实际浓度0.39%，pH 6.48，符合预期' },
        { timestamp: '2024-10-23 10:30:12', event: '结果反馈', details: 'EC从1.5提升至2.1，pH从6.8调整至6.5，营养优化成功' },
      ],
    },
    // 新增：失败案例 #8 - 传感器故障
    {
      id: 'cmd_022',
      commandNo: 'CMD-20241023-022',
      decisionId: 'dec_022',
      decisionTitle: '22号大棚土壤湿度调控决策',
      deviceType: 'irrigation',
      deviceId: 'dev_irr_022',
      deviceName: '水肥机-22',
      fieldName: '22号大棚',
      executionMode: 'auto',
      action: '补充灌溉',
      parameters: {
        duration: 35,
        waterAmount: 90,
        flowRate: 2.57,
        targetMoisture: 65,
      },
      status: 'failed',
      createdAt: '2024-10-23 11:15:00',
      sentAt: '2024-10-23 11:15:03',
      executedAt: '2024-10-23 11:15:10',
      progress: 25,
      retryCount: 1,
      maxRetries: 3,
      iotPlatform: 'Huawei Cloud IoT',
      iotCommandId: 'iot_cmd_2024102311150001',
      deviceFeedback: {
        status: 'error',
        message: '传感器故障',
        data: {
          errorCode: 'SENSOR_ERROR',
          errorDetail: '土壤湿度传感器读数异常，返回值-999超出正常范围0-100',
          sensorValue: -999,
          normalRange: [0, 100],
          sensorId: 'SOIL_MOISTURE_022',
        },
      },
      result: {
        success: false,
        message: '自动执行失败：土壤湿度传感器故障，无法监测灌溉效果',
      },
      logs: [
        { timestamp: '2024-10-23 11:15:00', event: '指令生成', details: '土壤湿度42%，低于阈值，生成补充灌溉指令' },
        { timestamp: '2024-10-23 11:15:03', event: '指令下发', details: '通过Huawei Cloud IoT下发至水肥机-22' },
        { timestamp: '2024-10-23 11:15:10', event: '开始执行', details: '启动灌溉，目标湿度65%' },
        { timestamp: '2024-10-23 11:23:00', event: '传感器异常', details: '检测到传感器返回-999，数值异常' },
        { timestamp: '2024-10-23 11:23:05', event: '暂停执行', details: '传感器故障(SENSOR_ERROR)，无法监测，暂停灌溉' },
        { timestamp: '2024-10-23 11:24:00', event: '自动重试', details: '第1次重试：检查传感器状态' },
        { timestamp: '2024-10-23 11:24:05', event: '仍然故障', details: '传感器仍返回异常值，重试失败' },
        { timestamp: '2024-10-23 11:24:06', event: '执行失败', details: '传感器SOIL_MOISTURE_022故障，建议维修后重新执行' },
      ],
    },
    // 新增：成功案例 #9 - 温湿度联合调控成功
    {
      id: 'cmd_023',
      commandNo: 'CMD-20241023-023',
      decisionId: 'dec_023',
      decisionTitle: '23号大棚温湿度平衡决策',
      deviceType: 'curtain',
      deviceId: 'dev_cur_023',
      deviceName: '卷帘机-23',
      fieldName: '23号大棚',
      executionMode: 'auto',
      action: '智能调节',
      parameters: {
        openPercentage: 45,
        speed: 'normal',
        targetTemp: 28,
        targetHumidity: 70,
        reason: '温湿度平衡',
        adjustmentMode: 'auto-balance',
      },
      status: 'completed',
      createdAt: '2024-10-23 13:45:00',
      sentAt: '2024-10-23 13:45:02',
      executedAt: '2024-10-23 13:45:08',
      completedAt: '2024-10-23 13:50:08',
      progress: 100,
      expectedDuration: 5,
      actualDuration: 5,
      iotPlatform: 'Tencent Cloud IoT',
      iotCommandId: 'iot_cmd_2024102313450001',
      deviceFeedback: {
        status: 'success',
        message: '温湿度调控完成',
        data: {
          currentPosition: 45,
          finalTemp: 28.2,
          finalHumidity: 69,
          adjustmentCycles: 3,
        },
      },
      result: {
        success: true,
        message: '温湿度联合调控成功，温度28.2℃，湿度69%，均达标',
        beforeValue: { temperature: 32, humidity: 58, position: 15 },
        afterValue: { temperature: 28.2, humidity: 69, position: 45 },
      },
      logs: [
        { timestamp: '2024-10-23 13:45:00', event: '指令生成', details: '温度32℃过高，湿度58%偏低，生成平衡调控指令' },
        { timestamp: '2024-10-23 13:45:02', event: '指令下发', details: '通过Tencent Cloud IoT下发至卷帘机-23' },
        { timestamp: '2024-10-23 13:45:08', event: '开始执行', details: '卷帘从15%调节至45%，实现通风降温和湿度提升' },
        { timestamp: '2024-10-23 13:47:08', event: '执行中', details: '位置30%，温度30.5℃，湿度62%' },
        { timestamp: '2024-10-23 13:50:08', event: '执行完成', details: '位置45%，温度28.2℃，湿度69%，调控完成' },
        { timestamp: '2024-10-23 13:50:12', event: '结果反馈', details: '温湿度平衡成功，经过3次微调达到最佳状态' },
      ],
    },
    // 新增：失败案例 #9 - 电源异常
    {
      id: 'cmd_024',
      commandNo: 'CMD-20241023-024',
      decisionId: 'dec_024',
      decisionTitle: '24号大棚夜间补光决策',
      deviceType: 'light',
      deviceId: 'dev_light_024',
      deviceName: '补光灯-24',
      fieldName: '24号大棚',
      executionMode: 'auto',
      action: '夜间补光',
      parameters: {
        intensity: 75,
        duration: 300,
        spectrum: 'full',
        startTime: '20:00',
        endTime: '01:00',
      },
      status: 'failed',
      createdAt: '2024-10-23 20:00:00',
      sentAt: '2024-10-23 20:00:02',
      executedAt: '2024-10-23 20:00:08',
      progress: 12,
      retryCount: 2,
      maxRetries: 3,
      iotPlatform: 'AliCloud IoT',
      iotCommandId: 'iot_cmd_2024102320000001',
      deviceFeedback: {
        status: 'error',
        message: '电源异常',
        data: {
          errorCode: 'POWER_ERROR',
          errorDetail: '检测到电压不稳定，输入电压190V低于安全电压220V±10%',
          currentVoltage: 190,
          safeVoltageRange: [198, 242],
          powerFluctuation: true,
        },
      },
      result: {
        success: false,
        message: '自动执行失败：电源电压不稳定，为保护设备已自动停止',
      },
      logs: [
        { timestamp: '2024-10-23 20:00:00', event: '指令生成', details: '夜间光照不足，生成5小时补光指令' },
        { timestamp: '2024-10-23 20:00:02', event: '指令下发', details: '通过AliCloud IoT下发至补光灯-24' },
        { timestamp: '2024-10-23 20:00:08', event: '开始执行', details: '启动补光灯，强度75%，全光谱模式' },
        { timestamp: '2024-10-23 20:36:00', event: '电压告警', details: '检测到电压波动，当前电压195V' },
        { timestamp: '2024-10-23 20:36:30', event: '电压异常', details: '电压降至190V，低于安全范围198-242V' },
        { timestamp: '2024-10-23 20:36:35', event: '保护停机', details: '电源异常(POWER_ERROR)，为保护灯具自动停止' },
        { timestamp: '2024-10-23 20:37:00', event: '第1次重试', details: '等待电压稳定后重试' },
        { timestamp: '2024-10-23 20:37:30', event: '第1次失败', details: '电压仍不稳定，重试失败' },
        { timestamp: '2024-10-23 20:38:00', event: '第2次重试', details: '再次尝试启动' },
        { timestamp: '2024-10-23 20:38:30', event: '第2次失败', details: '电源持续异常，建议检查供电系统' },
        { timestamp: '2024-10-23 20:38:31', event: '执行失败', details: '已重试2次，电源问题未解决，等待人工处理' },
      ],
    },
    // 新增：成功案例 #10 - 复杂调度成功
    {
      id: 'cmd_025',
      commandNo: 'CMD-20241023-025',
      decisionId: 'dec_025',
      decisionTitle: '25号大棚综合环境优化决策',
      deviceType: 'pump',
      deviceId: 'dev_pump_025',
      deviceName: '智能泵站-25',
      fieldName: '25号大棚',
      executionMode: 'auto',
      action: '综合调控',
      parameters: {
        sequence: [
          { device: 'irrigation', duration: 30, waterAmount: 100 },
          { device: 'fertilizer', duration: 20, amount: 30 },
          { device: 'ventilation', duration: 15, speed: 3 },
        ],
        totalDuration: 65,
        coordinated: true,
        priority: 'high',
      },
      status: 'completed',
      createdAt: '2024-10-23 17:00:00',
      sentAt: '2024-10-23 17:00:03',
      executedAt: '2024-10-23 17:00:10',
      completedAt: '2024-10-23 18:05:10',
      progress: 100,
      expectedDuration: 65,
      actualDuration: 65,
      iotPlatform: 'Huawei Cloud IoT',
      iotCommandId: 'iot_cmd_2024102317000001',
      deviceFeedback: {
        status: 'success',
        message: '综合调控完成',
        data: {
          sequenceCompleted: 3,
          totalWater: 98,
          totalFertilizer: 29.5,
          ventilationTime: 15,
          coordinationSuccess: true,
        },
      },
      result: {
        success: true,
        message: '综合环境优化成功，3个调控序列全部完成，环境指标均达标',
        beforeValue: { 
          soilMoisture: 38, 
          soilEC: 1.1, 
          temperature: 31,
          airQuality: 'poor',
        },
        afterValue: { 
          soilMoisture: 65, 
          soilEC: 1.9, 
          temperature: 27,
          airQuality: 'good',
        },
      },
      logs: [
        { timestamp: '2024-10-23 17:00:00', event: '指令生成', details: '综合环境评估，生成3步骤联动调控指令' },
        { timestamp: '2024-10-23 17:00:03', event: '指令下发', details: '通过Huawei Cloud IoT下发至智能泵站-25' },
        { timestamp: '2024-10-23 17:00:10', event: '序列1开始', details: '启动灌溉系统，目标用水100L，预计30分钟' },
        { timestamp: '2024-10-23 17:30:10', event: '序列1完成', details: '灌溉完成，实际用水98L，土壤湿度提升至58%' },
        { timestamp: '2024-10-23 17:30:15', event: '序列2开始', details: '启动施肥系统，目标施肥30L，预计20分钟' },
        { timestamp: '2024-10-23 17:50:15', event: '序列2完成', details: '施肥完成，实际施肥29.5L，EC值提升至1.9' },
        { timestamp: '2024-10-23 17:50:20', event: '序列3开始', details: '启动通风系统，3档风速，预计15分钟' },
        { timestamp: '2024-10-23 18:05:20', event: '序列3完成', details: '通风完成，温度降至27℃，空气质量改善' },
        { timestamp: '2024-10-23 18:05:25', event: '结果反馈', details: '综合调控成功，湿度、营养、温度、空气均优化完成' },
      ],
    },
  ]);

  // 应用筛选条件
  const filteredCommands = commands.filter(command => {
    if (filters.deviceType !== 'all' && command.deviceType !== filters.deviceType) return false;
    if (filters.status !== 'all' && command.status !== filters.status) return false;
    if (filters.executionMode !== 'all' && command.executionMode !== filters.executionMode) return false;
    if (filters.deviceId !== 'all' && command.deviceId !== filters.deviceId) return false;
    if (filters.searchText && !command.decisionTitle.toLowerCase().includes(filters.searchText.toLowerCase())) return false;
    
    // 日期范围筛选
    const now = new Date();
    const createdDate = new Date(command.createdAt);
    const daysDiff = Math.floor((now.getTime() - createdDate.getTime()) / (1000 * 60 * 60 * 24));
    
    switch (filters.dateRange) {
      case 'today':
        if (daysDiff > 0) return false;
        break;
      case '3days':
        if (daysDiff > 3) return false;
        break;
      case '7days':
        if (daysDiff > 7) return false;
        break;
    }
    
    return true;
  });

  const handleViewDetail = (command: ControlCommand) => {
    setSelectedCommand(command);
    setShowCommandDetail(true);
  };

  // 手动下发指令
  const handleManualSend = (command: ControlCommand) => {
    setManualSendingCommand(command);
    setShowManualSendDialog(true);
  };

  const confirmManualSend = () => {
    if (!manualSendingCommand) return;
    
    // 更新指令状态
    setCommands(prev => prev.map(cmd => 
      cmd.id === manualSendingCommand.id
        ? {
            ...cmd,
            status: 'sent' as CommandStatus,
            sentAt: new Date().toISOString().slice(0, 19).replace('T', ' '),
            logs: [
              ...cmd.logs,
              {
                timestamp: new Date().toISOString().slice(0, 19).replace('T', ' '),
                event: '手动下发',
                details: '用户手动下发指令至IoT平台'
              }
            ]
          }
        : cmd
    ));
    
    setShowManualSendDialog(false);
    setManualSendingCommand(null);
    toast.success('指令已手动下发至IoT平台，等待设备响应');
  };

  // 重试失败的指令
  const handleRetryCommand = (command: ControlCommand) => {
    const currentRetry = (command.retryCount || 0) + 1;
    
    // 更新指令状态
    setCommands(prev => prev.map(cmd => 
      cmd.id === command.id
        ? {
            ...cmd,
            status: 'sent' as CommandStatus,
            sentAt: new Date().toISOString().slice(0, 19).replace('T', ' '),
            retryCount: currentRetry,
            logs: [
              ...cmd.logs,
              {
                timestamp: new Date().toISOString().slice(0, 19).replace('T', ' '),
                event: `第${currentRetry}次重试`,
                details: `用户手动重试指令，重新下发至IoT平台`
              }
            ]
          }
        : cmd
    ));
    
    toast.info(`正在重试指令 (第${currentRetry}次)：${command.commandNo}`);
  };

  const handleExport = () => {
    toast.success('控制指令列表导出成功');
  };

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

  const getStatusBadge = (status: CommandStatus) => {
    const config = {
      pending: { label: '待下发', icon: Clock, className: 'bg-warning-muted text-warning-muted-foreground border-warning' },
      sent: { label: '已下发', icon: Send, className: 'bg-info-muted text-info-muted-foreground border-info' },
      auto_executing: { label: '自动执行中', icon: PlayCircle, className: 'bg-accent-muted text-accent-foreground border-accent' },
      executing: { label: '执行中', icon: Activity, className: 'bg-accent-muted text-accent-foreground border-accent' },
      completed: { label: '已完成', icon: CheckCircle, className: 'bg-success-muted text-success-muted-foreground border-success' },
      failed: { label: '执行失败', icon: XCircle, className: 'bg-error-muted text-error-muted-foreground border-error' },
      timeout: { label: '超时', icon: AlertTriangle, className: 'bg-warning-muted text-warning-muted-foreground border-warning' },
    };
    const { label, icon: Icon, className } = config[status];
    return (
      <Badge variant="outline" className={className}>
        <Icon className="w-3 h-3 mr-1" />
        {label}
      </Badge>
    );
  };

  const getExecutionModeBadge = (mode: ExecutionMode) => {
    const config = {
      auto: { label: '自动执行', className: 'bg-accent-muted text-accent-foreground border-accent', icon: Zap },
      manual: { label: '手动执行', className: 'bg-info-muted text-info-muted-foreground border-info', icon: User },
    };
    const { label, className, icon: Icon } = config[mode];
    return (
      <Badge variant="outline" className={className}>
        <Icon className="w-3 h-3 mr-1" />
        {label}
      </Badge>
    );
  };

  const getDeviceTypeBadge = (type: DeviceType) => {
    const config = {
      irrigation: { label: '灌溉', icon: Droplets, className: 'bg-info-muted text-info-muted-foreground' },
      curtain: { label: '卷帘', icon: Sun, className: 'bg-warning-muted text-warning-muted-foreground' },
      fan: { label: '风扇', icon: Wind, className: 'bg-info-muted text-info-muted-foreground' },
      heater: { label: '加温', icon: Thermometer, className: 'bg-error-muted text-error-muted-foreground' },
      light: { label: '补光', icon: Sun, className: 'bg-warning-muted text-warning-muted-foreground' },
      pump: { label: '水泵', icon: Power, className: 'bg-accent-muted text-accent-foreground' },
    };
    const { label, icon: Icon, className } = config[type];
    return (
      <Badge variant="outline" className={className}>
        <Icon className="w-3 h-3 mr-1" />
        {label}
      </Badge>
    );
  };

  // 统计数据
  const stats = {
    total: commands.length,
    completed: commands.filter(c => c.status === 'completed').length,
    executing: commands.filter(c => ['auto_executing', 'executing', 'sent'].includes(c.status)).length,
    failed: commands.filter(c => c.status === 'failed').length,
    pending: commands.filter(c => c.status === 'pending').length,
    autoExecution: commands.filter(c => c.executionMode === 'auto').length,
    manualExecution: commands.filter(c => c.executionMode === 'manual').length,
  };

  return (
    <div className="space-y-6">
      {/* 页面标题 */}
      <Card className="p-6 bg-gradient-to-r from-green-50 to-emerald-50 border-green-200">
        <div className="flex items-start gap-3">
          <Zap className="w-6 h-6 text-green-600 flex-shrink-0 mt-1" />
          <div className="flex-1">
            <h2 className="mb-2">设备控制集成</h2>
            <p className="text-sm text-muted-foreground mb-3">
              自动生成标准控制指令，通过集成IoT平台下发至设备执行，支持自动执行和失败重试
            </p>
            <div className="flex flex-wrap gap-2">
              <Badge variant="outline" className="bg-white">
                <PlayCircle className="w-3 h-3 mr-1" />
                自动执行
              </Badge>
              <Badge variant="outline" className="bg-white">
                <Radio className="w-3 h-3 mr-1" />
                IoT平台集成
              </Badge>
              <Badge variant="outline" className="bg-white">
                <RotateCcw className="w-3 h-3 mr-1" />
                失败重试
              </Badge>
              <Badge variant="outline" className="bg-white">
                <Activity className="w-3 h-3 mr-1" />
                实时监控
              </Badge>
            </div>
          </div>
        </div>
      </Card>

      {/* 统计卡片 */}
      <div className="grid grid-cols-5 gap-4">
        <Card className="p-4">
          <div className="flex items-center justify-between mb-2">
            <div className="text-sm text-muted-foreground">总指令数</div>
            <Database className="w-4 h-4 text-gray-400" />
          </div>
          <div className="text-2xl font-bold">{stats.total}</div>
        </Card>

        <Card className="p-4">
          <div className="flex items-center justify-between mb-2">
            <div className="text-sm text-muted-foreground">执行中</div>
            <Activity className="w-4 h-4 text-purple-500" />
          </div>
          <div className="text-2xl font-bold text-purple-600">{stats.executing}</div>
        </Card>

        <Card className="p-4">
          <div className="flex items-center justify-between mb-2">
            <div className="text-sm text-muted-foreground">已完成</div>
            <CheckCircle className="w-4 h-4 text-green-500" />
          </div>
          <div className="text-2xl font-bold text-green-600">{stats.completed}</div>
        </Card>

        <Card className="p-4">
          <div className="flex items-center justify-between mb-2">
            <div className="text-sm text-muted-foreground">执行失败</div>
            <XCircle className="w-4 h-4 text-red-500" />
          </div>
          <div className="text-2xl font-bold text-red-600">{stats.failed}</div>
        </Card>

        <Card className="p-4">
          <div className="flex items-center justify-between mb-2">
            <div className="text-sm text-muted-foreground">待下发</div>
            <Clock className="w-4 h-4 text-orange-500" />
          </div>
          <div className="text-2xl font-bold text-orange-600">{stats.pending}</div>
        </Card>
      </div>

      {/* 筛选工具栏 */}
      <Card className="p-4">
        <div className="flex items-center gap-2 mb-4">
          <Filter className="w-5 h-5 text-green-600" />
          <h3>筛选条件</h3>
        </div>
        <div className="flex items-center gap-4 flex-wrap">
          {/* 搜索 */}
          <div className="flex-1 min-w-64">
            <div className="relative">
              <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-gray-400" />
              <Input
                placeholder="搜索决策标题..."
                value={filters.searchText}
                onChange={(e) => setFilters({ ...filters, searchText: e.target.value })}
                className="pl-10"
              />
            </div>
          </div>

          {/* 执行模式 */}
          <div className="w-40">
            <Select value={filters.executionMode} onValueChange={(value) => setFilters({ ...filters, executionMode: value })}>
              <SelectTrigger>
                <SelectValue placeholder="执行模式" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="all">全部模式</SelectItem>
                <SelectItem value="auto">自动执行</SelectItem>
                <SelectItem value="manual">手动执行</SelectItem>
              </SelectContent>
            </Select>
          </div>

          {/* 设备类型 */}
          <div className="w-40">
            <Select value={filters.deviceType} onValueChange={(value) => setFilters({ ...filters, deviceType: value })}>
              <SelectTrigger>
                <SelectValue placeholder="设备类型" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="all">全部类型</SelectItem>
                <SelectItem value="irrigation">灌溉</SelectItem>
                <SelectItem value="curtain">卷帘</SelectItem>
                <SelectItem value="fan">风扇</SelectItem>
                <SelectItem value="heater">加温</SelectItem>
                <SelectItem value="light">补光</SelectItem>
                <SelectItem value="pump">水泵</SelectItem>
              </SelectContent>
            </Select>
          </div>

          {/* 指令状态 */}
          <div className="w-40">
            <Select value={filters.status} onValueChange={(value) => setFilters({ ...filters, status: value })}>
              <SelectTrigger>
                <SelectValue placeholder="指令状态" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="all">全部状态</SelectItem>
                <SelectItem value="pending">待下发</SelectItem>
                <SelectItem value="sent">已下发</SelectItem>
                <SelectItem value="auto_executing">自动执行中</SelectItem>
                <SelectItem value="executing">执行中</SelectItem>
                <SelectItem value="completed">已完成</SelectItem>
                <SelectItem value="failed">执行失败</SelectItem>
              </SelectContent>
            </Select>
          </div>

          {/* 时间范围 */}
          <div className="w-40">
            <Select value={filters.dateRange} onValueChange={(value) => setFilters({ ...filters, dateRange: value })}>
              <SelectTrigger>
                <SelectValue placeholder="时间范围" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="today">今天</SelectItem>
                <SelectItem value="3days">最近3天</SelectItem>
                <SelectItem value="7days">最近7天</SelectItem>
                <SelectItem value="all">全部</SelectItem>
              </SelectContent>
            </Select>
          </div>

          {/* 操作按钮 */}
          <div className="flex items-center gap-2 ml-auto">
            <Button variant="outline" size="sm" onClick={handleRefresh}>
              <RefreshCw className="w-4 h-4 mr-1" />
              刷新
            </Button>
            <Button variant="outline" size="sm" onClick={handleExport}>
              <Download className="w-4 h-4 mr-1" />
              导出
            </Button>
          </div>
        </div>

        {/* 筛选结果提示 */}
        <div className="mt-3 flex items-center justify-between">
          <div className="flex items-center gap-2 text-sm text-muted-foreground">
            <Info className="w-4 h-4" />
            共找到 <strong className="text-foreground">{filteredCommands.length}</strong> 条控制指令
          </div>
          <div className="flex items-center gap-4 text-sm text-muted-foreground">
            <div className="flex items-center gap-1">
              <Zap className="w-4 h-4 text-purple-500" />
              自动执行: <strong className="text-foreground">{stats.autoExecution}</strong>
            </div>
            <div className="flex items-center gap-1">
              <User className="w-4 h-4 text-blue-500" />
              手动执行: <strong className="text-foreground">{stats.manualExecution}</strong>
            </div>
          </div>
        </div>
      </Card>

      {/* 控制指令列表 */}
      <Card className="p-6">
        <h3 className="mb-4">控制指令列表</h3>
        
        {filteredCommands.length === 0 ? (
          <div className="text-center py-12 text-muted-foreground">
            <FileText className="w-12 h-12 mx-auto mb-3 opacity-50" />
            <div>暂无符合条件的控制指令</div>
          </div>
        ) : (
          <div className="space-y-4">
            {filteredCommands.map((command) => (
              <Card key={command.id} className="p-5 hover:shadow-md transition-shadow">
                <div className="flex items-start justify-between">
                  <div className="flex-1">
                    <div className="flex items-center gap-2 mb-2">
                      {getExecutionModeBadge(command.executionMode)}
                      {getDeviceTypeBadge(command.deviceType)}
                      {getStatusBadge(command.status)}
                      {command.retryCount && command.retryCount > 0 && (
                        <Badge variant="outline" className="bg-yellow-100 text-yellow-800 border-yellow-300">
                          <RotateCcw className="w-3 h-3 mr-1" />
                          已重试 {command.retryCount} 次
                        </Badge>
                      )}
                    </div>
                    
                    <h4 className="mb-2">{command.decisionTitle}</h4>
                    
                    <div className="grid grid-cols-3 gap-4 text-sm mb-3">
                      <div>
                        <span className="text-muted-foreground">指令编号:</span>
                        <span className="ml-2 font-medium">{command.commandNo}</span>
                      </div>
                      <div>
                        <span className="text-muted-foreground">设备:</span>
                        <span className="ml-2 font-medium">{command.deviceName}</span>
                      </div>
                      <div>
                        <span className="text-muted-foreground">地块:</span>
                        <span className="ml-2 font-medium">{command.fieldName}</span>
                      </div>
                      <div>
                        <span className="text-muted-foreground">动作:</span>
                        <span className="ml-2 font-medium">{command.action}</span>
                      </div>
                      <div>
                        <span className="text-muted-foreground">创建时间:</span>
                        <span className="ml-2 font-medium">{command.createdAt}</span>
                      </div>
                      {command.iotPlatform && (
                        <div>
                          <span className="text-muted-foreground">IoT平台:</span>
                          <span className="ml-2 font-medium">{command.iotPlatform}</span>
                        </div>
                      )}
                    </div>

                    {/* 执行参数 */}
                    <div className="p-3 bg-muted rounded text-sm mb-3">
                      <div className="flex items-center gap-4 flex-wrap">
                        {Object.entries(command.parameters).map(([key, value]) => (
                          <div key={key} className="flex items-center gap-1">
                            <Settings className="w-4 h-4 text-blue-600" />
                            <span className="text-muted-foreground">{key}:</span>
                            <strong>{String(value)}</strong>
                          </div>
                        ))}
                      </div>
                    </div>

                    {/* 执行进度 */}
                    {(command.status === 'auto_executing' || command.status === 'executing') && command.progress !== undefined && (
                      <div className="mb-3">
                        <div className="flex items-center justify-between text-sm mb-1">
                          <span className="text-muted-foreground">执行进度</span>
                          <span className="font-medium">{command.progress}%</span>
                        </div>
                        <Progress value={command.progress} className="h-2" />
                      </div>
                    )}

                    {/* 执行结果 */}
                    {command.result && (
                      <div className={`p-3 rounded text-sm ${
                        command.result.success 
                          ? 'bg-green-50 border border-green-200' 
                          : 'bg-red-50 border border-red-200'
                      }`}>
                        <div className="flex items-center gap-2">
                          {command.result.success ? (
                            <CheckCircle className="w-4 h-4 text-green-600" />
                          ) : (
                            <XCircle className="w-4 h-4 text-red-600" />
                          )}
                          <span className={command.result.success ? 'text-green-900' : 'text-red-900'}>
                            {command.result.message}
                          </span>
                        </div>
                        {command.result.beforeValue && command.result.afterValue && (
                          <div className="mt-2 flex items-center gap-4 text-xs">
                            <span>执行前: {JSON.stringify(command.result.beforeValue)}</span>
                            <ArrowRight className="w-3 h-3" />
                            <span>执行后: {JSON.stringify(command.result.afterValue)}</span>
                          </div>
                        )}
                      </div>
                    )}

                    {/* 设备反馈 */}
                    {command.deviceFeedback && command.status !== 'completed' && (
                      <div className="p-3 bg-blue-50 rounded text-sm border border-blue-200">
                        <div className="flex items-center gap-2">
                          <Radio className="w-4 h-4 text-blue-600" />
                          <span className="text-blue-900">
                            设备反馈: {command.deviceFeedback.message}
                          </span>
                        </div>
                      </div>
                    )}
                  </div>

                  <div className="flex flex-col gap-2 ml-4">
                    <Button size="sm" variant="outline" onClick={() => handleViewDetail(command)}>
                      <Eye className="w-4 h-4 mr-1" />
                      详情
                    </Button>
                    
                    {/* 手动下发按钮（待下发状态或手动执行模式） */}
                    {(command.status === 'pending' || command.executionMode === 'manual') && command.status !== 'completed' && (
                      <Button 
                        size="sm" 
                        onClick={() => handleManualSend(command)} 
                        className="bg-green-600 hover:bg-green-700"
                      >
                        <Send className="w-4 h-4 mr-1" />
                        手动下发
                      </Button>
                    )}
                    
                    {/* 失败重试按钮 */}
                    {command.status === 'failed' && (
                      <Button 
                        size="sm" 
                        variant="outline" 
                        onClick={() => handleRetryCommand(command)}
                        className="border-orange-300 text-orange-700 hover:bg-orange-50"
                      >
                        <RotateCcw className="w-4 h-4 mr-1" />
                        重试{command.retryCount ? ` (${command.retryCount}/${command.maxRetries || 3})` : ''}
                      </Button>
                    )}
                  </div>
                </div>
              </Card>
            ))}
          </div>
        )}
      </Card>

      {/* 指令详情对话框 */}
      <Dialog open={showCommandDetail} onOpenChange={setShowCommandDetail}>
        <DialogContent className="max-w-4xl max-h-[90vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle>控制指令详情</DialogTitle>
            <DialogDescription>
              查看控制指令的完整执行过程和设备反馈信息
            </DialogDescription>
          </DialogHeader>

          {selectedCommand && (
            <div className="space-y-6">
              {/* 基本信息 */}
              <div className="p-4 bg-muted rounded-lg">
                <div className="flex items-center gap-2 mb-3">
                  {getExecutionModeBadge(selectedCommand.executionMode)}
                  {getDeviceTypeBadge(selectedCommand.deviceType)}
                  {getStatusBadge(selectedCommand.status)}
                </div>
                <h3 className="mb-3">{selectedCommand.decisionTitle}</h3>
                <div className="grid grid-cols-3 gap-4 text-sm">
                  <div>
                    <span className="text-muted-foreground">指令编号:</span>
                    <div className="font-medium mt-1">{selectedCommand.commandNo}</div>
                  </div>
                  <div>
                    <span className="text-muted-foreground">设备名称:</span>
                    <div className="font-medium mt-1">{selectedCommand.deviceName}</div>
                  </div>
                  <div>
                    <span className="text-muted-foreground">所属地块:</span>
                    <div className="font-medium mt-1">{selectedCommand.fieldName}</div>
                  </div>
                  <div>
                    <span className="text-muted-foreground">动作指令:</span>
                    <div className="font-medium mt-1">{selectedCommand.action}</div>
                  </div>
                  <div>
                    <span className="text-muted-foreground">创建时间:</span>
                    <div className="font-medium mt-1">{selectedCommand.createdAt}</div>
                  </div>
                  {selectedCommand.iotPlatform && (
                    <div>
                      <span className="text-muted-foreground">IoT平台:</span>
                      <div className="font-medium mt-1">{selectedCommand.iotPlatform}</div>
                    </div>
                  )}
                </div>
              </div>

              {/* 执行参数 */}
              <Card className="p-4">
                <h4 className="mb-3">执行参数</h4>
                <div className="grid grid-cols-2 gap-3">
                  {Object.entries(selectedCommand.parameters).map(([key, value]) => (
                    <div key={key} className="p-3 bg-muted rounded">
                      <div className="text-xs text-muted-foreground mb-1">{key}</div>
                      <div className="font-medium">{String(value)}</div>
                    </div>
                  ))}
                </div>
              </Card>

              {/* 执行日志 */}
              <Card className="p-4">
                <h4 className="mb-3">执行日志</h4>
                <div className="space-y-2">
                  {selectedCommand.logs.map((log, idx) => (
                    <div key={idx} className="flex items-start gap-3 p-3 bg-muted rounded">
                      <div className="flex-shrink-0 w-32 text-sm text-muted-foreground">
                        {log.timestamp}
                      </div>
                      <div className="flex-shrink-0">
                        <Badge variant="outline" className="text-xs">{log.event}</Badge>
                      </div>
                      <div className="flex-1 text-sm">{log.details}</div>
                    </div>
                  ))}
                </div>
              </Card>

              {/* 设备反馈 */}
              {selectedCommand.deviceFeedback && (
                <Card className="p-4">
                  <h4 className="mb-3">设备反馈</h4>
                  <div className="p-4 bg-blue-50 rounded border border-blue-200">
                    <div className="grid grid-cols-2 gap-3 text-sm">
                      <div>
                        <span className="text-muted-foreground">反馈状态:</span>
                        <div className="font-medium mt-1">{selectedCommand.deviceFeedback.status}</div>
                      </div>
                      <div>
                        <span className="text-muted-foreground">反馈信息:</span>
                        <div className="font-medium mt-1">{selectedCommand.deviceFeedback.message}</div>
                      </div>
                      {selectedCommand.deviceFeedback.data && (
                        <div className="col-span-2">
                          <span className="text-muted-foreground">详细数据:</span>
                          <div className="font-mono text-xs mt-1 p-2 bg-white rounded">
                            {JSON.stringify(selectedCommand.deviceFeedback.data, null, 2)}
                          </div>
                        </div>
                      )}
                    </div>
                  </div>
                </Card>
              )}

              {/* 执行结果 */}
              {selectedCommand.result && (
                <Card className="p-4">
                  <h4 className="mb-3">执行结果</h4>
                  <div className={`p-4 rounded ${
                    selectedCommand.result.success 
                      ? 'bg-green-50 border border-green-200' 
                      : 'bg-red-50 border border-red-200'
                  }`}>
                    <div className="flex items-center gap-2 mb-2">
                      {selectedCommand.result.success ? (
                        <CheckCircle className="w-5 h-5 text-green-600" />
                      ) : (
                        <XCircle className="w-5 h-5 text-red-600" />
                      )}
                      <span className={`font-medium ${
                        selectedCommand.result.success ? 'text-green-900' : 'text-red-900'
                      }`}>
                        {selectedCommand.result.message}
                      </span>
                    </div>
                    {selectedCommand.result.beforeValue && selectedCommand.result.afterValue && (
                      <div className="mt-3 grid grid-cols-2 gap-4 text-sm">
                        <div>
                          <span className="text-muted-foreground">执行前数值:</span>
                          <div className="font-mono mt-1 p-2 bg-white rounded">
                            {JSON.stringify(selectedCommand.result.beforeValue, null, 2)}
                          </div>
                        </div>
                        <div>
                          <span className="text-muted-foreground">执行后数值:</span>
                          <div className="font-mono mt-1 p-2 bg-white rounded">
                            {JSON.stringify(selectedCommand.result.afterValue, null, 2)}
                          </div>
                        </div>
                      </div>
                    )}
                  </div>
                </Card>
              )}
            </div>
          )}

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

      {/* 手动下发确认对话框 */}
      <Dialog open={showManualSendDialog} onOpenChange={setShowManualSendDialog}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>确认手动下发指令</DialogTitle>
            <DialogDescription>
              确认要手动下发此控制指令至IoT平台吗？
            </DialogDescription>
          </DialogHeader>

          {manualSendingCommand && (
            <div className="py-4 space-y-4">
              <div className="p-4 bg-blue-50 rounded-lg border border-blue-200">
                <div className="flex items-center gap-2 mb-2">
                  <Info className="w-5 h-5 text-blue-600" />
                  <h4 className="text-sm font-medium text-blue-900">指令信息</h4>
                </div>
                <div className="space-y-2 text-sm">
                  <div className="flex justify-between">
                    <span className="text-muted-foreground">指令编号:</span>
                    <strong>{manualSendingCommand.commandNo}</strong>
                  </div>
                  <div className="flex justify-between">
                    <span className="text-muted-foreground">设备:</span>
                    <strong>{manualSendingCommand.deviceName}</strong>
                  </div>
                  <div className="flex justify-between">
                    <span className="text-muted-foreground">动作:</span>
                    <strong>{manualSendingCommand.action}</strong>
                  </div>
                  {manualSendingCommand.iotPlatform && (
                    <div className="flex justify-between">
                      <span className="text-muted-foreground">IoT平台:</span>
                      <strong>{manualSendingCommand.iotPlatform}</strong>
                    </div>
                  )}
                </div>
              </div>

              <div className="flex items-start gap-3 p-3 bg-yellow-50 rounded border border-yellow-200">
                <AlertTriangle className="w-5 h-5 text-yellow-600 flex-shrink-0 mt-0.5" />
                <div className="text-sm text-yellow-900">
                  <div className="font-medium mb-1">注意事项：</div>
                  <ul className="list-disc list-inside space-y-1">
                    <li>确保设备在线且处于正常状态</li>
                    <li>指令将通过IoT平台立即下发至设备</li>
                    <li>请确认设备参数配置正确</li>
                  </ul>
                </div>
              </div>
            </div>
          )}

          <DialogFooter>
            <Button variant="outline" onClick={() => setShowManualSendDialog(false)}>
              取消
            </Button>
            <Button onClick={confirmManualSend} className="bg-green-600 hover:bg-green-700">
              <Send className="w-4 h-4 mr-2" />
              确认下发
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
}
