import { useState, useEffect } from 'react';
import { Card } from '../../ui/card';
import { Badge } from '../../ui/badge';
import { Button } from '../../ui/button';
import { Plus, Trash2, Eye, Search, Filter, Activity, Signal, Battery, Clock, ChevronRight, Link2, History } from 'lucide-react';
import { MachineryRecord } from '../../../types/machinery';
import { machineryStorage } from '../../../lib/machineryStorage';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '../../ui/table';
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle, DialogFooter } from '../../ui/dialog';
import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle } from '../../ui/alert-dialog';
import { Input } from '../../ui/input';
import { Label } from '../../ui/label';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '../../ui/select';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '../../ui/tabs';
import { Progress } from '../../ui/progress';
import { toast } from 'sonner@2.0.3';

// 物联设备接口（来自全域数据感知中心）
interface IoTDevice {
  id: string;
  code: string;
  name: string;
  type: string;
  manufacturer: string;
  model: string;
  status: '在线' | '离线' | '故障' | '维护中';
  batteryLevel?: number;
  signalStrength?: number;
  lastReportTime?: string;
}

// 负载挂载记录接口
interface LoadMountRecord {
  id: string;
  machineryId: string;
  deviceId: string;
  mountDate: string;
  mountTime: string;
  mountBy: string;
  unmountDate?: string;
  unmountTime?: string;
  unmountBy?: string;
  status: '已挂载' | '已卸载';
  remarks?: string;
  createdAt: string;
  updatedAt: string;
}

// 农机挂载设备清单
interface MachineryLoadList {
  machinery: MachineryRecord;
  mountedDevices: {
    record: LoadMountRecord;
    device: IoTDevice;
  }[];
}

// 设备监控数据接口
interface DeviceMonitorData {
  deviceId: string;
  temperature?: number;
  workTime?: number;
  dataCount?: number;
  lastUpdate?: string;
  sensors?: {
    name: string;
    value: number;
    unit: string;
    status: 'normal' | 'warning' | 'error';
  }[];
}

export function LoadDevice() {
  const [machinery, setMachinery] = useState<MachineryRecord[]>([]);
  const [iotDevices, setIotDevices] = useState<IoTDevice[]>([]);
  const [mountRecords, setMountRecords] = useState<LoadMountRecord[]>([]);
  const [monitorData, setMonitorData] = useState<DeviceMonitorData[]>([]);
  const [selectedMachineryId, setSelectedMachineryId] = useState<string>('');
  const [showMountDialog, setShowMountDialog] = useState(false);
  const [showViewDialog, setShowViewDialog] = useState(false);
  const [viewingData, setViewingData] = useState<{
    record: LoadMountRecord;
    device: IoTDevice;
    monitor?: DeviceMonitorData;
  } | null>(null);
  const [showUnmountConfirm, setShowUnmountConfirm] = useState(false);
  const [pendingUnmountId, setPendingUnmountId] = useState<string | null>(null);
  const [searchTerm, setSearchTerm] = useState('');

  const [selectedDevice, setSelectedDevice] = useState('');
  const [mountRemarks, setMountRemarks] = useState('');
  const [unmountRemarks, setUnmountRemarks] = useState('');

  useEffect(() => {
    loadData();
    // 模拟实时监控数据更新
    const interval = setInterval(() => {
      updateMonitorData();
    }, 5000);
    return () => clearInterval(interval);
  }, []);

  const loadData = () => {
    // 加载农机数据
    const machineryData = machineryStorage.getAllMachinery();
    setMachinery(machineryData);
    if (machineryData.length > 0 && !selectedMachineryId) {
      setSelectedMachineryId(machineryData[0].id);
    }

    // 加载物联设备数据
    const devicesData = localStorage.getItem('smart_agriculture_iot_devices');
    if (devicesData) {
      const devices = JSON.parse(devicesData);
      setIotDevices(devices);
    } else {
      // 初始化示例物联设备数据
      const mockDevices: IoTDevice[] = [
        {
          id: 'iot-1',
          code: 'GPS-2024-001',
          name: 'GPS定位器-001',
          type: 'GPS定位器',
          manufacturer: '北斗星通',
          model: 'BD-GPS-Pro',
          status: '在线',
          batteryLevel: 85,
          signalStrength: 92,
          lastReportTime: '2024-10-28 14:35:20',
        },
        {
          id: 'iot-2',
          code: 'CAM-2024-001',
          name: '监控摄像头-001',
          type: '摄像头',
          manufacturer: '海康威视',
          model: 'HIK-CAM-4K',
          status: '在线',
          signalStrength: 88,
          lastReportTime: '2024-10-28 14:35:15',
        },
        {
          id: 'iot-3',
          code: 'SENSOR-2024-001',
          name: '油耗传感器-001',
          type: '油耗传感器',
          manufacturer: '艾默生',
          model: 'EMR-FUEL-500',
          status: '在线',
          batteryLevel: 78,
          signalStrength: 85,
          lastReportTime: '2024-10-28 14:35:18',
        },
        {
          id: 'iot-4',
          code: 'TEMP-2024-001',
          name: '温度传感器-001',
          type: '温度传感器',
          manufacturer: '施耐德',
          model: 'SE-TEMP-100',
          status: '在线',
          batteryLevel: 92,
          signalStrength: 90,
          lastReportTime: '2024-10-28 14:35:22',
        },
        {
          id: 'iot-5',
          code: 'SPEED-2024-001',
          name: '速度传感器-001',
          type: '速度传感器',
          manufacturer: '博世',
          model: 'BOSCH-SPEED-X1',
          status: '在线',
          batteryLevel: 88,
          signalStrength: 87,
          lastReportTime: '2024-10-28 14:35:19',
        },
      ];
      localStorage.setItem('smart_agriculture_iot_devices', JSON.stringify(mockDevices));
      setIotDevices(mockDevices);
    }

    // 加载挂载记录
    const recordsData = localStorage.getItem('smart_agriculture_load_mount_records');
    if (recordsData) {
      setMountRecords(JSON.parse(recordsData));
    } else {
      // 初始化示例挂载记录
      const mockRecords: LoadMountRecord[] = [
        {
          id: 'mount-1',
          machineryId: machineryData[0]?.id || 'machinery-1',
          deviceId: 'iot-1',
          mountDate: '2024-10-01',
          mountTime: '09:30:00',
          mountBy: '张三',
          status: '已挂载',
          remarks: '用于实时定位追踪',
          createdAt: new Date().toISOString(),
          updatedAt: new Date().toISOString(),
        },
        {
          id: 'mount-2',
          machineryId: machineryData[0]?.id || 'machinery-1',
          deviceId: 'iot-3',
          mountDate: '2024-10-01',
          mountTime: '09:35:00',
          mountBy: '张三',
          status: '已挂载',
          remarks: '监控油耗数据',
          createdAt: new Date().toISOString(),
          updatedAt: new Date().toISOString(),
        },
        {
          id: 'mount-3',
          machineryId: machineryData[1]?.id || 'machinery-2',
          deviceId: 'iot-2',
          mountDate: '2024-10-05',
          mountTime: '10:15:00',
          mountBy: '李四',
          status: '已挂载',
          remarks: '监控作业过程',
          createdAt: new Date().toISOString(),
          updatedAt: new Date().toISOString(),
        },
        {
          id: 'mount-4',
          machineryId: machineryData[0]?.id || 'machinery-1',
          deviceId: 'iot-5',
          mountDate: '2024-09-20',
          mountTime: '08:20:00',
          mountBy: '王五',
          unmountDate: '2024-10-10',
          unmountTime: '16:30:00',
          unmountBy: '赵六',
          status: '已卸载',
          remarks: '设备升级更换',
          createdAt: new Date().toISOString(),
          updatedAt: new Date().toISOString(),
        },
      ];
      localStorage.setItem('smart_agriculture_load_mount_records', JSON.stringify(mockRecords));
      setMountRecords(mockRecords);
    }

    // 初始化监控数据
    initMonitorData();
  };

  const initMonitorData = () => {
    const mockMonitorData: DeviceMonitorData[] = [
      {
        deviceId: 'iot-1',
        workTime: 125.5,
        dataCount: 15230,
        lastUpdate: '2024-10-28 14:35:20',
        sensors: [
          { name: '纬度', value: 39.9042, unit: '°', status: 'normal' },
          { name: '经度', value: 116.4074, unit: '°', status: 'normal' },
          { name: '速度', value: 12.5, unit: 'km/h', status: 'normal' },
        ],
      },
      {
        deviceId: 'iot-2',
        workTime: 98.3,
        dataCount: 8920,
        lastUpdate: '2024-10-28 14:35:15',
        sensors: [
          { name: '图像质量', value: 98, unit: 'score', status: 'normal' },
          { name: '存储空间', value: 45, unit: '%', status: 'normal' },
        ],
      },
      {
        deviceId: 'iot-3',
        temperature: 45.2,
        workTime: 132.8,
        dataCount: 19850,
        lastUpdate: '2024-10-28 14:35:18',
        sensors: [
          { name: '瞬时油耗', value: 8.5, unit: 'L/h', status: 'normal' },
          { name: '累计油耗', value: 1125.8, unit: 'L', status: 'normal' },
        ],
      },
      {
        deviceId: 'iot-5',
        temperature: 38.5,
        workTime: 86.2,
        dataCount: 12450,
        lastUpdate: '2024-10-28 14:35:19',
        sensors: [
          { name: '当前速度', value: 15.3, unit: 'km/h', status: 'normal' },
          { name: '最大速度', value: 42.8, unit: 'km/h', status: 'normal' },
        ],
      },
    ];
    setMonitorData(mockMonitorData);
  };

  const updateMonitorData = () => {
    setMonitorData(prev => prev.map(data => ({
      ...data,
      temperature: data.temperature ? data.temperature + (Math.random() - 0.5) * 2 : undefined,
      workTime: (data.workTime || 0) + Math.random() * 0.5,
      dataCount: (data.dataCount || 0) + Math.floor(Math.random() * 10),
      lastUpdate: new Date().toLocaleString('zh-CN', { hour12: false }),
      sensors: data.sensors?.map(sensor => ({
        ...sensor,
        value: sensor.value + (Math.random() - 0.5) * (sensor.value * 0.1),
        status: Math.random() > 0.95 ? 'warning' : 'normal',
      })),
    })));
  };

  const handleMount = () => {
    if (!selectedMachineryId || !selectedDevice) {
      toast.error('请选择农机和设备');
      return;
    }

    // 检查设备是否已挂载
    const existingMount = mountRecords.find(
      r => r.deviceId === selectedDevice && r.status === '已挂载'
    );
    if (existingMount) {
      toast.error('该设备已被挂载到其他农机');
      return;
    }

    const now = new Date();
    const deviceInfo = iotDevices.find(d => d.id === selectedDevice);

    const newRecord: LoadMountRecord = {
      id: `mount-${Date.now()}`,
      machineryId: selectedMachineryId,
      deviceId: selectedDevice,
      mountDate: now.toISOString().split('T')[0],
      mountTime: now.toTimeString().split(' ')[0],
      mountBy: '当前用户', // 实际应从登录状态获取
      status: '已挂载',
      remarks: mountRemarks,
      createdAt: now.toISOString(),
      updatedAt: now.toISOString(),
    };

    const newRecords = [...mountRecords, newRecord];
    setMountRecords(newRecords);
    localStorage.setItem('smart_agriculture_load_mount_records', JSON.stringify(newRecords));
    
    toast.success(`设备 ${deviceInfo?.name} 已成功挂载`);
    setShowMountDialog(false);
    setSelectedDevice('');
    setMountRemarks('');
  };

  const handleUnmountClick = (id: string) => {
    setPendingUnmountId(id);
    setShowUnmountConfirm(true);
  };

  const confirmUnmount = () => {
    if (pendingUnmountId) {
      const record = mountRecords.find(r => r.id === pendingUnmountId);
      if (record && record.status === '已挂载') {
        const now = new Date();
        const updatedRecord: LoadMountRecord = {
          ...record,
          unmountDate: now.toISOString().split('T')[0],
          unmountTime: now.toTimeString().split(' ')[0],
          unmountBy: '当前用户', // 实际应从登录状态获取
          status: '已卸载',
          remarks: unmountRemarks || record.remarks, // 保留原有备注或使用卸载备注
          updatedAt: now.toISOString(),
        };

        const newRecords = mountRecords.map(r => r.id === pendingUnmountId ? updatedRecord : r);
        setMountRecords(newRecords);
        localStorage.setItem('smart_agriculture_load_mount_records', JSON.stringify(newRecords));
        
        const device = iotDevices.find(d => d.id === record.deviceId);
        toast.success(`设备 ${device?.name} 已成功卸载`);
      }
    }
    setShowUnmountConfirm(false);
    setPendingUnmountId(null);
    setUnmountRemarks('');
  };

  const handleView = (record: LoadMountRecord) => {
    const device = iotDevices.find(d => d.id === record.deviceId);
    const monitor = monitorData.find(m => m.deviceId === record.deviceId);
    if (device) {
      setViewingData({ record, device, monitor });
      setShowViewDialog(true);
    }
  };

  const getStatusColor = (status: string) => {
    return status === '已挂载'
      ? 'bg-success-muted text-success'
      : 'bg-muted text-muted-foreground';
  };

  const getDeviceStatusColor = (status: string) => {
    switch (status) {
      case '在线': return 'bg-success-muted text-success';
      case '离线': return 'bg-muted text-muted-foreground';
      case '故障': return 'bg-error-muted text-error';
      case '维护中': return 'bg-warning-muted text-warning';
      default: return 'bg-muted text-muted-foreground';
    }
  };

  const getSensorStatusColor = (status: string) => {
    switch (status) {
      case 'normal': return 'text-success';
      case 'warning': return 'text-warning';
      case 'error': return 'text-error';
      default: return 'text-muted-foreground';
    }
  };

  // 获取可用于挂载的设备（未被挂载的设备）
  const availableDevices = iotDevices.filter(device => {
    const mounted = mountRecords.some(
      r => r.deviceId === device.id && r.status === '已挂载'
    );
    return !mounted;
  });

  // 获取当前选中农机的挂载设备清单
  const getMachineryLoadList = (): MachineryLoadList | null => {
    if (!selectedMachineryId) return null;
    const machineryInfo = machinery.find(m => m.id === selectedMachineryId);
    if (!machineryInfo) return null;

    const mountedDevices = mountRecords
      .filter(r => r.machineryId === selectedMachineryId && r.status === '已挂载')
      .map(record => {
        const device = iotDevices.find(d => d.id === record.deviceId);
        return device ? { record, device } : null;
      })
      .filter((item): item is { record: LoadMountRecord; device: IoTDevice } => item !== null);

    return {
      machinery: machineryInfo,
      mountedDevices,
    };
  };

  // 搜索过滤农机
  const filteredMachinery = machinery.filter(m => {
    if (!searchTerm) return true;
    const searchLower = searchTerm.toLowerCase();
    return (
      (m.name && m.name.toLowerCase().includes(searchLower)) ||
      (m.code && m.code.toLowerCase().includes(searchLower))
    );
  });

  const loadList = getMachineryLoadList();

  const totalMountedDevices = mountRecords.filter(r => r.status === '已挂载').length;
  const totalAvailableDevices = availableDevices.length;

  return (
    <div className="space-y-6">
      <div>
        <h2 className="text-primary">负载管理</h2>
        <p className="text-muted-foreground">为每台农机维护挂载设备清单，实时监控设备状态</p>
      </div>

      {/* 统计卡片 */}
      <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
        <Card className="p-4 bg-gradient-to-br from-green-50 to-green-100 dark:from-green-900/20 dark:to-green-800/20">
          <div className="text-sm text-muted-foreground">已挂载设备总数</div>
          <div className="mt-1 text-success">{totalMountedDevices}</div>
        </Card>
        <Card className="p-4 bg-gradient-to-br from-blue-50 to-blue-100 dark:from-blue-900/20 dark:to-blue-800/20">
          <div className="text-sm text-muted-foreground">可用设备</div>
          <div className="mt-1 text-info">{totalAvailableDevices}</div>
        </Card>
        <Card className="p-4 bg-gradient-to-br from-purple-50 to-purple-100 dark:from-purple-900/20 dark:to-purple-800/20">
          <div className="text-sm text-muted-foreground">当前农机挂载数</div>
          <div className="mt-1 text-info">
            {loadList?.mountedDevices.length || 0}
          </div>
        </Card>
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
        {/* 左侧：农机列表 */}
        <Card className="lg:col-span-1">
          <div className="p-4 border-b">
            <h3>农机列表</h3>
            <div className="mt-3">
              <div className="relative">
                <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground" />
                <Input
                  placeholder="搜索农机..."
                  value={searchTerm}
                  onChange={(e) => setSearchTerm(e.target.value)}
                  className="pl-10"
                />
              </div>
            </div>
          </div>

          <div className="max-h-[600px] overflow-y-auto">
            {filteredMachinery.length === 0 ? (
              <div className="text-center text-muted-foreground py-12">
                <Filter className="w-12 h-12 mx-auto mb-3 opacity-30" />
                <p>暂无农机数据</p>
              </div>
            ) : (
              <div className="p-2">
                {filteredMachinery.map((m) => {
                  const mountedCount = mountRecords.filter(
                    r => r.machineryId === m.id && r.status === '已挂载'
                  ).length;
                  const isSelected = selectedMachineryId === m.id;

                  return (
                    <div
                      key={m.id}
                      className={`p-3 mb-2 rounded-lg cursor-pointer transition-all ${
                        isSelected
                          ? 'bg-success-muted border-2 border-success'
                          : 'bg-card border border-border hover:border-success/50'
                      }`}
                      onClick={() => setSelectedMachineryId(m.id)}
                    >
                      <div className="flex items-center justify-between">
                        <div className="flex-1">
                          <div className="font-medium">{m.name || m.code}</div>
                          <div className="text-sm text-muted-foreground mt-1">
                            {m.typeName || '未分类'}
                          </div>
                        </div>
                        <div className="flex items-center gap-2">
                          <Badge variant="outline" className="bg-info-muted text-info">
                            {mountedCount} 设备
                          </Badge>
                          {isSelected && <ChevronRight className="w-4 h-4 text-success" />}
                        </div>
                      </div>
                    </div>
                  );
                })}
              </div>
            )}
          </div>
        </Card>

        {/* 右侧：挂载设备清单与拆卸历史 */}
        <Card className="lg:col-span-2">
          <div className="p-4 border-b">
            <div className="flex items-center justify-between">
              <div>
                <h3>设备管理</h3>
                {loadList && (
                  <p className="text-sm text-muted-foreground mt-1">
                    {loadList.machinery.name || loadList.machinery.code}
                  </p>
                )}
              </div>
              <Button onClick={() => setShowMountDialog(true)} disabled={!selectedMachineryId}>
                <Plus className="w-4 h-4 mr-2" />
                挂载设备
              </Button>
            </div>
          </div>

          {!loadList ? (
            <div className="text-center text-muted-foreground py-12">
              <Activity className="w-12 h-12 mx-auto mb-3 opacity-30" />
              <p>请先选择一台农机</p>
            </div>
          ) : (
            <Tabs defaultValue="current" className="p-4">
              <TabsList className="grid w-full grid-cols-2 mb-4">
                <TabsTrigger value="current">
                  当前挂载 ({loadList.mountedDevices.length})
                </TabsTrigger>
                <TabsTrigger value="history">
                  拆卸历史
                </TabsTrigger>
              </TabsList>

              {/* 当前挂载标签页 */}
              <TabsContent value="current" className="mt-0">
                {loadList.mountedDevices.length === 0 ? (
                  <div className="text-center text-muted-foreground py-12">
                    <Filter className="w-12 h-12 mx-auto mb-3 opacity-30" />
                    <p>该农机暂未挂载设备</p>
                    <Button className="mt-4" onClick={() => setShowMountDialog(true)}>
                      <Plus className="w-4 h-4 mr-2" />
                      挂载设备
                    </Button>
                  </div>
                ) : (
                  <div className="space-y-4">
                    {loadList.mountedDevices.map(({ record, device }) => {
                      const monitor = monitorData.find(m => m.deviceId === device.id);
                      
                      return (
                        <Card key={record.id} className="p-4 border-l-4 border-green-500">
                          <div className="flex items-start justify-between mb-3">
                            <div className="flex-1">
                              <div className="flex items-center gap-2 mb-2">
                                <h4>{device.name}</h4>
                                <Badge variant="outline">{device.type}</Badge>
                                <Badge className={getDeviceStatusColor(device.status)}>
                                  {device.status}
                                </Badge>
                              </div>
                              <div className="text-sm text-muted-foreground space-y-1">
                                <div>编号: {device.code}</div>
                                <div>制造商: {device.manufacturer} | 型号: {device.model}</div>
                                <div className="flex items-center gap-4 mt-2">
                                  <div className="flex items-center gap-1">
                                    <Clock className="w-3 h-3" />
                                    挂载: {record.mountDate} {record.mountTime}
                                  </div>
                                  <div>操作人: {record.mountBy}</div>
                                </div>
                              </div>
                            </div>
                            <div className="flex items-center gap-2">
                              <Button
                                variant="ghost"
                                size="sm"
                                onClick={() => handleView(record)}
                                title="查看详情及监控数据"
                              >
                                <Eye className="w-4 h-4" />
                              </Button>
                              <Button
                                variant="ghost"
                                size="sm"
                                onClick={() => handleUnmountClick(record.id)}
                                title="卸载设备"
                              >
                                <Trash2 className="w-4 h-4 text-error" />
                              </Button>
                            </div>
                          </div>

                          {/* 设备状态指示器 */}
                          <div className="grid grid-cols-2 md:grid-cols-4 gap-3 mt-3 pt-3 border-t">
                            {device.signalStrength !== undefined && (
                              <div className="flex items-center gap-2">
                                <Signal className="w-4 h-4 text-muted-foreground" />
                                <div>
                                  <div className="text-xs text-muted-foreground">信号强度</div>
                                  <div className="text-sm font-medium">{device.signalStrength}%</div>
                                  <Progress value={device.signalStrength} className="h-1 mt-1" />
                                </div>
                              </div>
                            )}
                            {device.batteryLevel !== undefined && (
                              <div className="flex items-center gap-2">
                                <Battery className="w-4 h-4 text-muted-foreground" />
                                <div>
                                  <div className="text-xs text-muted-foreground">电池电量</div>
                                  <div className="text-sm font-medium">{device.batteryLevel}%</div>
                                  <Progress value={device.batteryLevel} className="h-1 mt-1" />
                                </div>
                              </div>
                            )}
                            {monitor?.workTime !== undefined && (
                              <div className="flex items-center gap-2">
                                <Activity className="w-4 h-4 text-muted-foreground" />
                                <div>
                                  <div className="text-xs text-muted-foreground">工作时长</div>
                                  <div className="text-sm font-medium">{monitor.workTime.toFixed(1)}h</div>
                                </div>
                              </div>
                            )}
                            {monitor?.dataCount !== undefined && (
                              <div className="flex items-center gap-2">
                                <Link2 className="w-4 h-4 text-muted-foreground" />
                                <div>
                                  <div className="text-xs text-muted-foreground">数据上报</div>
                                  <div className="text-sm font-medium">{monitor.dataCount}</div>
                                </div>
                              </div>
                            )}
                          </div>

                          {/* 实时传感器数据 */}
                          {monitor?.sensors && monitor.sensors.length > 0 && (
                            <div className="mt-3 pt-3 border-t">
                              <div className="text-xs text-muted-foreground mb-2">实时监控数据</div>
                              <div className="grid grid-cols-2 md:grid-cols-3 gap-2">
                                {monitor.sensors.map((sensor, idx) => (
                                  <div key={idx} className="text-sm">
                                    <span className="text-muted-foreground">{sensor.name}: </span>
                                    <span className={`font-medium ${getSensorStatusColor(sensor.status)}`}>
                                      {sensor.value.toFixed(2)} {sensor.unit}
                                    </span>
                                  </div>
                                ))}
                              </div>
                            </div>
                          )}
                        </Card>
                      );
                    })}
                  </div>
                )}
              </TabsContent>

              {/* 拆卸历史标签页 */}
              <TabsContent value="history" className="mt-0">
                {(() => {
                  // 获取该农机的所有历史记录（只显示已卸载的）
                  const machineryHistory = mountRecords
                    .filter(r => r.machineryId === selectedMachineryId && r.status === '已卸载')
                    .sort((a, b) => {
                      // 按卸载时间倒序排列（最新的在最上面）
                      const aTime = r => r.unmountDate ? new Date(`${r.unmountDate} ${r.unmountTime}`).getTime() : 0;
                      return aTime(b) - aTime(a);
                    });

                  // 计算挂载时长（拆卸历史中都是已卸载的记录）
                  const calculateDuration = (record: LoadMountRecord) => {
                    const mountDateTime = new Date(`${record.mountDate} ${record.mountTime}`);
                    const unmountDateTime = new Date(`${record.unmountDate} ${record.unmountTime}`);
                    const hours = (unmountDateTime.getTime() - mountDateTime.getTime()) / (1000 * 60 * 60);
                    if (hours < 24) {
                      return `${hours.toFixed(1)} 小时`;
                    } else {
                      const days = hours / 24;
                      return `${days.toFixed(1)} 天（${hours.toFixed(1)} 小时）`;
                    }
                  };

                  return machineryHistory.length > 0 ? (
                    <div>
                      <div className="mb-4 text-sm text-muted-foreground">
                        共 {machineryHistory.length} 条记录
                      </div>
                      <Table>
                        <TableHeader>
                          <TableRow>
                            <TableHead>设备</TableHead>
                            <TableHead>挂载时间</TableHead>
                            <TableHead>挂载人</TableHead>
                            <TableHead>卸载时间</TableHead>
                            <TableHead>卸载人</TableHead>
                            <TableHead>挂载时长</TableHead>
                            <TableHead>备注</TableHead>
                          </TableRow>
                        </TableHeader>
                        <TableBody>
                          {machineryHistory.map((record) => {
                            const device = iotDevices.find(d => d.id === record.deviceId);
                            return (
                              <TableRow key={record.id}>
                                <TableCell>
                                  <div className="font-medium">
                                    {device?.name || '未知设备'}
                                  </div>
                                  <div className="text-xs text-muted-foreground">
                                    {device?.code}
                                  </div>
                                </TableCell>
                                <TableCell className="text-sm">
                                  <div>{record.mountDate}</div>
                                  <div className="text-muted-foreground">{record.mountTime}</div>
                                </TableCell>
                                <TableCell className="text-sm">{record.mountBy}</TableCell>
                                <TableCell className="text-sm">
                                  <div>{record.unmountDate}</div>
                                  <div className="text-muted-foreground">{record.unmountTime}</div>
                                </TableCell>
                                <TableCell className="text-sm">
                                  {record.unmountBy}
                                </TableCell>
                                <TableCell className="text-sm">
                                  <div className="font-medium">
                                    {calculateDuration(record)}
                                  </div>
                                </TableCell>
                                <TableCell className="text-sm max-w-[200px]">
                                  <div className="truncate" title={record.remarks || ''}>
                                    {record.remarks || '-'}
                                  </div>
                                </TableCell>
                              </TableRow>
                            );
                          })}
                        </TableBody>
                      </Table>
                    </div>
                  ) : (
                    <div className="text-center text-muted-foreground py-12">
                      <History className="w-12 h-12 mx-auto mb-3 opacity-30" />
                      <p>暂无拆卸历史记录</p>
                    </div>
                  );
                })()}
              </TabsContent>
            </Tabs>
          )}
        </Card>
      </div>

      {/* 挂载设备对话框 */}
      <Dialog open={showMountDialog} onOpenChange={setShowMountDialog}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>挂载设备</DialogTitle>
            <DialogDescription>
              为 {loadList?.machinery.name || loadList?.machinery.code} 挂载设备
            </DialogDescription>
          </DialogHeader>

          <div className="space-y-4">
            <div>
              <Label>选择设备 *</Label>
              <Select value={selectedDevice} onValueChange={setSelectedDevice}>
                <SelectTrigger className="mt-2">
                  <SelectValue placeholder="请选择设备" />
                </SelectTrigger>
                <SelectContent>
                  {availableDevices.map((device) => (
                    <SelectItem key={device.id} value={device.id}>
                      <div className="flex items-center gap-2">
                        <span>{device.name}</span>
                        <Badge variant="outline" className="text-xs">{device.type}</Badge>
                        <Badge className={getDeviceStatusColor(device.status)} variant="outline">
                          {device.status}
                        </Badge>
                      </div>
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
              {availableDevices.length === 0 && (
                <p className="text-sm text-muted-foreground mt-2">
                  暂无可用设备，所有设备都已被挂载
                </p>
              )}
            </div>

            <div>
              <Label>备注</Label>
              <Input
                value={mountRemarks}
                onChange={(e) => setMountRemarks(e.target.value)}
                placeholder="选填，记录挂载说明"
                className="mt-2"
              />
            </div>
          </div>

          <DialogFooter>
            <Button variant="outline" onClick={() => setShowMountDialog(false)}>
              取消
            </Button>
            <Button onClick={handleMount}>
              确认挂载
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* 查看详情对话框 - 包含监控数据 */}
      <Dialog open={showViewDialog} onOpenChange={setShowViewDialog}>
        <DialogContent className="max-w-3xl max-h-[90vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle>设备详情与监控数据</DialogTitle>
            <DialogDescription>查看设备挂载信息和实时监控数据</DialogDescription>
          </DialogHeader>

          {viewingData && (
            <Tabs defaultValue="info" className="mt-4">
              <TabsList className="grid w-full grid-cols-2">
                <TabsTrigger value="info">挂载信息</TabsTrigger>
                <TabsTrigger value="monitor">监控数据</TabsTrigger>
              </TabsList>

              <TabsContent value="info" className="space-y-4 mt-4">
                <div>
                  <h4 className="mb-3">设备信息</h4>
                  <div className="grid grid-cols-2 gap-4">
                    <div>
                      <Label>设备名称</Label>
                      <div className="field-value">{viewingData.device.name}</div>
                    </div>
                    <div>
                      <Label>设备编号</Label>
                      <div className="field-value">{viewingData.device.code}</div>
                    </div>
                    <div>
                      <Label>设备类型</Label>
                      <div className="field-value">
                        <Badge variant="outline">{viewingData.device.type}</Badge>
                      </div>
                    </div>
                    <div>
                      <Label>设备状态</Label>
                      <div className="field-value">
                        <Badge className={getDeviceStatusColor(viewingData.device.status)}>
                          {viewingData.device.status}
                        </Badge>
                      </div>
                    </div>
                    <div>
                      <Label>制造商</Label>
                      <div className="field-value">{viewingData.device.manufacturer}</div>
                    </div>
                    <div>
                      <Label>型号</Label>
                      <div className="field-value">{viewingData.device.model}</div>
                    </div>
                  </div>
                </div>

                <div>
                  <h4 className="mb-3">挂载信息</h4>
                  <div className="grid grid-cols-2 gap-4">
                    <div>
                      <Label>挂载日期</Label>
                      <div className="field-value">{viewingData.record.mountDate}</div>
                    </div>
                    <div>
                      <Label>挂载时间</Label>
                      <div className="field-value">{viewingData.record.mountTime}</div>
                    </div>
                    <div>
                      <Label>挂载人</Label>
                      <div className="field-value">{viewingData.record.mountBy}</div>
                    </div>
                    <div>
                      <Label>挂载状态</Label>
                      <div className="field-value">
                        <Badge className={getStatusColor(viewingData.record.status)}>
                          {viewingData.record.status}
                        </Badge>
                      </div>
                    </div>
                    {viewingData.record.unmountDate && (
                      <>
                        <div>
                          <Label>卸载日期</Label>
                          <div className="field-value">{viewingData.record.unmountDate}</div>
                        </div>
                        <div>
                          <Label>卸载时间</Label>
                          <div className="field-value">{viewingData.record.unmountTime}</div>
                        </div>
                        <div>
                          <Label>卸载人</Label>
                          <div className="field-value">{viewingData.record.unmountBy}</div>
                        </div>
                      </>
                    )}
                  </div>
                </div>

                {viewingData.record.remarks && (
                  <div>
                    <Label>备注</Label>
                    <div className="field-value">{viewingData.record.remarks}</div>
                  </div>
                )}
              </TabsContent>

              <TabsContent value="monitor" className="space-y-4 mt-4">
                {viewingData.monitor ? (
                  <>
                    <div>
                      <h4 className="mb-3">设备状态</h4>
                      <div className="grid grid-cols-2 gap-4">
                        {viewingData.device.signalStrength !== undefined && (
                          <div>
                            <Label>信号强度</Label>
                            <div className="field-value flex items-center gap-2">
                              <Signal className="w-4 h-4" />
                              {viewingData.device.signalStrength}%
                              <Progress value={viewingData.device.signalStrength} className="h-2 flex-1" />
                            </div>
                          </div>
                        )}
                        {viewingData.device.batteryLevel !== undefined && (
                          <div>
                            <Label>电池电量</Label>
                            <div className="field-value flex items-center gap-2">
                              <Battery className="w-4 h-4" />
                              {viewingData.device.batteryLevel}%
                              <Progress value={viewingData.device.batteryLevel} className="h-2 flex-1" />
                            </div>
                          </div>
                        )}
                        {viewingData.monitor.temperature !== undefined && (
                          <div>
                            <Label>设备温度</Label>
                            <div className="field-value">{viewingData.monitor.temperature.toFixed(1)}°C</div>
                          </div>
                        )}
                        <div>
                          <Label>工作时长</Label>
                          <div className="field-value">{viewingData.monitor.workTime?.toFixed(1)}小时</div>
                        </div>
                        <div>
                          <Label>数据上报次数</Label>
                          <div className="field-value">{viewingData.monitor.dataCount}</div>
                        </div>
                        <div>
                          <Label>最后更新时间</Label>
                          <div className="field-value text-sm">{viewingData.monitor.lastUpdate}</div>
                        </div>
                      </div>
                    </div>

                    {viewingData.monitor.sensors && viewingData.monitor.sensors.length > 0 && (
                      <div>
                        <h4 className="mb-3">传感器数据</h4>
                        <Table>
                          <TableHeader>
                            <TableRow>
                              <TableHead>传感器名称</TableHead>
                              <TableHead>当前值</TableHead>
                              <TableHead>单位</TableHead>
                              <TableHead>状态</TableHead>
                            </TableRow>
                          </TableHeader>
                          <TableBody>
                            {viewingData.monitor.sensors.map((sensor, idx) => (
                              <TableRow key={idx}>
                                <TableCell>{sensor.name}</TableCell>
                                <TableCell className={`font-medium ${getSensorStatusColor(sensor.status)}`}>
                                  {sensor.value.toFixed(2)}
                                </TableCell>
                                <TableCell>{sensor.unit}</TableCell>
                                <TableCell>
                                  <Badge variant="outline" className={getSensorStatusColor(sensor.status)}>
                                    {sensor.status === 'normal' ? '正常' : sensor.status === 'warning' ? '警告' : '错误'}
                                  </Badge>
                                </TableCell>
                              </TableRow>
                            ))}
                          </TableBody>
                        </Table>
                      </div>
                    )}
                  </>
                ) : (
                  <div className="text-center text-muted-foreground py-12">
                    <Activity className="w-12 h-12 mx-auto mb-3 opacity-30" />
                    <p>暂无监控数据</p>
                  </div>
                )}
              </TabsContent>
            </Tabs>
          )}
        </DialogContent>
      </Dialog>

      {/* 卸载确认对话框 */}
      <Dialog open={showUnmountConfirm} onOpenChange={setShowUnmountConfirm}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>卸载设备</DialogTitle>
            <DialogDescription>
              确定要卸载该设备吗？卸载后将记录卸载时间，设备将可以挂载到其他农机。
            </DialogDescription>
          </DialogHeader>

          <div className="space-y-4">
            <div>
              <Label>卸载备注</Label>
              <Input
                value={unmountRemarks}
                onChange={(e) => setUnmountRemarks(e.target.value)}
                placeholder="选填，记录卸载原因或说明"
                className="mt-2"
              />
            </div>
          </div>

          <DialogFooter>
            <Button variant="outline" onClick={() => {
              setShowUnmountConfirm(false);
              setUnmountRemarks('');
            }}>
              取消
            </Button>
            <Button onClick={confirmUnmount}>
              确认卸载
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
}
