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 { Textarea } from '../ui/textarea';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription, DialogFooter } from '../ui/dialog';
import { Label } from '../ui/label';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '../ui/table';
import { Progress } from '../ui/progress';
import { Switch } from '../ui/switch';
import {
  Database,
  Plus,
  Search,
  Download,
  Upload,
  RefreshCw,
  CheckCircle,
  XCircle,
  AlertCircle,
  Clock,
  Cloud,
  Satellite,
  Wifi,
  WifiOff,
  Activity,
  Thermometer,
  Droplet,
  Sun,
  Wind,
  Camera,
  Gauge,
  Zap,
  Settings,
  Eye,
  Edit,
  Trash2,
  Link,
  PlayCircle,
  PauseCircle,
  BarChart3,
  Calendar,
  MapPin,
  Signal,
  CheckCircle2,
  AlertTriangle,
  TrendingUp,
  Filter,
  FileText,
} from 'lucide-react';
import { toast } from 'sonner@2.0.3';
import {
  LineChart,
  Line,
  BarChart,
  Bar,
  XAxis,
  YAxis,
  CartesianGrid,
  Tooltip as RechartsTooltip,
  Legend,
  ResponsiveContainer,
  AreaChart,
  Area,
} from 'recharts';

interface AIDataCenterProps {
  activePath?: string;
}

type DataSourceType = '气象数据' | '卫星遥感' | '土壤数据' | '作物生长' | '其他';
type DataSourceStatus = '正常' | '异常' | '离线' | '待配置';
type AccessMethod = '手动上传' | 'API对接' | 'FTP传输' | 'WebSocket';

type DeviceType = '气象站' | '土壤传感器' | '摄像头' | '水质传感器' | '环境监测站';
type DeviceStatus = '在线' | '离线' | '故障' | '维护中';
type Protocol = 'MQTT' | 'HTTP' | 'CoAP' | 'WebSocket';

interface ExternalDataSource {
  id: string;
  name: string;
  type: DataSourceType;
  provider: string;
  accessMethod: AccessMethod;
  apiEndpoint?: string;
  updateFrequency: string;
  lastUpdateTime: string;
  dataPoints: number;
  status: DataSourceStatus;
  dataFields: string[];
  description: string;
}

interface IoTDevice {
  id: string;
  code: string;
  name: string;
  type: DeviceType;
  deviceTypeId?: string; // 设备类型ID，关联到设备类型管理
  manufacturer: string;
  model: string;
  location: string; // 从业务系统绑定自动获取
  fieldId: string;
  fieldName: string; // 从业务系统绑定自动获取
  protocol: Protocol;
  ipAddress?: string;
  mqttTopic?: string;
  status: DeviceStatus;
  bindingStatus: '未绑定' | '已绑定'; // 设备绑定状态
  bindingSystem?: string; // 绑定的子系统名称
  lastReportTime: string;
  dataFrequency: string;
  batteryLevel?: number;
  signalStrength?: number;
  sensors: {
    name: string;
    unit: string;
    currentValue: number;
    normalRange: string;
  }[];
}

interface DataQuality {
  completeness: number;
  accuracy: number;
  timeliness: number;
  consistency: number;
}

export function AIDataCenter({ activePath }: AIDataCenterProps) {
  const [activeTab, setActiveTab] = useState('external');
  const [showDataSourceDialog, setShowDataSourceDialog] = useState(false);
  const [showDeviceDialog, setShowDeviceDialog] = useState(false);
  const [showUploadDialog, setShowUploadDialog] = useState(false);
  const [showValidationDialog, setShowValidationDialog] = useState(false);
  const [showDataPreviewDialog, setShowDataPreviewDialog] = useState(false);
  const [showDeviceDetailDialog, setShowDeviceDetailDialog] = useState(false);
  const [showRealtimeDataDialog, setShowRealtimeDataDialog] = useState(false);
  const [selectedDataSource, setSelectedDataSource] = useState<ExternalDataSource | null>(null);
  const [selectedDevice, setSelectedDevice] = useState<IoTDevice | null>(null);
  const [uploadedFile, setUploadedFile] = useState<File | null>(null);
  const [uploadedFiles, setUploadedFiles] = useState<File[]>([]);
  const [uploadProgress, setUploadProgress] = useState(0);
  const [selectedAccessMethod, setSelectedAccessMethod] = useState<AccessMethod>('API对接');
  const [deviceTypes, setDeviceTypes] = useState<Array<{ id: string; name: string }>>([]);

  // 根据路径自动切换Tab
  useEffect(() => {
    if (activePath) {
      if (activePath.includes('/data-center/external')) {
        setActiveTab('external');
      } else if (activePath.includes('/data-center/iot')) {
        setActiveTab('iot');
      }
    }
  }, [activePath]);

  // 加载设备类型数据
  useEffect(() => {
    const loadDeviceTypes = () => {
      const data = localStorage.getItem('smart_agriculture_ai_device_types');
      if (data) {
        const types = JSON.parse(data);
        setDeviceTypes(types.map((t: any) => ({ id: t.id, name: t.name })));
      }
    };
    loadDeviceTypes();
  }, []);

  // 外部数据源模拟数据
  const [externalDataSources] = useState<ExternalDataSource[]>([
    {
      id: 'ext-1',
      name: '国家气象局API',
      type: '气象数据',
      provider: '中国气象局',
      accessMethod: 'API对接',
      apiEndpoint: 'https://api.weather.gov.cn/v1/data',
      updateFrequency: '每小时',
      lastUpdateTime: '2024-10-15 14:00:00',
      dataPoints: 24850,
      status: '正常',
      dataFields: ['温度', '湿度', '气压', '降水量', '风速', '风向'],
      description: '实时气象数据，包含温度、湿度、降水等多维度信息',
    },
    {
      id: 'ext-2',
      name: 'Sentinel-2卫星数据',
      type: '卫星遥感',
      provider: 'ESA欧空局',
      accessMethod: 'API对接',
      apiEndpoint: 'https://scihub.copernicus.eu/dhus',
      updateFrequency: '每5天',
      lastUpdateTime: '2024-10-12 08:30:00',
      dataPoints: 1280,
      status: '正常',
      dataFields: ['NDVI', 'EVI', 'LAI', '地表温度', '土壤湿度指数'],
      description: '高分辨率卫星遥感影像，用于作物长势监测',
    },
    {
      id: 'ext-3',
      name: '土壤数据库',
      type: '土壤数据',
      provider: '农业部土壤监测中心',
      accessMethod: '手动上传',
      updateFrequency: '每季度',
      lastUpdateTime: '2024-09-20 10:15:00',
      dataPoints: 385,
      status: '正常',
      dataFields: ['pH值', '有机质', '氮磷钾含量', '土壤质地', '盐分'],
      description: '区域土壤理化性质数据',
    },
    {
      id: 'ext-4',
      name: '光照辐射数据',
      type: '气象数据',
      provider: '光伏气象站网络',
      accessMethod: 'FTP传输',
      updateFrequency: '每30分钟',
      lastUpdateTime: '2024-10-15 13:30:00',
      dataPoints: 15620,
      status: '正常',
      dataFields: ['总辐射', '直接辐射', '散射辐射', '光合有效辐射'],
      description: '太阳辐射数据，用于光合作用分析',
    },
  ]);

  // 地块数据（模拟从地块管理获取）
  const [fieldsList] = useState([
    { id: 'field_001', name: '1号大棚', area: 2.5, cropType: '番茄' },
    { id: 'field_002', name: '2号大棚', area: 3.0, cropType: '番茄' },
    { id: 'field_003', name: '3号地块', area: 5.0, cropType: '小麦' },
    { id: 'field_004', name: '4号地块', area: 4.2, cropType: '玉米' },
    { id: 'field_005', name: '5号大棚', area: 2.8, cropType: '黄瓜' },
    { id: 'field_006', name: '6号地块', area: 8.0, cropType: '水稻' },
    { id: 'field_007', name: '7号大棚', area: 2.2, cropType: '茄子' },
    { id: 'field_008', name: '8号地块', area: 6.5, cropType: '花生' },
  ]);

  // 物联设备模拟数据
  const [iotDevices] = useState<IoTDevice[]>([
    {
      id: 'iot-1',
      code: 'WS-2024-001',
      name: '1号气象站',
      type: '气象站',
      deviceTypeId: 'device-type-2',
      manufacturer: '华为',
      model: 'HW-WS-Pro',
      location: '1号大棚北侧', // 从灌溉系统绑定自动获取
      fieldId: 'field_001',
      fieldName: '1号大棚', // 从地块管理自动获取
      protocol: 'MQTT',
      mqttTopic: 'farm/weather/station01',
      status: '在线',
      bindingStatus: '已绑定',
      bindingSystem: '智能灌溉控制系统',
      lastReportTime: '2024-10-15 14:05:00',
      dataFrequency: '每5分钟',
      batteryLevel: 85,
      signalStrength: 92,
      sensors: [
        { name: '温度', unit: '℃', currentValue: 24.5, normalRange: '-10~40' },
        { name: '湿度', unit: '%', currentValue: 68, normalRange: '0~100' },
        { name: '气压', unit: 'hPa', currentValue: 1013, normalRange: '950~1050' },
        { name: '风速', unit: 'm/s', currentValue: 3.2, normalRange: '0~30' },
      ],
    },
    {
      id: 'iot-2',
      code: 'SS-2024-012',
      name: '2号土壤传感器',
      type: '土壤传感器',
      deviceTypeId: 'device-type-1',
      manufacturer: '中科院',
      model: 'CAS-SS-300',
      location: '3号地块中心', // 从地块管理自动获取
      fieldId: 'field_003',
      fieldName: '3号地块', // 从地块管理自动获取
      protocol: 'MQTT',
      mqttTopic: 'farm/soil/sensor02',
      status: '在线',
      bindingStatus: '已绑定',
      bindingSystem: '智能灌溉控制系统',
      lastReportTime: '2024-10-15 14:03:00',
      dataFrequency: '每10分钟',
      batteryLevel: 72,
      signalStrength: 88,
      sensors: [
        { name: '土壤温度', unit: '℃', currentValue: 18.3, normalRange: '0~35' },
        { name: '土壤湿度', unit: '%', currentValue: 45, normalRange: '20~80' },
        { name: 'EC值', unit: 'mS/cm', currentValue: 1.2, normalRange: '0.5~3' },
        { name: 'pH值', unit: '', currentValue: 6.8, normalRange: '5.5~8.5' },
      ],
    },
    {
      id: 'iot-3',
      code: 'CAM-2024-005',
      name: '3号监控摄像头',
      type: '摄像头',
      deviceTypeId: undefined,
      manufacturer: '海康威视',
      model: 'HIK-CAM-4K',
      location: '2号大棚入口', // 从地块管理自动获取
      fieldId: 'field_002',
      fieldName: '2号大棚', // 从地块管理自动获取
      protocol: 'HTTP',
      ipAddress: '192.168.1.105',
      status: '在线',
      bindingStatus: '未绑定',
      lastReportTime: '2024-10-15 14:05:30',
      dataFrequency: '实时',
      signalStrength: 95,
      sensors: [
        { name: '图像质量', unit: 'score', currentValue: 98, normalRange: '80~100' },
        { name: '存储空间', unit: '%', currentValue: 45, normalRange: '0~90' },
      ],
    },
    {
      id: 'iot-4',
      code: 'WS-2024-002',
      name: '2号气象站',
      type: '气象站',
      deviceTypeId: 'device-type-2',
      manufacturer: '华为',
      model: 'HW-WS-Pro',
      location: '6号地块东侧', // 从地块管理自动获取
      fieldId: 'field_006',
      fieldName: '6号地块', // 从地块管理自动获取
      protocol: 'MQTT',
      mqttTopic: 'farm/weather/station02',
      status: '离线',
      bindingStatus: '未绑定',
      lastReportTime: '2024-10-15 10:25:00',
      dataFrequency: '每5分钟',
      batteryLevel: 15,
      signalStrength: 0,
      sensors: [
        { name: '温度', unit: '℃', currentValue: 0, normalRange: '-10~40' },
        { name: '湿度', unit: '%', currentValue: 0, normalRange: '0~100' },
      ],
    },
  ]);

  // 数据质量评估
  const [dataQuality] = useState<DataQuality>({
    completeness: 94.5,
    accuracy: 96.8,
    timeliness: 92.3,
    consistency: 95.2,
  });

  // 统计数据
  const totalExternalSources = externalDataSources.length;
  const activeExternalSources = externalDataSources.filter(s => s.status === '正常').length;
  const totalDevices = iotDevices.length;
  const onlineDevices = iotDevices.filter(d => d.status === '在线').length;
  const offlineDevices = iotDevices.filter(d => d.status === '离线').length;
  const faultDevices = iotDevices.filter(d => d.status === '故障').length;

  // 设备数据采集趋势
  const deviceDataTrend = [
    { time: '10:00', 数据点: 1250 },
    { time: '11:00', 数据点: 1420 },
    { time: '12:00', 数据点: 1380 },
    { time: '13:00', 数据点: 1560 },
    { time: '14:00', 数据点: 1680 },
  ];

  const getStatusColor = (status: DataSourceStatus | DeviceStatus) => {
    switch (status) {
      case '正常':
      case '在线':
        return 'bg-success-muted text-success-muted-foreground';
      case '异常':
      case '故障':
        return 'bg-error-muted text-error-muted-foreground';
      case '离线':
        return 'bg-muted text-muted-foreground';
      case '待配置':
      case '维护中':
        return 'bg-warning-muted text-warning-muted-foreground';
      default:
        return 'bg-muted text-muted-foreground';
    }
  };

  const getStatusIcon = (status: DataSourceStatus | DeviceStatus) => {
    switch (status) {
      case '正常':
      case '在线':
        return <CheckCircle className="w-4 h-4 text-success" />;
      case '异常':
      case '故障':
        return <XCircle className="w-4 h-4 text-error" />;
      case '离线':
        return <WifiOff className="w-4 h-4 text-muted-foreground" />;
      case '待配置':
      case '维护中':
        return <AlertCircle className="w-4 h-4 text-warning" />;
      default:
        return <AlertCircle className="w-4 h-4 text-muted-foreground" />;
    }
  };

  const getDataTypeIcon = (type: DataSourceType) => {
    switch (type) {
      case '气象数据':
        return <Cloud className="w-4 h-4" />;
      case '卫星遥感':
        return <Satellite className="w-4 h-4" />;
      case '土壤数据':
        return <Database className="w-4 h-4" />;
      case '作物生长':
        return <TrendingUp className="w-4 h-4" />;
      default:
        return <Database className="w-4 h-4" />;
    }
  };

  const getDeviceTypeIcon = (type: DeviceType) => {
    switch (type) {
      case '气象站':
        return <Cloud className="w-4 h-4" />;
      case '土壤传感器':
        return <Gauge className="w-4 h-4" />;
      case '摄像头':
        return <Camera className="w-4 h-4" />;
      case '水质传感器':
        return <Droplet className="w-4 h-4" />;
      case '环境监测站':
        return <Activity className="w-4 h-4" />;
      default:
        return <Wifi className="w-4 h-4" />;
    }
  };

  const handleSaveDataSource = () => {
    toast.success('数据源配置保存成功');
    setShowDataSourceDialog(false);
  };

  const handleSaveDevice = () => {
    toast.success('设备配置保存成功');
    setShowDeviceDialog(false);
  };

  const handleTestConnection = () => {
    toast.success('连接测试成功，数据接入正常');
  };

  const handleSyncData = () => {
    toast.success('数据同步已启动');
  };

  const handleFileUpload = (event: React.ChangeEvent<HTMLInputElement>) => {
    const files = event.target.files;
    if (files && files.length > 0) {
      const fileArray = Array.from(files);
      setUploadedFiles(fileArray);
      setUploadedFile(fileArray[0]); // 保持兼容性
      // 模拟上传进度
      let progress = 0;
      const interval = setInterval(() => {
        progress += 10;
        setUploadProgress(progress);
        if (progress >= 100) {
          clearInterval(interval);
          toast.success(`成功上传${fileArray.length}个文件`);
        }
      }, 200);
    }
  };

  const handleRemoveFile = (index: number) => {
    const newFiles = uploadedFiles.filter((_, i) => i !== index);
    setUploadedFiles(newFiles);
    if (newFiles.length === 0) {
      setUploadedFile(null);
      setUploadProgress(0);
    } else {
      setUploadedFile(newFiles[0]);
    }
  };

  const handleManualUpload = () => {
    setShowUploadDialog(true);
  };

  const handleDataValidation = () => {
    toast.success('数据校验完成，质量评分：优秀');
  };

  const handleDataPreview = () => {
    setShowDataPreviewDialog(true);
  };

  const handleDeviceDetail = (device: IoTDevice) => {
    setSelectedDevice(device);
    setShowDeviceDetailDialog(true);
  };

  const handleRealtimeData = (device: IoTDevice) => {
    setSelectedDevice(device);
    setShowRealtimeDataDialog(true);
  };

  const handleStartDataCollection = () => {
    toast.success('数据采集已启动');
  };

  const handleStopDataCollection = () => {
    toast.success('数据采集已停止');
  };

  const handleDeviceRestart = () => {
    toast.success('设备重启指令已发送');
  };

  return (
    <div className="space-y-6">
      <div>
        <h2>多数据源接入</h2>
        <p className="text-sm text-muted-foreground mt-1">
          多源数据智能接入，构建全面精准的农业数据底座
        </p>
      </div>

      {/* 统计卡片 */}
      <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
        <Card className="p-6">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-xs text-muted-foreground">外部数据源</p>
              <p className="mt-2 text-3xl text-info">{activeExternalSources}/{totalExternalSources}</p>
              <p className="text-xs text-info mt-1">正常运行</p>
            </div>
            <Database className="w-12 h-12 text-info opacity-50" />
          </div>
        </Card>

        <Card className="p-6">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-xs text-muted-foreground">物联设备</p>
              <p className="mt-2 text-3xl text-success">{onlineDevices}/{totalDevices}</p>
              <p className="text-xs text-success mt-1">在线设备</p>
            </div>
            <Wifi className="w-12 h-12 text-success opacity-50" />
          </div>
        </Card>

        <Card className="p-6">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-xs text-muted-foreground">数据质量</p>
              <p className="mt-2 text-3xl text-accent-foreground">{dataQuality.accuracy}%</p>
              <p className="text-xs text-accent-foreground mt-1">准确率</p>
            </div>
            <CheckCircle2 className="w-12 h-12 text-accent-foreground opacity-50" />
          </div>
        </Card>

        <Card className="p-6">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-xs text-muted-foreground">异常告警</p>
              <p className="mt-2 text-3xl text-warning">{offlineDevices + faultDevices}</p>
              <p className="text-xs text-warning mt-1">待处理</p>
            </div>
            <AlertTriangle className="w-12 h-12 text-warning opacity-50" />
          </div>
        </Card>
      </div>

      <Tabs value={activeTab} onValueChange={setActiveTab}>
        <TabsList className="grid w-full grid-cols-2">
          <TabsTrigger value="external">多源数据接入</TabsTrigger>
          <TabsTrigger value="iot">物联设备数据接入</TabsTrigger>
        </TabsList>

        {/* 多源数据接入 */}
        <TabsContent value="external" className="space-y-4">
          <Card className="p-4 bg-gradient-to-r from-info-muted to-accent border-info">
            <div className="flex items-start gap-2">
              <Database className="w-5 h-5 text-info flex-shrink-0 mt-0.5" />
              <div className="text-sm text-info-muted-foreground">
                <p className="mb-2">多源数据接入功能：</p>
                <ul className="space-y-1 text-xs">
                  <li>• <strong>灵活接入</strong>: 支持手动上传、API对接、FTP传输等多种方式</li>
                  <li>• <strong>数据校验</strong>: 提供格式适配与数据质量控制机制</li>
                  <li>• <strong>气象数据</strong>: 温度、湿度、光照、降水等实时气象信息</li>
                  <li>• <strong>卫星遥感</strong>: NDVI植被指数、作物长势监测影像</li>
                  <li>• <strong>高质量支撑</strong>: 确保数据完整性、准确性、时效性</li>
                </ul>
              </div>
            </div>
          </Card>

          <div className="flex gap-4">
            <Button onClick={() => {
              setSelectedDataSource(null);
              setSelectedAccessMethod('API对接');
              setUploadedFile(null);
              setUploadedFiles([]);
              setUploadProgress(0);
              setShowDataSourceDialog(true);
            }}>
              <Plus className="w-4 h-4 mr-2" />
              添加数据源
            </Button>
            <Button variant="outline" onClick={handleManualUpload}>
              <Upload className="w-4 h-4 mr-2" />
              手动上传数据
            </Button>
            <Button variant="outline" onClick={() => setShowValidationDialog(true)}>
              <CheckCircle2 className="w-4 h-4 mr-2" />
              数据校验规则
            </Button>
          </div>

          {/* 数据源列表 */}
          <Card>
            <div className="p-4 border-b">
              <h3 className="flex items-center gap-2">
                <Database className="w-5 h-5 text-info" />
                外部数据源
              </h3>
            </div>
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead>数据源名称</TableHead>
                  <TableHead>数据类型</TableHead>
                  <TableHead>提供商</TableHead>
                  <TableHead>接入方式</TableHead>
                  <TableHead>更新频率</TableHead>
                  <TableHead>数据点数</TableHead>
                  <TableHead>最后更新</TableHead>
                  <TableHead>状态</TableHead>
                  <TableHead>操作</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {externalDataSources.map((source) => (
                  <TableRow key={source.id}>
                    <TableCell>
                      <div className="flex items-center gap-2">
                        {getDataTypeIcon(source.type)}
                        <span className="font-medium">{source.name}</span>
                      </div>
                    </TableCell>
                    <TableCell>
                      <Badge variant="outline">{source.type}</Badge>
                    </TableCell>
                    <TableCell className="text-xs">{source.provider}</TableCell>
                    <TableCell>
                      <Badge variant="outline">{source.accessMethod}</Badge>
                    </TableCell>
                    <TableCell className="text-xs">{source.updateFrequency}</TableCell>
                    <TableCell className="text-xs">{source.dataPoints.toLocaleString()}</TableCell>
                    <TableCell className="text-xs">{source.lastUpdateTime}</TableCell>
                    <TableCell>
                      <div className="flex items-center gap-2">
                        {getStatusIcon(source.status)}
                        <Badge className={getStatusColor(source.status)}>{source.status}</Badge>
                      </div>
                    </TableCell>
                    <TableCell>
                      <div className="flex gap-2">
                        {source.accessMethod !== '手动上传' && (
                          <Button size="sm" variant="outline" onClick={handleTestConnection}>
                            <Link className="w-3 h-3" />
                          </Button>
                        )}
                        <Button size="sm" variant="outline" onClick={() => {
                          setSelectedDataSource(source);
                          setSelectedAccessMethod(source.accessMethod);
                          setShowDataSourceDialog(true);
                        }}>
                          <Edit className="w-3 h-3" />
                        </Button>
                        <Button size="sm" variant="outline" onClick={handleDataPreview}>
                          <Eye className="w-3 h-3" />
                        </Button>
                      </div>
                    </TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>
          </Card>
        </TabsContent>

        {/* 物联设备数据接入 */}
        <TabsContent value="iot" className="space-y-4">
          <Card className="p-4 bg-gradient-to-r from-success-muted/50 to-primary/10 border-success/30">
            <div className="flex items-start gap-2">
              <Wifi className="w-5 h-5 text-success flex-shrink-0 mt-0.5" />
              <div className="text-sm text-success-muted-foreground">
                <p className="mb-2">物联设备数据接入功能：</p>
                <ul className="space-y-1 text-xs">
                  <li>• <strong>无缝接入</strong>: 支持气象站、土壤传感器、摄像头等多种设备</li>
                  <li>• <strong>实时采集</strong>: 环境温湿度、土壤墒情、作物影像等多维数据</li>
                  <li>• <strong>标准协议</strong>: 支持MQTT、HTTP、CoAP等物联网标准协议</li>
                  <li>• <strong>状态监控</strong>: 设备在线状态、电池电量、信号强度实时监控</li>
                  <li>• <strong>质量控制</strong>: 数据质量控制与异常检测能力</li>
                </ul>
              </div>
            </div>
          </Card>

          <div className="flex gap-4">
            <Button onClick={() => {
              setSelectedDevice(null);
              setShowDeviceDialog(true);
            }}>
              <Plus className="w-4 h-4 mr-2" />
              添加设备
            </Button>
          </div>

          {/* 设备状态概览 */}
          <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
            <Card className="p-4 bg-success-muted">
              <div className="flex items-center gap-3">
                <div className="w-10 h-10 bg-success/20 rounded-full flex items-center justify-center">
                  <CheckCircle className="w-5 h-5 text-success" />
                </div>
                <div>
                  <p className="text-xs text-muted-foreground">在线设备</p>
                  <p className="text-2xl text-success">{onlineDevices}</p>
                </div>
              </div>
            </Card>
            <Card className="p-4 bg-muted">
              <div className="flex items-center gap-3">
                <div className="w-10 h-10 bg-muted rounded-full flex items-center justify-center">
                  <WifiOff className="w-5 h-5 text-muted-foreground" />
                </div>
                <div>
                  <p className="text-xs text-muted-foreground">离线设备</p>
                  <p className="text-2xl text-muted-foreground">{offlineDevices}</p>
                </div>
              </div>
            </Card>
            <Card className="p-4 bg-destructive/10">
              <div className="flex items-center gap-3">
                <div className="w-10 h-10 bg-error-muted rounded-full flex items-center justify-center">
                  <XCircle className="w-5 h-5 text-error" />
                </div>
                <div>
                  <p className="text-xs text-muted-foreground">故障设备</p>
                  <p className="text-2xl text-error">{faultDevices}</p>
                </div>
              </div>
            </Card>
            <Card className="p-4 bg-info-muted/50">
              <div className="flex items-center gap-3">
                <div className="w-10 h-10 bg-info-muted rounded-full flex items-center justify-center">
                  <Activity className="w-5 h-5 text-info" />
                </div>
                <div>
                  <p className="text-xs text-muted-foreground">数据采集率</p>
                  <p className="text-2xl text-info">98.5%</p>
                </div>
              </div>
            </Card>
          </div>

          {/* 设备列表 */}
          <Card>
            <div className="p-4 border-b">
              <h3 className="flex items-center gap-2">
                <Wifi className="w-5 h-5 text-success" />
                物联网设备
              </h3>
            </div>
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead>设备编号</TableHead>
                  <TableHead>设备名称</TableHead>
                  <TableHead>设备类型</TableHead>
                  <TableHead>所属地块</TableHead>
                  <TableHead>位置</TableHead>
                  <TableHead>绑定状态</TableHead>
                  <TableHead>通信协议</TableHead>
                  <TableHead>传感器状态</TableHead>
                  <TableHead>信号/电量</TableHead>
                  <TableHead>最后上报</TableHead>
                  <TableHead>设备状态</TableHead>
                  <TableHead>操作</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {iotDevices.map((device) => (
                  <TableRow key={device.id}>
                    <TableCell className="font-medium">{device.code}</TableCell>
                    <TableCell>
                      <div className="flex items-center gap-2">
                        {getDeviceTypeIcon(device.type)}
                        <div>
                          <div>{device.name}</div>
                          <div className="text-xs text-muted-foreground">{device.model}</div>
                        </div>
                      </div>
                    </TableCell>
                    <TableCell>
                      <Badge variant="outline">{device.type}</Badge>
                    </TableCell>
                    <TableCell>
                      <Badge variant="outline" className="bg-success/10 text-success border-success/30">
                        {device.fieldName}
                      </Badge>
                    </TableCell>
                    <TableCell className="text-xs">
                      <div className="flex items-center gap-1">
                        <MapPin className="w-3 h-3" />
                        {device.location}
                      </div>
                    </TableCell>
                    <TableCell>
                      <div className="flex flex-col gap-1">
                        <Badge className={device.bindingStatus === '已绑定' ? 'bg-success-muted text-success border-success' : 'bg-muted text-muted-foreground border-border'}>
                          {device.bindingStatus}
                        </Badge>
                        {device.bindingSystem && (
                          <span className="text-xs text-muted-foreground">{device.bindingSystem}</span>
                        )}
                      </div>
                    </TableCell>
                    <TableCell>
                      <Badge variant="outline">{device.protocol}</Badge>
                    </TableCell>
                    <TableCell>
                      <div className="text-xs space-y-1">
                        {device.sensors.slice(0, 2).map((sensor, idx) => (
                          <div key={idx} className="flex items-center gap-2">
                            <span className="text-muted-foreground">{sensor.name}:</span>
                            <span className="font-medium">{sensor.currentValue}{sensor.unit}</span>
                          </div>
                        ))}
                      </div>
                    </TableCell>
                    <TableCell>
                      <div className="text-xs space-y-1">
                        {device.signalStrength !== undefined && (
                          <div className="flex items-center gap-1">
                            <Signal className="w-3 h-3" />
                            <span>{device.signalStrength}%</span>
                          </div>
                        )}
                        {device.batteryLevel !== undefined && (
                          <div className="flex items-center gap-1">
                            <Zap className="w-3 h-3" />
                            <span>{device.batteryLevel}%</span>
                          </div>
                        )}
                      </div>
                    </TableCell>
                    <TableCell className="text-xs">{device.lastReportTime}</TableCell>
                    <TableCell>
                      <div className="flex items-center gap-2">
                        {getStatusIcon(device.status)}
                        <Badge className={getStatusColor(device.status)}>{device.status}</Badge>
                      </div>
                    </TableCell>
                    <TableCell>
                      <div className="flex gap-2">
                        <Button size="sm" variant="outline" onClick={() => handleRealtimeData(device)} title="实时数据">
                          <Activity className="w-3 h-3" />
                        </Button>
                        <Button size="sm" variant="outline" onClick={() => handleDeviceDetail(device)} title="设备详情">
                          <Eye className="w-3 h-3" />
                        </Button>
                        <Button size="sm" variant="outline" onClick={() => {
                          setSelectedDevice(device);
                          setShowDeviceDialog(true);
                        }} title="编辑配置">
                          <Settings className="w-3 h-3" />
                        </Button>
                      </div>
                    </TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>
          </Card>
        </TabsContent>
      </Tabs>

      {/* 数据源配置对话框 */}
      <Dialog open={showDataSourceDialog} onOpenChange={setShowDataSourceDialog}>
        <DialogContent className="max-w-3xl max-h-[90vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle className="flex items-center gap-2">
              {selectedAccessMethod === '手动上传' && <Upload className="w-5 h-5 text-info" />}
              {selectedDataSource ? '编辑数据源' : '添加数据源'}
            </DialogTitle>
            <DialogDescription>
              {selectedAccessMethod === '手动上传' 
                ? '支持CSV、JSON、XML等多种格式数据上传，支持多文件同时上传，系统将自动进行格式适配和质量校验'
                : '配置外部数据源的接入方式和参数'
              }
            </DialogDescription>
          </DialogHeader>

          <div className="space-y-4">
            <div className="grid grid-cols-2 gap-4">
              <div>
                <Label>数据源名称</Label>
                <Input placeholder={selectedAccessMethod === '手动上传' ? '输入数据源名称，如：2024年10月气象监测数据' : '输入数据源名称'} defaultValue={selectedDataSource?.name} />
              </div>
              <div>
                <Label>数据类型</Label>
                <Select defaultValue={selectedDataSource?.type || '气象数据'}>
                  <SelectTrigger>
                    <SelectValue placeholder="选择数据类型" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="气象数据">气象数据</SelectItem>
                    <SelectItem value="卫星遥感">{selectedAccessMethod === '手动上传' ? '卫星遥感影像' : '卫星遥感'}</SelectItem>
                    <SelectItem value="土壤数据">{selectedAccessMethod === '手动上传' ? '土壤监测数据' : '土壤数据'}</SelectItem>
                    <SelectItem value="作物生长">{selectedAccessMethod === '手动上传' ? '作物生长数据' : '作物生长'}</SelectItem>
                    {selectedAccessMethod === '手动上传' && <SelectItem value="其他">其他数据</SelectItem>}
                  </SelectContent>
                </Select>
              </div>
            </div>

            {/* 接入方式选择 */}
            <div>
              <Label>接入方式</Label>
              <Select 
                defaultValue={selectedDataSource?.accessMethod || selectedAccessMethod}
                onValueChange={(value) => setSelectedAccessMethod(value as AccessMethod)}
              >
                <SelectTrigger>
                  <SelectValue placeholder="选择接入方式" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="手动上传">手动上传</SelectItem>
                  <SelectItem value="API对接">API对接</SelectItem>
                  <SelectItem value="FTP传输">FTP传输</SelectItem>
                  <SelectItem value="WebSocket">WebSocket</SelectItem>
                </SelectContent>
              </Select>
            </div>

            {selectedAccessMethod === '手动上传' ? (
              <>
                {/* 手动上传模式 */}
                <div>
                  <Label>数据提供商</Label>
                  <Input 
                    placeholder="输入数据提供商名称，如：中国气象局、农业部监测中心等" 
                    defaultValue={selectedDataSource?.provider}
                  />
                </div>

                <div>
                  <Label>描述说明</Label>
                  <Textarea 
                    placeholder="输入数据源的描述信息，包括数据来源、采集时间、数据范围等..." 
                    rows={3}
                    defaultValue={selectedDataSource?.description}
                  />
                </div>

                <div>
                  <Label>数据格式</Label>
                  <Select defaultValue="CSV">
                    <SelectTrigger>
                      <SelectValue />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="CSV">CSV（逗号分隔）</SelectItem>
                      <SelectItem value="JSON">JSON</SelectItem>
                      <SelectItem value="XML">XML</SelectItem>
                      <SelectItem value="GeoJSON">GeoJSON（地理数据）</SelectItem>
                      <SelectItem value="Excel">Excel（.xlsx）</SelectItem>
                    </SelectContent>
                  </Select>
                </div>

                {/* 文件上传区域 */}
                <div className="border-2 border-dashed rounded-lg p-8 text-center">
                  <input
                    type="file"
                    id="datasource-file-upload"
                    className="hidden"
                    onChange={handleFileUpload}
                    accept=".csv,.json,.xml,.xlsx,.geojson"
                    multiple
                  />
                  <label htmlFor="datasource-file-upload" className="cursor-pointer">
                    <div className="flex flex-col items-center gap-2">
                      <Upload className="w-12 h-12 text-info" />
                      {uploadedFiles.length === 0 ? (
                        <div>
                          <p className="font-medium">点击上传或拖拽文件到此处</p>
                          <p className="text-xs text-muted-foreground mt-1">
                            支持 CSV, JSON, XML, GeoJSON, Excel 格式，可同时上传多个文件
                          </p>
                        </div>
                      ) : (
                        <div className="w-full">
                          <p className="font-medium text-success mb-2">已选择 {uploadedFiles.length} 个文件</p>
                        </div>
                      )}
                    </div>
                  </label>
                </div>

                {/* 已上传文件列表 */}
                {uploadedFiles.length > 0 && (
                  <Card className="p-4">
                    <h4 className="text-sm font-medium mb-3">已选择的文件</h4>
                    <div className="space-y-2">
                      {uploadedFiles.map((file, index) => (
                        <div key={index} className="flex items-center justify-between p-2 bg-muted rounded">
                          <div className="flex items-center gap-2 flex-1">
                            <FileText className="w-4 h-4 text-info" />
                            <div className="flex-1">
                              <p className="text-sm font-medium">{file.name}</p>
                              <p className="text-xs text-muted-foreground">
                                {(file.size / 1024).toFixed(2)} KB
                              </p>
                            </div>
                          </div>
                          <Button
                            size="sm"
                            variant="ghost"
                            onClick={() => handleRemoveFile(index)}
                          >
                            <XCircle className="w-4 h-4 text-destructive" />
                          </Button>
                        </div>
                      ))}
                    </div>
                  </Card>
                )}

                {/* 上传进度 */}
                {uploadProgress > 0 && uploadProgress < 100 && (
                  <div>
                    <div className="flex items-center justify-between mb-2">
                      <span className="text-sm">上传进度</span>
                      <span className="text-sm font-medium">{uploadProgress}%</span>
                    </div>
                    <Progress value={uploadProgress} className="h-2" />
                  </div>
                )}

                {/* 数据质量校验 */}
                <Card className="p-4 bg-info/10 border-info/30">
                  <h4 className="text-sm mb-3 flex items-center gap-2">
                    <CheckCircle2 className="w-4 h-4 text-info" />
                    数据质量校验
                  </h4>
                  <div className="space-y-2">
                    <div className="flex items-center justify-between">
                      <span className="text-xs">自动检测数据完整性</span>
                      <Switch defaultChecked />
                    </div>
                    <div className="flex items-center justify-between">
                      <span className="text-xs">验证数据格式规范</span>
                      <Switch defaultChecked />
                    </div>
                    <div className="flex items-center justify-between">
                      <span className="text-xs">异常值自动标记</span>
                      <Switch defaultChecked />
                    </div>
                  </div>
                </Card>

                {/* 数据预览 */}
                {uploadedFile && uploadProgress === 100 && (
                  <Card className="p-4">
                    <div className="flex items-center justify-between mb-3">
                      <h4 className="text-sm font-medium">数据预览</h4>
                      <Button size="sm" variant="outline" onClick={handleDataPreview}>
                        <Eye className="w-3 h-3 mr-1" />
                        查看详情
                      </Button>
                    </div>
                    <div className="text-xs space-y-2 text-muted-foreground">
                      <div className="flex justify-between">
                        <span>数据记录数：</span>
                        <span className="font-medium text-foreground">1,245 条</span>
                      </div>
                      <div className="flex justify-between">
                        <span>数据字段数：</span>
                        <span className="font-medium text-foreground">12 个</span>
                      </div>
                      <div className="flex justify-between">
                        <span>完整性评分：</span>
                        <Badge className="bg-success/10 text-success">98.5%</Badge>
                      </div>
                      <div className="flex justify-between">
                        <span>时间范围：</span>
                        <span className="font-medium text-foreground">2024-10-01 至 2024-10-15</span>
                      </div>
                    </div>
                  </Card>
                )}
              </>
            ) : (
              <>
                {/* API对接/FTP传输/WebSocket模式 */}
                <div>
                  <Label>数据提供商</Label>
                  <Input placeholder="输入提供商名称" defaultValue={selectedDataSource?.provider} />
                </div>

                <div>
                  <Label>API端点</Label>
                  <Input placeholder="https://api.example.com/data" defaultValue={selectedDataSource?.apiEndpoint} />
                </div>

                {/* API认证配置 */}
                <Card className="p-4 bg-muted">
                  <h4 className="text-sm mb-3">API认证配置（可选）</h4>
                  <div className="space-y-3">
                    <div>
                      <Label className="text-xs">认证方式</Label>
                      <Select defaultValue="none">
                        <SelectTrigger className="h-8 mt-1">
                          <SelectValue />
                        </SelectTrigger>
                        <SelectContent>
                          <SelectItem value="none">无需认证</SelectItem>
                          <SelectItem value="apikey">API Key</SelectItem>
                          <SelectItem value="bearer">Bearer Token</SelectItem>
                          <SelectItem value="basic">Basic Auth</SelectItem>
                          <SelectItem value="oauth">OAuth 2.0</SelectItem>
                        </SelectContent>
                      </Select>
                    </div>
                    <div className="grid grid-cols-2 gap-3">
                      <div>
                        <Label className="text-xs">API Key / Token</Label>
                        <Input placeholder="输入密钥" type="password" className="h-8 mt-1" />
                      </div>
                      <div>
                        <Label className="text-xs">请求头名称</Label>
                        <Input placeholder="如：X-API-Key" className="h-8 mt-1" />
                      </div>
                    </div>
                  </div>
                </Card>

                <div className="grid grid-cols-2 gap-4">
                  <div>
                    <Label>更新频率</Label>
                    <Select defaultValue={selectedDataSource?.updateFrequency}>
                      <SelectTrigger>
                        <SelectValue placeholder="选择更新频率" />
                      </SelectTrigger>
                      <SelectContent>
                        <SelectItem value="实时">实时</SelectItem>
                        <SelectItem value="每5分钟">每5分钟</SelectItem>
                        <SelectItem value="每小时">每小时</SelectItem>
                        <SelectItem value="每天">每天</SelectItem>
                        <SelectItem value="每周">每周</SelectItem>
                      </SelectContent>
                    </Select>
                  </div>
                  <div>
                    <Label>数据格式</Label>
                    <Select>
                      <SelectTrigger>
                        <SelectValue placeholder="选择数据格式" />
                      </SelectTrigger>
                      <SelectContent>
                        <SelectItem value="JSON">JSON</SelectItem>
                        <SelectItem value="XML">XML</SelectItem>
                        <SelectItem value="CSV">CSV</SelectItem>
                        <SelectItem value="GeoJSON">GeoJSON</SelectItem>
                      </SelectContent>
                    </Select>
                  </div>
                </div>

                <div>
                  <Label>数据字段</Label>
                  <Input placeholder="用逗号分隔多个字段，如：温度,湿度,降水量" defaultValue={selectedDataSource?.dataFields.join(', ')} />
                </div>

                <div>
                  <Label>描述说明</Label>
                  <Textarea placeholder="输入数据源的描述信息..." rows={3} defaultValue={selectedDataSource?.description} />
                </div>

                <div className="flex items-center justify-between p-4 bg-info/10 rounded-lg">
                  <div className="flex items-center gap-2">
                    <Switch />
                    <span className="text-sm">启用自动同步</span>
                  </div>
                  <Button size="sm" variant="outline" onClick={handleTestConnection}>
                    <Link className="w-3 h-3 mr-1" />
                    测试连接
                  </Button>
                </div>
              </>
            )}
          </div>

          <DialogFooter>
            <Button variant="outline" onClick={() => {
              setShowDataSourceDialog(false);
              setUploadedFile(null);
              setUploadedFiles([]);
              setUploadProgress(0);
            }}>
              取消
            </Button>
            <Button 
              className="bg-info hover:bg-info/90" 
              disabled={selectedAccessMethod === '手动上传' && (uploadedFiles.length === 0 || uploadProgress < 100)}
              onClick={() => {
                handleSaveDataSource();
                if (selectedAccessMethod === '手动上传') {
                  setUploadedFile(null);
                  setUploadedFiles([]);
                  setUploadProgress(0);
                }
              }}
            >
              {selectedAccessMethod === '手动上传' ? (
                <>
                  <CheckCircle2 className="w-4 h-4 mr-2" />
                  确认导入 {uploadedFiles.length > 0 ? `(${uploadedFiles.length}个文件)` : ''}
                </>
              ) : (
                '保存配置'
              )}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* 设备配置对话框 */}
      <Dialog open={showDeviceDialog} onOpenChange={setShowDeviceDialog}>
        <DialogContent className="max-w-4xl max-h-[90vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle className="flex items-center gap-2">
              <Settings className="w-5 h-5" />
              {selectedDevice ? '编辑设备配置' : '添加新设备'}
            </DialogTitle>
            <DialogDescription>
              配置IoT设备的基本信息、通信参数和数据采集设置
            </DialogDescription>
          </DialogHeader>

          <div className="space-y-6">
            {/* 基本信息 */}
            <div className="space-y-4">
              <h4 className="text-lg font-medium flex items-center gap-2">
                <Settings className="w-4 h-4" />
                基本信息
              </h4>
              <div className="grid grid-cols-3 gap-4">
                <div>
                  <Label>设备编号</Label>
                  <Input placeholder="如: WS-2024-001" defaultValue={selectedDevice?.code} />
                </div>
                <div>
                  <Label>设备名称</Label>
                  <Input placeholder="如: 1号气象站" defaultValue={selectedDevice?.name} />
                </div>
                <div>
                  <Label>设备类型</Label>
                  {deviceTypes.length > 0 ? (
                    <Select defaultValue={selectedDevice?.deviceTypeId}>
                      <SelectTrigger>
                        <SelectValue placeholder="选择设备类型" />
                      </SelectTrigger>
                      <SelectContent>
                        {deviceTypes.map(type => (
                          <SelectItem key={type.id} value={type.id}>
                            {type.name}
                          </SelectItem>
                        ))}
                      </SelectContent>
                    </Select>
                  ) : (
                    <Select>
                      <SelectTrigger>
                        <SelectValue placeholder="选择设备类型" />
                      </SelectTrigger>
                      <SelectContent>
                        <SelectItem value="weather_station">气象站</SelectItem>
                        <SelectItem value="soil_sensor">土壤传感器</SelectItem>
                        <SelectItem value="camera">摄像头</SelectItem>
                        <SelectItem value="water_sensor">水质传感器</SelectItem>
                        <SelectItem value="env_station">环境监测站</SelectItem>
                      </SelectContent>
                    </Select>
                  )}
                </div>
              </div>

              <div className="grid grid-cols-2 gap-4">
                <div>
                  <Label>制造商</Label>
                  <Select defaultValue={selectedDevice?.manufacturer}>
                    <SelectTrigger>
                      <SelectValue placeholder="选择制造商" />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="华为">华为</SelectItem>
                      <SelectItem value="中科院">中科院</SelectItem>
                      <SelectItem value="海康威视">海康威视</SelectItem>
                      <SelectItem value="绿盟科技">绿盟科技</SelectItem>
                      <SelectItem value="其他">其他</SelectItem>
                    </SelectContent>
                  </Select>
                </div>
                <div>
                  <Label>设备型号</Label>
                  <Input placeholder="如: HW-WS-Pro" defaultValue={selectedDevice?.model} />
                </div>
              </div>
            </div>

            {/* 位置信息 */}
            <div className="space-y-4">
              <h4 className="text-lg font-medium flex items-center gap-2">
                <MapPin className="w-4 h-4" />
                位置信息
              </h4>
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <Label>所属地块</Label>
                  <Select defaultValue={selectedDevice?.fieldId}>
                    <SelectTrigger>
                      <SelectValue placeholder="选择所属地块" />
                    </SelectTrigger>
                    <SelectContent>
                      {fieldsList.map(field => (
                        <SelectItem key={field.id} value={field.id}>
                          {field.name} ({field.cropType} · {field.area}亩)
                        </SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                  <p className="text-xs text-muted-foreground mt-1">
                    选择地块后，设备位置将自动从地块信息中获取
                  </p>
                </div>
                <div>
                  <Label>安装位置</Label>
                  <Input placeholder="如: 1号大棚北侧" defaultValue={selectedDevice?.location} />
                </div>
              </div>
            </div>

            {/* 通信配置 */}
            <div className="space-y-4">
              <h4 className="text-lg font-medium flex items-center gap-2">
                <Wifi className="w-4 h-4" />
                通信配置
              </h4>
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <Label>通信协议</Label>
                  <Select defaultValue={selectedDevice?.protocol}>
                    <SelectTrigger>
                      <SelectValue placeholder="选择通信协议" />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="MQTT">MQTT</SelectItem>
                      <SelectItem value="HTTP">HTTP</SelectItem>
                      <SelectItem value="CoAP">CoAP</SelectItem>
                      <SelectItem value="WebSocket">WebSocket</SelectItem>
                    </SelectContent>
                  </Select>
                </div>
                <div>
                  <Label>数据采集频率</Label>
                  <Select defaultValue={selectedDevice?.dataFrequency}>
                    <SelectTrigger>
                      <SelectValue placeholder="选择数据频率" />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="实时">实时</SelectItem>
                      <SelectItem value="每1分钟">每1分钟</SelectItem>
                      <SelectItem value="每5分钟">每5分钟</SelectItem>
                      <SelectItem value="每10分钟">每10分钟</SelectItem>
                      <SelectItem value="每30分钟">每30分钟</SelectItem>
                      <SelectItem value="每小时">每小时</SelectItem>
                    </SelectContent>
                  </Select>
                </div>
              </div>

              <div className="grid grid-cols-2 gap-4">
                <div>
                  <Label>IP地址</Label>
                  <Input placeholder="如: 192.168.1.100" defaultValue={selectedDevice?.ipAddress} />
                </div>
                <div>
                  <Label>MQTT主题</Label>
                  <Input placeholder="如: farm/weather/station01" defaultValue={selectedDevice?.mqttTopic} />
                </div>
              </div>
            </div>

            {/* 传感器配置 */}
            <div className="space-y-4">
              <h4 className="text-lg font-medium flex items-center gap-2">
                <Gauge className="w-4 h-4" />
                传感器配置
              </h4>
              <div className="space-y-3">
                <div className="grid grid-cols-4 gap-4 text-sm font-medium text-muted-foreground">
                  <div>传感器名称</div>
                  <div>数据单位</div>
                  <div>正常范围</div>
                  <div>启用状态</div>
                </div>

                {/* 默认传感器配置 */}
                <div className="grid grid-cols-4 gap-4 items-center">
                  <Input placeholder="温度" defaultValue="温度" />
                  <Input placeholder="℃" defaultValue="℃" />
                  <Input placeholder="-10~40" defaultValue="-10~40" />
                  <Switch defaultChecked />
                </div>
                <div className="grid grid-cols-4 gap-4 items-center">
                  <Input placeholder="湿度" defaultValue="湿度" />
                  <Input placeholder="%" defaultValue="%" />
                  <Input placeholder="0~100" defaultValue="0~100" />
                  <Switch defaultChecked />
                </div>
                <div className="grid grid-cols-4 gap-4 items-center">
                  <Input placeholder="气压" defaultValue="气压" />
                  <Input placeholder="hPa" defaultValue="hPa" />
                  <Input placeholder="950~1050" defaultValue="950~1050" />
                  <Switch defaultChecked />
                </div>
              </div>
              <Button variant="outline" className="w-full">
                <Plus className="w-4 h-4 mr-2" />
                添加传感器
              </Button>
            </div>

            {/* 绑定配置 */}
            <div className="space-y-4">
              <h4 className="text-lg font-medium flex items-center gap-2">
                <Link className="w-4 h-4" />
                绑定配置
              </h4>
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <Label>绑定状态</Label>
                  <Select defaultValue={selectedDevice?.bindingStatus}>
                    <SelectTrigger>
                      <SelectValue placeholder="选择绑定状态" />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="未绑定">未绑定</SelectItem>
                      <SelectItem value="已绑定">已绑定</SelectItem>
                    </SelectContent>
                  </Select>
                </div>
                <div>
                  <Label>绑定系统</Label>
                  <Select defaultValue={selectedDevice?.bindingSystem}>
                    <SelectTrigger>
                      <SelectValue placeholder="选择绑定系统" />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="智能灌溉控制系统">智能灌溉控制系统</SelectItem>
                      <SelectItem value="视频监控系统">视频监控系统</SelectItem>
                      <SelectItem value="环境监测系统">环境监测系统</SelectItem>
                      <SelectItem value="生产管理系统">生产管理系统</SelectItem>
                    </SelectContent>
                  </Select>
                </div>
              </div>
            </div>

            {/* 备注信息 */}
            <div className="space-y-4">
              <h4 className="text-lg font-medium flex items-center gap-2">
                <FileText className="w-4 h-4" />
                备注信息
              </h4>
              <div>
                <Label>设备描述</Label>
                <Textarea
                  placeholder="请输入设备的详细描述信息，包括功能特点、安装要求等"
                  className="resize-none"
                  rows={3}
                  defaultValue={selectedDevice ? `${selectedDevice.manufacturer} ${selectedDevice.model}，${selectedDevice.sensors.length}个传感器` : ''}
                />
              </div>
            </div>

            {/* 启用和测试 */}
            <div className="flex items-center justify-between p-4 bg-green-50 dark:bg-green-950/30 rounded-lg border border-green-200 dark:border-green-800">
              <div className="flex items-center gap-2">
                <Switch defaultChecked />
                <span className="text-sm font-medium">启用设备</span>
              </div>
              <Button size="sm" variant="outline" onClick={handleTestConnection}>
                <Link className="w-3 h-3 mr-1" />
                测试连接
              </Button>
            </div>
          </div>

          <div className="flex justify-end gap-3 pt-4 border-t">
            <Button variant="outline" onClick={() => setShowDeviceDialog(false)}>
              取消
            </Button>
            <Button className="bg-green-600 hover:bg-green-700" onClick={handleSaveDevice}>
              {selectedDevice ? '保存配置' : '添加设备'}
            </Button>
          </div>
        </DialogContent>
      </Dialog>

      {/* 手动上传数据对话框 */}
      <Dialog open={showUploadDialog} onOpenChange={setShowUploadDialog}>
        <DialogContent className="max-w-3xl max-h-[90vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle className="flex items-center gap-2">
              <Upload className="w-5 h-5 text-info" />
              手动上传数据
            </DialogTitle>
            <DialogDescription>
              支持CSV、JSON、XML等多种格式数据上传，支持多文件同时上传，系统将自动进行格式适配和质量校验
            </DialogDescription>
          </DialogHeader>

          <div className="space-y-4">
            {/* 数据源名称 */}
            <div>
              <Label>数据源名称</Label>
              <Input placeholder="输入数据源名称，如：2024年10月气象监测数据" />
            </div>

            {/* 数据类型选择 */}
            <div>
              <Label>数据类型</Label>
              <Select defaultValue="气象数据">
                <SelectTrigger>
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="气象数据">气象数据</SelectItem>
                  <SelectItem value="卫星遥感">卫星遥感影像</SelectItem>
                  <SelectItem value="土壤数据">土壤监测数据</SelectItem>
                  <SelectItem value="作物生长">作物生长数据</SelectItem>
                  <SelectItem value="其他">其他数据</SelectItem>
                </SelectContent>
              </Select>
            </div>

            {/* 数据提供商 */}
            <div>
              <Label>数据提供商</Label>
              <Input placeholder="输入数据提供商名称，如：中国气象局、农业部监测中心等" />
            </div>

            {/* 描述说明 */}
            <div>
              <Label>描述说明</Label>
              <Textarea 
                placeholder="输入数据源的描述信息，包括数据来源、采集时间、数据范围等..." 
                rows={3}
              />
            </div>

            {/* 数据格式 */}
            <div>
              <Label>数据格式</Label>
              <Select defaultValue="CSV">
                <SelectTrigger>
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="CSV">CSV（逗号分隔）</SelectItem>
                  <SelectItem value="JSON">JSON</SelectItem>
                  <SelectItem value="XML">XML</SelectItem>
                  <SelectItem value="GeoJSON">GeoJSON（地理数据）</SelectItem>
                  <SelectItem value="Excel">Excel（.xlsx）</SelectItem>
                </SelectContent>
              </Select>
            </div>

            {/* 文件上传区域 */}
            <div className="border-2 border-dashed rounded-lg p-8 text-center">
              <input
                type="file"
                id="file-upload"
                className="hidden"
                onChange={handleFileUpload}
                accept=".csv,.json,.xml,.xlsx,.geojson"
                multiple
              />
              <label htmlFor="file-upload" className="cursor-pointer">
                <div className="flex flex-col items-center gap-2">
                  <Upload className="w-12 h-12 text-info" />
                  {uploadedFiles.length === 0 ? (
                    <div>
                      <p className="font-medium">点击上传或拖拽文件到此处</p>
                      <p className="text-xs text-muted-foreground mt-1">
                        支持 CSV, JSON, XML, GeoJSON, Excel 格式，可同时上传多个文件
                      </p>
                    </div>
                  ) : (
                    <div className="w-full">
                      <p className="font-medium text-success mb-2">已选择 {uploadedFiles.length} 个文件</p>
                    </div>
                  )}
                </div>
              </label>
            </div>

            {/* 已上传文件列表 */}
            {uploadedFiles.length > 0 && (
              <Card className="p-4">
                <h4 className="text-sm font-medium mb-3">已选择的文件</h4>
                <div className="space-y-2">
                  {uploadedFiles.map((file, index) => (
                    <div key={index} className="flex items-center justify-between p-2 bg-muted rounded">
                      <div className="flex items-center gap-2 flex-1">
                        <FileText className="w-4 h-4 text-info" />
                        <div className="flex-1">
                          <p className="text-sm font-medium">{file.name}</p>
                          <p className="text-xs text-muted-foreground">
                            {(file.size / 1024).toFixed(2)} KB
                          </p>
                        </div>
                      </div>
                      <Button
                        size="sm"
                        variant="ghost"
                        onClick={() => handleRemoveFile(index)}
                      >
                        <XCircle className="w-4 h-4 text-destructive" />
                      </Button>
                    </div>
                  ))}
                </div>
              </Card>
            )}

            {/* 上传进度 */}
            {uploadProgress > 0 && uploadProgress < 100 && (
              <div>
                <div className="flex items-center justify-between mb-2">
                  <span className="text-sm">上传进度</span>
                  <span className="text-sm font-medium">{uploadProgress}%</span>
                </div>
                <Progress value={uploadProgress} className="h-2" />
              </div>
            )}

            {/* 数据校验选项 */}
            <Card className="p-4 bg-info/10 border-info/30">
              <h4 className="text-sm mb-3 flex items-center gap-2">
                <CheckCircle2 className="w-4 h-4 text-info" />
                数据质量校验
              </h4>
              <div className="space-y-2">
                <div className="flex items-center justify-between">
                  <span className="text-sm">格式适配与转换</span>
                  <Switch defaultChecked />
                </div>
                <div className="flex items-center justify-between">
                  <span className="text-sm">缺失值检测</span>
                  <Switch defaultChecked />
                </div>
                <div className="flex items-center justify-between">
                  <span className="text-sm">异常值过滤</span>
                  <Switch defaultChecked />
                </div>
                <div className="flex items-center justify-between">
                  <span className="text-sm">时间戳校验</span>
                  <Switch defaultChecked />
                </div>
              </div>
            </Card>

            {/* 数据预览 */}
            {uploadedFile && uploadProgress === 100 && (
              <Card className="p-4">
                <div className="flex items-center justify-between mb-3">
                  <h4 className="text-sm font-medium">数据预览</h4>
                  <Button size="sm" variant="outline" onClick={handleDataPreview}>
                    <Eye className="w-3 h-3 mr-1" />
                    查看详情
                  </Button>
                </div>
                <div className="text-xs space-y-2 text-muted-foreground">
                  <div className="flex justify-between">
                    <span>数据记录数：</span>
                    <span className="font-medium text-foreground">1,245 条</span>
                  </div>
                  <div className="flex justify-between">
                    <span>数据字段数：</span>
                    <span className="font-medium text-foreground">12 个</span>
                  </div>
                  <div className="flex justify-between">
                    <span>完整性评分：</span>
                    <Badge className="bg-success/10 text-success">98.5%</Badge>
                  </div>
                  <div className="flex justify-between">
                    <span>时间范围：</span>
                    <span className="font-medium text-foreground">2024-10-01 至 2024-10-15</span>
                  </div>
                </div>
              </Card>
            )}
          </div>

          <DialogFooter>
            <Button variant="outline" onClick={() => {
              setShowUploadDialog(false);
              setUploadedFile(null);
              setUploadedFiles([]);
              setUploadProgress(0);
            }}>
              取消
            </Button>
            <Button 
              className="bg-info hover:bg-info/90" 
              disabled={uploadedFiles.length === 0 || uploadProgress < 100}
              onClick={() => {
                handleDataValidation();
                setShowUploadDialog(false);
                setUploadedFile(null);
                setUploadedFiles([]);
                setUploadProgress(0);
              }}
            >
              <CheckCircle2 className="w-4 h-4 mr-2" />
              确认导入 ({uploadedFiles.length}个文件)
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* 数据校验规则对话框 */}
      <Dialog open={showValidationDialog} onOpenChange={setShowValidationDialog}>
        <DialogContent className="max-w-3xl max-h-[90vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle className="flex items-center gap-2">
              <Settings className="w-5 h-5 text-info" />
              数据校验规则配置
            </DialogTitle>
            <DialogDescription>
              配置数据接入时的质量校验规则，确保数据的完整性、准确性和时效性
            </DialogDescription>
          </DialogHeader>

          <div className="space-y-4">
            {/* 气象数据校验规则 */}
            <Card className="p-4">
              <h4 className="mb-3 flex items-center gap-2">
                <Cloud className="w-4 h-4 text-info" />
                气象数据校验规则
              </h4>
              <div className="space-y-3">
                <div className="grid grid-cols-2 gap-4">
                  <div>
                    <Label className="text-xs">温度范围 (℃)</Label>
                    <div className="flex gap-2 items-center mt-1">
                      <Input placeholder="-30" className="h-8" />
                      <span className="text-xs">至</span>
                      <Input placeholder="50" className="h-8" />
                    </div>
                  </div>
                  <div>
                    <Label className="text-xs">湿度范围 (%)</Label>
                    <div className="flex gap-2 items-center mt-1">
                      <Input placeholder="0" className="h-8" />
                      <span className="text-xs">至</span>
                      <Input placeholder="100" className="h-8" />
                    </div>
                  </div>
                </div>
                <div className="grid grid-cols-2 gap-4">
                  <div>
                    <Label className="text-xs">降水量范围 (mm)</Label>
                    <div className="flex gap-2 items-center mt-1">
                      <Input placeholder="0" className="h-8" />
                      <span className="text-xs">至</span>
                      <Input placeholder="500" className="h-8" />
                    </div>
                  </div>
                  <div>
                    <Label className="text-xs">风速范围 (m/s)</Label>
                    <div className="flex gap-2 items-center mt-1">
                      <Input placeholder="0" className="h-8" />
                      <span className="text-xs">至</span>
                      <Input placeholder="50" className="h-8" />
                    </div>
                  </div>
                </div>
              </div>
            </Card>

            {/* 卫星遥感数据校验规则 */}
            <Card className="p-4">
              <h4 className="mb-3 flex items-center gap-2">
                <Satellite className="w-4 h-4 text-accent" />
                卫星遥感数据校验规则
              </h4>
              <div className="space-y-3">
                <div className="grid grid-cols-2 gap-4">
                  <div>
                    <Label className="text-xs">NDVI范围</Label>
                    <div className="flex gap-2 items-center mt-1">
                      <Input placeholder="-1.0" className="h-8" />
                      <span className="text-xs">至</span>
                      <Input placeholder="1.0" className="h-8" />
                    </div>
                  </div>
                  <div>
                    <Label className="text-xs">影像分辨率要求 (米)</Label>
                    <Select defaultValue="10">
                      <SelectTrigger className="h-8">
                        <SelectValue />
                      </SelectTrigger>
                      <SelectContent>
                        <SelectItem value="1">≤ 1米</SelectItem>
                        <SelectItem value="5">≤ 5米</SelectItem>
                        <SelectItem value="10">≤ 10米</SelectItem>
                        <SelectItem value="30">≤ 30米</SelectItem>
                      </SelectContent>
                    </Select>
                  </div>
                </div>
                <div>
                  <Label className="text-xs">云量覆盖率上限 (%)</Label>
                  <Input placeholder="20" className="h-8 mt-1" />
                </div>
              </div>
            </Card>

            {/* 通用校验规则 */}
            <Card className="p-4">
              <h4 className="mb-3 flex items-center gap-2">
                <CheckCircle2 className="w-4 h-4 text-success" />
                通用质量控制规则
              </h4>
              <div className="space-y-3">
                <div className="flex items-center justify-between p-3 bg-muted rounded">
                  <div>
                    <p className="text-sm font-medium">数据完整性检查</p>
                    <p className="text-xs text-muted-foreground">检测缺失字段和空值</p>
                  </div>
                  <Switch defaultChecked />
                </div>
                <div className="flex items-center justify-between p-3 bg-muted rounded">
                  <div>
                    <p className="text-sm font-medium">时间戳连续性校验</p>
                    <p className="text-xs text-muted-foreground">确保时间序列数据的连续性</p>
                  </div>
                  <Switch defaultChecked />
                </div>
                <div className="flex items-center justify-between p-3 bg-muted rounded">
                  <div>
                    <p className="text-sm font-medium">异常值检测 (3σ原则)</p>
                    <p className="text-xs text-muted-foreground">自动标记超出3倍标准差的数据</p>
                  </div>
                  <Switch defaultChecked />
                </div>
                <div className="flex items-center justify-between p-3 bg-muted rounded">
                  <div>
                    <p className="text-sm font-medium">重复数据检测</p>
                    <p className="text-xs text-muted-foreground">基于时间戳和关键字段去重</p>
                  </div>
                  <Switch defaultChecked />
                </div>
                <div>
                  <Label className="text-xs">数据时效性要求</Label>
                  <Select defaultValue="24h">
                    <SelectTrigger className="h-8 mt-1">
                      <SelectValue />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="realtime">实时数据 (5分钟内)</SelectItem>
                      <SelectItem value="1h">1小时内</SelectItem>
                      <SelectItem value="24h">24小时内</SelectItem>
                      <SelectItem value="7d">7天内</SelectItem>
                      <SelectItem value="none">无时效要求</SelectItem>
                    </SelectContent>
                  </Select>
                </div>
              </div>
            </Card>

            {/* 自动处理策略 */}
            <Card className="p-4 bg-warning/10 border-warning/30">
              <h4 className="mb-3 text-sm font-medium text-warning">
                数据质量问题自动处理策略
              </h4>
              <div className="space-y-2">
                <div className="flex items-center justify-between">
                  <span className="text-xs text-warning-muted-foreground">缺失值自动填充（线性插值）</span>
                  <Switch />
                </div>
                <div className="flex items-center justify-between">
                  <span className="text-xs text-warning-muted-foreground">异常值自动剔除</span>
                  <Switch />
                </div>
                <div className="flex items-center justify-between">
                  <span className="text-xs text-warning-muted-foreground">超时数据自动丢弃</span>
                  <Switch defaultChecked />
                </div>
                <div className="flex items-center justify-between">
                  <span className="text-xs text-warning-muted-foreground">质量问题告警通知</span>
                  <Switch defaultChecked />
                </div>
              </div>
            </Card>
          </div>

          <DialogFooter>
            <Button variant="outline" onClick={() => setShowValidationDialog(false)}>
              取消
            </Button>
            <Button className="bg-info hover:bg-info/90" onClick={() => {
              toast.success('数据校验规则已保存');
              setShowValidationDialog(false);
            }}>
              保存规则
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* 数据预览对话框 */}
      <Dialog open={showDataPreviewDialog} onOpenChange={setShowDataPreviewDialog}>
        <DialogContent className="max-w-5xl max-h-[90vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle className="flex items-center gap-2">
              <Eye className="w-5 h-5 text-info" />
              数据预览与质量分析
            </DialogTitle>
            <DialogDescription>
              查看上传数据的详细内容和质量分析报告
            </DialogDescription>
          </DialogHeader>

          <div className="space-y-4">
            {/* 质量评分 */}
            <div className="grid grid-cols-4 gap-4">
              <Card className="p-4 bg-success/10">
                <div className="text-center">
                  <div className="text-2xl text-success mb-1">98.5%</div>
                  <p className="text-xs text-muted-foreground">完整性</p>
                </div>
              </Card>
              <Card className="p-4 bg-info/10">
                <div className="text-center">
                  <div className="text-2xl text-info mb-1">97.2%</div>
                  <p className="text-xs text-muted-foreground">准确性</p>
                </div>
              </Card>
              <Card className="p-4 bg-accent/20">
                <div className="text-center">
                  <div className="text-2xl text-accent mb-1">100%</div>
                  <p className="text-xs text-muted-foreground">时效性</p>
                </div>
              </Card>
              <Card className="p-4 bg-warning/10">
                <div className="text-center">
                  <div className="text-2xl text-warning mb-1">96.8%</div>
                  <p className="text-xs text-muted-foreground">一致性</p>
                </div>
              </Card>
            </div>

            {/* 数据统计 */}
            <Card className="p-4">
              <h4 className="mb-3 text-sm font-medium">数据统计信息</h4>
              <div className="grid grid-cols-3 gap-4 text-xs">
                <div className="flex justify-between">
                  <span className="text-muted-foreground">总记录数：</span>
                  <span className="font-medium">1,245</span>
                </div>
                <div className="flex justify-between">
                  <span className="text-muted-foreground">字段数：</span>
                  <span className="font-medium">12</span>
                </div>
                <div className="flex justify-between">
                  <span className="text-muted-foreground">有效记录：</span>
                  <span className="font-medium text-success">1,227</span>
                </div>
                <div className="flex justify-between">
                  <span className="text-muted-foreground">缺失值：</span>
                  <span className="font-medium text-warning">18</span>
                </div>
                <div className="flex justify-between">
                  <span className="text-muted-foreground">异常值：</span>
                  <span className="font-medium text-destructive">12</span>
                </div>
                <div className="flex justify-between">
                  <span className="text-muted-foreground">重复记录：</span>
                  <span className="font-medium">0</span>
                </div>
              </div>
            </Card>

            {/* 数据样本预览 */}
            <Card className="p-4">
              <h4 className="mb-3 text-sm font-medium">数据样本（前10条）</h4>
              <div className="overflow-x-auto">
                <Table>
                  <TableHeader>
                    <TableRow>
                      <TableHead>时间戳</TableHead>
                      <TableHead>温度(℃)</TableHead>
                      <TableHead>湿度(%)</TableHead>
                      <TableHead>降水(mm)</TableHead>
                      <TableHead>风速(m/s)</TableHead>
                      <TableHead>气压(hPa)</TableHead>
                      <TableHead>状态</TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {[
                      { time: '2024-10-15 14:00', temp: 24.5, humidity: 68, rain: 0, wind: 3.2, pressure: 1013, status: '正常' },
                      { time: '2024-10-15 13:00', temp: 23.8, humidity: 70, rain: 0, wind: 2.8, pressure: 1014, status: '正常' },
                      { time: '2024-10-15 12:00', temp: 23.2, humidity: 72, rain: 0.5, wind: 3.5, pressure: 1012, status: '正常' },
                      { time: '2024-10-15 11:00', temp: 22.5, humidity: 75, rain: 1.2, wind: 4.2, pressure: 1011, status: '正常' },
                      { time: '2024-10-15 10:00', temp: 21.8, humidity: 78, rain: 0, wind: 3.0, pressure: 1013, status: '正常' },
                    ].map((row, idx) => (
                      <TableRow key={idx}>
                        <TableCell className="text-xs">{row.time}</TableCell>
                        <TableCell className="text-xs">{row.temp}</TableCell>
                        <TableCell className="text-xs">{row.humidity}</TableCell>
                        <TableCell className="text-xs">{row.rain}</TableCell>
                        <TableCell className="text-xs">{row.wind}</TableCell>
                        <TableCell className="text-xs">{row.pressure}</TableCell>
                        <TableCell>
                          <Badge className="bg-success/10 text-success text-xs">
                            {row.status}
                          </Badge>
                        </TableCell>
                      </TableRow>
                    ))}
                  </TableBody>
                </Table>
              </div>
            </Card>

            {/* 质量问题清单 */}
            <Card className="p-4 bg-warning/10 border-warning/30">
              <h4 className="mb-3 text-sm font-medium text-warning">
                数据质量问题清单
              </h4>
              <div className="space-y-2 text-xs">
                <div className="flex items-start gap-2">
                  <AlertCircle className="w-4 h-4 text-warning flex-shrink-0 mt-0.5" />
                  <div>
                    <p className="font-medium">缺失值检测：</p>
                    <p className="text-muted-foreground">
                      第128行温度字段缺失，第345行湿度字段缺失，共18处
                    </p>
                  </div>
                </div>
                <div className="flex items-start gap-2">
                  <AlertCircle className="w-4 h-4 text-warning flex-shrink-0 mt-0.5" />
                  <div>
                    <p className="font-medium">异常值检测：</p>
                    <p className="text-muted-foreground">
                      第256行风速数值异常（52.3 m/s），超出合理范围，共12处
                    </p>
                  </div>
                </div>
                <div className="flex items-start gap-2">
                  <CheckCircle className="w-4 h-4 text-success flex-shrink-0 mt-0.5" />
                  <div>
                    <p className="font-medium text-success">时间连续性：</p>
                    <p className="text-success">时间序列完整，无中断</p>
                  </div>
                </div>
              </div>
            </Card>
          </div>

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

      {/* 设备详情对话框 */}
      <Dialog open={showDeviceDetailDialog} onOpenChange={setShowDeviceDetailDialog}>
        <DialogContent className="max-w-5xl max-h-[90vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle>设备详情 - {selectedDevice?.name}</DialogTitle>
            <DialogDescription>
              查看设备详细信息、传感器配置和运行状态
            </DialogDescription>
          </DialogHeader>

          <div className="space-y-6">
            {/* 设备基本信息 */}
            <Card className="p-4">
              <h4 className="mb-4 flex items-center gap-2">
                <Wifi className="w-4 h-4 text-success" />
                基本信息
              </h4>
              <div className="grid grid-cols-3 gap-4">
                <div>
                  <Label className="text-xs">设备编号</Label>
                  <p className="mt-1 text-sm font-medium">{selectedDevice?.code}</p>
                </div>
                <div>
                  <Label className="text-xs">设备名称</Label>
                  <p className="mt-1 text-sm font-medium">{selectedDevice?.name}</p>
                </div>
                <div>
                  <Label className="text-xs">设备类型</Label>
                  <p className="mt-1">
                    <Badge variant="outline">{selectedDevice?.type}</Badge>
                  </p>
                </div>
                <div>
                  <Label className="text-xs">设备型号</Label>
                  <p className="mt-1 text-sm">{selectedDevice?.model}</p>
                </div>
                <div>
                  <Label className="text-xs">生产厂家</Label>
                  <p className="mt-1 text-sm">{selectedDevice?.manufacturer}</p>
                </div>
                <div>
                  <Label className="text-xs">所属地块</Label>
                  <p className="mt-1">
                    <Badge variant="outline" className="bg-success/10 text-success border-success/30">
                      {selectedDevice?.fieldName}
                    </Badge>
                  </p>
                </div>
                <div>
                  <Label className="text-xs">安装位置</Label>
                  <p className="mt-1 text-sm flex items-center gap-1">
                    <MapPin className="w-3 h-3 text-muted-foreground" />
                    {selectedDevice?.location}
                  </p>
                </div>
                <div>
                  <Label className="text-xs">通信协议</Label>
                  <p className="mt-1">
                    <Badge variant="outline">{selectedDevice?.protocol}</Badge>
                  </p>
                </div>
                <div>
                  <Label className="text-xs">上报频率</Label>
                  <p className="mt-1 text-sm">{selectedDevice?.dataFrequency}</p>
                </div>
                <div>
                  <Label className="text-xs">设备状态</Label>
                  <p className="mt-1">
                    <Badge className={getStatusColor(selectedDevice?.status || '在线')}>
                      {selectedDevice?.status}
                    </Badge>
                  </p>
                </div>
              </div>
            </Card>

            {/* 通信状态 */}
            <Card className="p-4">
              <h4 className="mb-4 flex items-center gap-2">
                <Signal className="w-4 h-4 text-info" />
                通信状态
              </h4>
              <div className="grid grid-cols-4 gap-4">
                {selectedDevice?.signalStrength !== undefined && (
                  <div>
                    <Label className="text-xs">信号强度</Label>
                    <div className="mt-2 flex items-center gap-2">
                      <Progress value={selectedDevice.signalStrength} className="flex-1" />
                      <span className="text-sm font-medium">{selectedDevice.signalStrength}%</span>
                    </div>
                  </div>
                )}
                {selectedDevice?.batteryLevel !== undefined && (
                  <div>
                    <Label className="text-xs">电池电量</Label>
                    <div className="mt-2 flex items-center gap-2">
                      <Progress value={selectedDevice.batteryLevel} className="flex-1" />
                      <span className="text-sm font-medium">{selectedDevice.batteryLevel}%</span>
                    </div>
                  </div>
                )}
                <div>
                  <Label className="text-xs">最后上报时间</Label>
                  <p className="mt-1 text-sm flex items-center gap-1">
                    <Clock className="w-3 h-3 text-muted-foreground" />
                    {selectedDevice?.lastReportTime}
                  </p>
                </div>
                <div>
                  <Label className="text-xs">在线时长</Label>
                  <p className="mt-1 text-sm">48小时15分</p>
                </div>
              </div>

              {/* 协议配置信息 */}
              <div className="mt-4 p-3 bg-muted rounded-md">
                <h5 className="text-xs font-medium text-muted-foreground mb-2">协议配置</h5>
                <div className="grid grid-cols-2 gap-3 text-xs">
                  {selectedDevice?.protocol === 'MQTT' && (
                    <>
                      <div>
                        <span className="text-muted-foreground">MQTT主题:</span>
                        <span className="ml-2 font-mono">{selectedDevice.mqttTopic || 'farm/sensors/data'}</span>
                      </div>
                      <div>
                        <span className="text-muted-foreground">Broker地址:</span>
                        <span className="ml-2 font-mono">mqtt.farm.com:1883</span>
                      </div>
                    </>
                  )}
                  {selectedDevice?.protocol === 'HTTP' && (
                    <>
                      <div>
                        <span className="text-muted-foreground">API端点:</span>
                        <span className="ml-2 font-mono">{selectedDevice.ipAddress || 'http://192.168.1.100/api/data'}</span>
                      </div>
                      <div>
                        <span className="text-muted-foreground">请求方式:</span>
                        <span className="ml-2">POST</span>
                      </div>
                    </>
                  )}
                </div>
              </div>
            </Card>

            {/* 传感器配置 */}
            <Card className="p-4">
              <h4 className="mb-4 flex items-center gap-2">
                <Gauge className="w-4 h-4 text-accent" />
                传感器配置
              </h4>
              {selectedDevice?.sensors && selectedDevice.sensors.length > 0 && (
                <Card className="p-4 bg-muted">
                  <div className="grid grid-cols-4 gap-4">
                    <div>
                      <Label className="text-xs">传感器名称</Label>
                      <p className="mt-1 text-sm font-medium">{selectedDevice.sensors[0].name}</p>
                    </div>
                    <div>
                      <Label className="text-xs">当前读数</Label>
                      <p className="mt-1 text-sm">
                        <span className="font-medium text-success">{selectedDevice.sensors[0].currentValue}</span>
                        <span className="text-muted-foreground ml-1">{selectedDevice.sensors[0].unit}</span>
                      </p>
                    </div>
                    <div>
                      <Label className="text-xs">正常范围</Label>
                      <p className="mt-1 text-xs text-muted-foreground">{selectedDevice.sensors[0].normalRange}</p>
                    </div>
                    <div>
                      <Label className="text-xs">状态</Label>
                      <p className="mt-1">
                        <Badge className="bg-success/10 text-success text-xs">正常</Badge>
                      </p>
                    </div>
                  </div>
                </Card>
              )}
            </Card>

            {/* 数据采集统计 */}
            <Card className="p-4">
              <h4 className="mb-4 flex items-center gap-2">
                <BarChart3 className="w-4 h-4 text-info" />
                数据采集统计（最近24小时）
              </h4>
              <div className="grid grid-cols-4 gap-4">
                <div className="p-3 bg-info/10 rounded-md">
                  <p className="text-xs text-muted-foreground">总采集次数</p>
                  <p className="text-2xl text-info mt-1">2,880</p>
                  <p className="text-xs text-muted-foreground mt-1">平均每分钟2次</p>
                </div>
                <div className="p-3 bg-success/10 rounded-md">
                  <p className="text-xs text-muted-foreground">有效数据</p>
                  <p className="text-2xl text-success mt-1">2,856</p>
                  <p className="text-xs text-success mt-1">99.2%成功率</p>
                </div>
                <div className="p-3 bg-warning/10 rounded-md">
                  <p className="text-xs text-muted-foreground">异常数据</p>
                  <p className="text-2xl text-warning mt-1">18</p>
                  <p className="text-xs text-warning mt-1">0.6%异常率</p>
                </div>
                <div className="p-3 bg-destructive/10 rounded-md">
                  <p className="text-xs text-muted-foreground">丢失数据</p>
                  <p className="text-2xl text-destructive mt-1">6</p>
                  <p className="text-xs text-destructive mt-1">0.2%丢失率</p>
                </div>
              </div>

              {/* 数据采集趋势小图 */}
              <div className="mt-4">
                <ResponsiveContainer width="100%" height={150}>
                  <AreaChart data={[
                    { time: '00:00', count: 120 },
                    { time: '04:00', count: 118 },
                    { time: '08:00', count: 125 },
                    { time: '12:00', count: 122 },
                    { time: '16:00', count: 119 },
                    { time: '20:00', count: 121 },
                    { time: '24:00', count: 120 },
                  ]}>
                    <CartesianGrid strokeDasharray="3 3" />
                    <XAxis dataKey="time" />
                    <YAxis />
                    <RechartsTooltip />
                    <Area type="monotone" dataKey="count" stroke="#3b82f6" fill="#93c5fd" />
                  </AreaChart>
                </ResponsiveContainer>
              </div>
            </Card>

          </div>

          <DialogFooter>
            <Button variant="outline" onClick={() => setShowDeviceDetailDialog(false)}>
              关闭
            </Button>
            <Button onClick={() => {
              setShowDeviceDetailDialog(false);
              setShowDeviceDialog(true);
            }}>
              <Edit className="w-4 h-4 mr-2" />
              编辑配置
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* 实时数据监控对话框 */}
      <Dialog open={showRealtimeDataDialog} onOpenChange={setShowRealtimeDataDialog}>
        <DialogContent className="max-w-6xl max-h-[90vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle>实时数据监控 - {selectedDevice?.name}</DialogTitle>
            <DialogDescription>
              查看设备实时采集的传感器数据和数据流状态
            </DialogDescription>
          </DialogHeader>

          <div className="space-y-6">
            {/* 数据流状态 */}
            <div className="grid grid-cols-4 gap-4">
              <Card className="p-4 bg-gradient-to-br from-info/10 to-info/20">
                <div className="flex items-center gap-3">
                  <div className="w-10 h-10 bg-info rounded-full flex items-center justify-center">
                    <Activity className="w-5 h-5 text-white" />
                  </div>
                  <div>
                    <p className="text-xs text-muted-foreground">数据流状态</p>
                    <p className="text-lg text-info flex items-center gap-1">
                      正常
                      <span className="w-2 h-2 bg-success rounded-full animate-pulse"></span>
                    </p>
                  </div>
                </div>
              </Card>

              <Card className="p-4 bg-gradient-to-br from-success/10 to-success/20">
                <div className="flex items-center gap-3">
                  <div className="w-10 h-10 bg-success rounded-full flex items-center justify-center">
                    <Zap className="w-5 h-5 text-white" />
                  </div>
                  <div>
                    <p className="text-xs text-muted-foreground">数据速率</p>
                    <p className="text-lg text-success">2条/分钟</p>
                  </div>
                </div>
              </Card>

              <Card className="p-4 bg-gradient-to-br from-accent/20 to-accent/30">
                <div className="flex items-center gap-3">
                  <div className="w-10 h-10 bg-accent rounded-full flex items-center justify-center">
                    <Clock className="w-5 h-5 text-white" />
                  </div>
                  <div>
                    <p className="text-xs text-muted-foreground">最后更新</p>
                    <p className="text-lg text-accent">2秒前</p>
                  </div>
                </div>
              </Card>

              <Card className="p-4 bg-gradient-to-br from-warning/10 to-warning/20">
                <div className="flex items-center gap-3">
                  <div className="w-10 h-10 bg-warning rounded-full flex items-center justify-center">
                    <TrendingUp className="w-5 h-5 text-white" />
                  </div>
                  <div>
                    <p className="text-xs text-muted-foreground">数据质量</p>
                    <p className="text-lg text-warning">优秀</p>
                  </div>
                </div>
              </Card>
            </div>

            {/* 实时传感器数据 */}
            <Card className="p-4">
              <div className="flex items-center justify-between mb-4">
                <h4 className="flex items-center gap-2">
                  <Gauge className="w-4 h-4 text-success" />
                  实时传感器读数
                </h4>
                <Button size="sm" variant="outline" onClick={() => toast.success('数据已刷新')}>
                  <RefreshCw className="w-3 h-3 mr-1" />
                  刷新
                </Button>
              </div>

              <div className="grid grid-cols-2 gap-4">
                {selectedDevice?.sensors.map((sensor, idx) => (
                  <Card key={idx} className="p-4 bg-gradient-to-br from-muted to-secondary">
                    <div className="flex items-start justify-between">
                      <div className="flex-1">
                        <div className="flex items-center gap-2 mb-2">
                          {sensor.name.includes('温度') && <Thermometer className="w-4 h-4 text-destructive" />}
                          {sensor.name.includes('湿度') && <Droplet className="w-4 h-4 text-info" />}
                          {sensor.name.includes('光照') && <Sun className="w-4 h-4 text-warning" />}
                          {sensor.name.includes('风速') && <Wind className="w-4 h-4 text-muted-foreground" />}
                          {!sensor.name.includes('温度') && !sensor.name.includes('湿度') && !sensor.name.includes('光照') && !sensor.name.includes('风速') && <Gauge className="w-4 h-4 text-muted-foreground" />}
                          <span className="text-sm font-medium">{sensor.name}</span>
                        </div>
                        <div className="flex items-baseline gap-2">
                          <span className="text-3xl font-medium text-success">{sensor.currentValue}</span>
                          <span className="text-sm text-muted-foreground">{sensor.unit}</span>
                        </div>
                        <div className="mt-2 text-xs text-muted-foreground">
                          正常范围: {sensor.normalRange}
                        </div>
                        <div className="mt-2">
                          <div className="flex items-center justify-between text-xs mb-1">
                            <span className="text-muted-foreground">当前值位置</span>
                            <span>正常</span>
                          </div>
                          <Progress value={75} className="h-1.5" />
                        </div>
                      </div>
                      <Badge className="bg-success/10 text-success">正常</Badge>
                    </div>

                    {/* 迷你趋势图 */}
                    <div className="mt-3 h-16">
                      <ResponsiveContainer width="100%" height="100%">
                        <LineChart data={[
                          { time: 1, value: parseFloat(sensor.currentValue) - 2 },
                          { time: 2, value: parseFloat(sensor.currentValue) - 1.5 },
                          { time: 3, value: parseFloat(sensor.currentValue) - 1 },
                          { time: 4, value: parseFloat(sensor.currentValue) - 0.5 },
                          { time: 5, value: parseFloat(sensor.currentValue) },
                        ]}>
                          <Line type="monotone" dataKey="value" stroke="#10b981" strokeWidth={2} dot={false} />
                        </LineChart>
                      </ResponsiveContainer>
                    </div>
                  </Card>
                ))}
              </div>
            </Card>

            {/* 数据采集日志 */}
            <Card className="p-4">
              <h4 className="mb-4 flex items-center gap-2">
                <Clock className="w-4 h-4 text-info" />
                数据采集日志（最近10条）
              </h4>
              <div className="space-y-2 max-h-60 overflow-y-auto">
                {[
                  { time: '2024-10-23 14:32:15', status: 'success', msg: '数据采集成功，所有传感器正常' },
                  { time: '2024-10-23 14:31:45', status: 'success', msg: '数据采集成功，所有传感器正常' },
                  { time: '2024-10-23 14:31:15', status: 'success', msg: '数据采集成功，所有传感器正常' },
                  { time: '2024-10-23 14:30:45', status: 'warning', msg: '湿度传感器读数略低，已标记' },
                  { time: '2024-10-23 14:30:15', status: 'success', msg: '数据采集成功，所有传感器正常' },
                  { time: '2024-10-23 14:29:45', status: 'success', msg: '数据采集成功，所有传感器正常' },
                  { time: '2024-10-23 14:29:15', status: 'success', msg: '数据采集成功，所有传感器正常' },
                  { time: '2024-10-23 14:28:45', status: 'error', msg: '温度传感器通信失败，重试成功' },
                  { time: '2024-10-23 14:28:15', status: 'success', msg: '数据采集成功，所有传感器正常' },
                  { time: '2024-10-23 14:27:45', status: 'success', msg: '数据采集成功，所有传感器正常' },
                ].map((log, idx) => (
                  <div key={idx} className="flex items-start gap-3 p-2 bg-muted rounded text-xs">
                    <Clock className="w-3 h-3 text-muted-foreground flex-shrink-0 mt-0.5" />
                    <div className="flex-1">
                      <div className="flex items-center gap-2">
                        <span className="text-muted-foreground">{log.time}</span>
                        {log.status === 'success' && <CheckCircle className="w-3 h-3 text-success" />}
                        {log.status === 'warning' && <AlertCircle className="w-3 h-3 text-warning" />}
                        {log.status === 'error' && <XCircle className="w-3 h-3 text-destructive" />}
                      </div>
                      <p className="mt-0.5">{log.msg}</p>
                    </div>
                  </div>
                ))}
              </div>
            </Card>

            {/* 历史传感器数据报表 */}
            <Card className="p-4">
              <div className="flex items-center justify-between mb-4">
                <h4 className="flex items-center gap-2">
                  <BarChart3 className="w-4 h-4 text-accent" />
                  历史传感器数据报表
                </h4>
                <div className="flex gap-2">
                  <Button size="sm" variant="outline" onClick={() => toast.success('数据报表已刷新')}>
                    <RefreshCw className="w-3 h-3 mr-1" />
                    刷新
                  </Button>
                  <Button size="sm" className="bg-success hover:bg-success/90" onClick={() => toast.success('历史数据已导出为Excel文件')}>
                    <Download className="w-3 h-3 mr-1" />
                    导出Excel
                  </Button>
                </div>
              </div>

              {/* 时间范围选择 */}
              <div className="flex gap-4 mb-4">
                <div className="flex-1">
                  <Label className="text-xs">开始时间</Label>
                  <Input type="datetime-local" defaultValue="2024-10-23T00:00" className="mt-1" />
                </div>
                <div className="flex-1">
                  <Label className="text-xs">结束时间</Label>
                  <Input type="datetime-local" defaultValue="2024-10-23T23:59" className="mt-1" />
                </div>
                <div className="flex items-end">
                  <Button onClick={() => toast.success('数据已筛选')}>
                    <Search className="w-4 h-4 mr-2" />
                    查询
                  </Button>
                </div>
              </div>

              {/* 历史数据表格 */}
              <div className="overflow-x-auto max-h-80 overflow-y-auto">
                <Table>
                  <TableHeader>
                    <TableRow>
                      <TableHead className="w-40">采集时间</TableHead>
                      {selectedDevice?.sensors.map((sensor, idx) => (
                        <TableHead key={idx}>{sensor.name} ({sensor.unit})</TableHead>
                      ))}
                      <TableHead className="w-24">数据状态</TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {[
                      { time: '2024-10-23 14:30:00', values: ['25.5', '62', '45000', '2.3'], status: '正常' },
                      { time: '2024-10-23 14:00:00', values: ['25.2', '63', '44500', '2.1'], status: '正常' },
                      { time: '2024-10-23 13:30:00', values: ['24.8', '65', '44000', '1.8'], status: '正常' },
                      { time: '2024-10-23 13:00:00', values: ['24.5', '66', '43500', '1.6'], status: '正常' },
                      { time: '2024-10-23 12:30:00', values: ['24.2', '68', '43000', '1.5'], status: '正常' },
                      { time: '2024-10-23 12:00:00', values: ['23.8', '70', '42500', '1.3'], status: '正常' },
                      { time: '2024-10-23 11:30:00', values: ['23.5', '71', '42000', '1.2'], status: '正常' },
                      { time: '2024-10-23 11:00:00', values: ['23.2', '72', '41500', '1.1'], status: '正常' },
                      { time: '2024-10-23 10:30:00', values: ['22.8', '74', '41000', '1.0'], status: '正常' },
                      { time: '2024-10-23 10:00:00', values: ['22.5', '75', '40500', '0.9'], status: '正常' },
                      { time: '2024-10-23 09:30:00', values: ['22.2', '76', '40000', '0.8'], status: '正常' },
                      { time: '2024-10-23 09:00:00', values: ['21.8', '78', '39500', '0.7'], status: '正常' },
                      { time: '2024-10-23 08:30:00', values: ['21.5', '79', '39000', '0.6'], status: '正常' },
                      { time: '2024-10-23 08:00:00', values: ['21.2', '80', '38500', '0.5'], status: '正常' },
                      { time: '2024-10-23 07:30:00', values: ['20.8', '82', '38000', '0.4'], status: '正常' },
                    ].map((record, idx) => (
                      <TableRow key={idx}>
                        <TableCell className="text-xs font-medium">{record.time}</TableCell>
                        {record.values.map((value, vIdx) => (
                          <TableCell key={vIdx} className="text-xs">{value}</TableCell>
                        ))}
                        <TableCell>
                          <Badge className="bg-success/10 text-success text-xs">{record.status}</Badge>
                        </TableCell>
                      </TableRow>
                    ))}
                  </TableBody>
                </Table>
              </div>

              {/* 统计信息 */}
              <div className="mt-4 grid grid-cols-4 gap-4 pt-4 border-t">
                <div className="text-center">
                  <p className="text-xs text-muted-foreground">数据记录数</p>
                  <p className="text-lg font-medium text-info">15 条</p>
                </div>
                <div className="text-center">
                  <p className="text-xs text-muted-foreground">时间跨度</p>
                  <p className="text-lg font-medium text-success">7.5 小时</p>
                </div>
                <div className="text-center">
                  <p className="text-xs text-muted-foreground">采集频率</p>
                  <p className="text-lg font-medium text-accent">30 分钟</p>
                </div>
                <div className="text-center">
                  <p className="text-xs text-muted-foreground">数据完整率</p>
                  <p className="text-lg font-medium text-warning">100%</p>
                </div>
              </div>
            </Card>
          </div>

          <DialogFooter>
            <Button variant="outline" onClick={() => setShowRealtimeDataDialog(false)}>
              关闭
            </Button>
            <Button onClick={() => {
              setShowRealtimeDataDialog(false);
              setShowDeviceDetailDialog(true);
            }}>
              <Eye className="w-4 h-4 mr-2" />
              查看设备详情
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* 添加/编辑设备对话框 */}
      <Dialog open={showDeviceDialog} onOpenChange={setShowDeviceDialog}>
        <DialogContent className="max-w-2xl">
          <DialogHeader>
            <DialogTitle className="flex items-center gap-2">
              <Wifi className="w-5 h-5 text-success" />
              {selectedDevice ? '编辑设备' : '添加设备'}
            </DialogTitle>
            <DialogDescription>
              {selectedDevice ? '修改设备信息和配置参数' : '添加新的物联设备到数据采集系统'}
            </DialogDescription>
          </DialogHeader>

          <div className="space-y-4">
            {/* 基本信息 */}
            <div className="grid grid-cols-2 gap-4">
              <div>
                <Label>设备编号 *</Label>
                <Input 
                  placeholder="例如：WS-2024-001" 
                  defaultValue={selectedDevice?.code}
                />
              </div>
              <div>
                <Label>设备名称 *</Label>
                <Input 
                  placeholder="例如：1号气象站" 
                  defaultValue={selectedDevice?.name}
                />
              </div>
            </div>

            <div className="grid grid-cols-2 gap-4">
              <div>
                <Label>设备类型 *</Label>
                <Select defaultValue={selectedDevice?.type || '气象站'}>
                  <SelectTrigger>
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="气象站">气象站</SelectItem>
                    <SelectItem value="土壤传感器">土壤传感器</SelectItem>
                    <SelectItem value="摄像头">摄像头</SelectItem>
                    <SelectItem value="水质传感器">水质传感器</SelectItem>
                    <SelectItem value="环境监测站">环境监测站</SelectItem>
                  </SelectContent>
                </Select>
              </div>
              <div>
                <Label>通信协议 *</Label>
                <Select defaultValue={selectedDevice?.protocol || 'MQTT'}>
                  <SelectTrigger>
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="MQTT">MQTT</SelectItem>
                    <SelectItem value="HTTP">HTTP</SelectItem>
                    <SelectItem value="CoAP">CoAP</SelectItem>
                    <SelectItem value="WebSocket">WebSocket</SelectItem>
                  </SelectContent>
                </Select>
              </div>
            </div>

            <div className="grid grid-cols-2 gap-4">
              <div>
                <Label>生产厂家</Label>
                <Input 
                  placeholder="例如：华为" 
                  defaultValue={selectedDevice?.manufacturer}
                />
              </div>
              <div>
                <Label>设备型号</Label>
                <Input 
                  placeholder="例如：HW-WS-Pro" 
                  defaultValue={selectedDevice?.model}
                />
              </div>
            </div>

            <div>
              <Label>安装位置</Label>
              <Input 
                placeholder="例如：1号大棚北侧" 
                defaultValue={selectedDevice?.location}
              />
            </div>

            <div>
              <Label>数据上报频率</Label>
              <Select defaultValue={selectedDevice?.dataFrequency || '每5分钟'}>
                <SelectTrigger>
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="每1分钟">每1分钟</SelectItem>
                  <SelectItem value="每5分钟">每5分钟</SelectItem>
                  <SelectItem value="每10分钟">每10分钟</SelectItem>
                  <SelectItem value="每30分钟">每30分钟</SelectItem>
                  <SelectItem value="每1小时">每1小时</SelectItem>
                </SelectContent>
              </Select>
            </div>

            {/* 协议配置 */}
            <Card className="p-4 bg-muted">
              <h4 className="mb-3 text-sm font-medium">协议配置</h4>
              <div className="space-y-3">
                <div>
                  <Label className="text-xs">IP地址/端点</Label>
                  <Input 
                    placeholder="例如：192.168.1.100" 
                    defaultValue={selectedDevice?.ipAddress}
                    className="mt-1"
                  />
                </div>
                <div>
                  <Label className="text-xs">MQTT主题（仅MQTT协议）</Label>
                  <Input 
                    placeholder="例如：farm/sensors/data" 
                    defaultValue={selectedDevice?.mqttTopic}
                    className="mt-1"
                  />
                </div>
              </div>
            </Card>

            {/* 提示信息 */}
            <Card className="p-3 bg-info/10 dark:bg-info/20 border-info/30 dark:border-info/50">
              <div className="flex items-start gap-2">
                <AlertCircle className="w-4 h-4 text-info dark:text-info flex-shrink-0 mt-0.5" />
                <p className="text-xs text-info dark:text-info">
                  添加设备后，系统会自动开始数据采集。请确保设备已正确配置并能正常通信。
                </p>
              </div>
            </Card>
          </div>

          <DialogFooter>
            <Button variant="outline" onClick={() => {
              setShowDeviceDialog(false);
              setSelectedDevice(null);
            }}>
              取消
            </Button>
            <Button className="bg-success hover:bg-success/90" onClick={() => {
              toast.success(selectedDevice ? '设备信息已更新' : '设备添加成功');
              setShowDeviceDialog(false);
              setSelectedDevice(null);
            }}>
              {selectedDevice ? '保存' : '添加'}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
}
