import { useState, useEffect } from 'react';
import { Card } from '../../ui/card';
import { Button } from '../../ui/button';
import { Badge } from '../../ui/badge';
import { DeviceType, ParameterDefinition } from '../../../types/equipment';
import { Plus, Edit, Trash2, Settings } from 'lucide-react';
import { Input } from '../../ui/input';
import { Label } from '../../ui/label';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '../../ui/select';
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle, DialogFooter } from '../../ui/dialog';
import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle } from '../../ui/alert-dialog';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '../../ui/table';
import { Textarea } from '../../ui/textarea';
import { toast } from 'sonner@2.0.3';

export function LoadParameter() {
  const [deviceTypes, setDeviceTypes] = useState<DeviceType[]>([]);
  const [selectedType, setSelectedType] = useState<DeviceType | null>(null);
  const [showParamDialog, setShowParamDialog] = useState(false);
  const [editingParam, setEditingParam] = useState<ParameterDefinition | null>(null);
  const [showDeleteConfirm, setShowDeleteConfirm] = useState(false);
  const [pendingDeleteParam, setPendingDeleteParam] = useState<string | null>(null);

  // 表单状态
  const [paramForm, setParamForm] = useState({
    key: '',
    label: '',
    type: 'string' as 'string' | 'number' | 'boolean' | 'select',
    required: false,
    defaultValue: '',
    unit: '',
    min: '',
    max: '',
    description: '',
    options: [] as { label: string; value: string }[]
  });

  // 选项编辑状态
  const [optionLabel, setOptionLabel] = useState('');
  const [optionValue, setOptionValue] = useState('');

  useEffect(() => {
    loadData();
  }, []);

  const loadData = () => {
    const typesData = localStorage.getItem('smart_agriculture_device_types');
    if (typesData) {
      setDeviceTypes(JSON.parse(typesData));
    } else {
      // 初始化样例数据
      const mockDeviceTypes: DeviceType[] = [
        {
          id: 'device-type-1',
          name: '北斗定位终端',
          category: '北斗终端',
          manufacturer: '华为',
          model: 'BD-200',
          communicationProtocol: 'MQTT',
          dataFormat: 'JSON',
          description: '高精度北斗定位终端，支持实时位置上报和轨迹记录',
          parameterDefinitions: [
            {
              key: 'reportInterval',
              label: '上报间隔',
              type: 'number',
              unit: '秒',
              required: true,
              defaultValue: 10,
              min: 1,
              max: 60,
              description: '位置数据上报时间间隔'
            },
            {
              key: 'accuracyMode',
              label: '精度模式',
              type: 'select',
              options: [
                { label: '高精度', value: 'high' },
                { label: '普通', value: 'normal' },
                { label: '省电', value: 'eco' }
              ],
              defaultValue: 'high',
              description: '定位精度模式'
            },
            {
              key: 'trackingEnabled',
              label: '轨迹跟踪',
              type: 'boolean',
              defaultValue: true,
              description: '是否启用轨迹跟踪功能'
            }
          ],
          createdAt: new Date().toISOString(),
          updatedAt: new Date().toISOString(),
        },
        {
          id: 'device-type-2',
          name: '高清摄像头',
          category: '摄像头',
          manufacturer: '海康威视',
          model: 'DS-2CD2345',
          communicationProtocol: 'HTTP',
          dataFormat: 'Binary',
          description: '4K高清网络摄像头，支持夜视功能和远程监控',
          parameterDefinitions: [
            {
              key: 'resolution',
              label: '分辨率',
              type: 'select',
              options: [
                { label: '720P', value: '720p' },
                { label: '1080P', value: '1080p' },
                { label: '4K', value: '4k' }
              ],
              required: true,
              defaultValue: '4k',
              description: '视频分辨率'
            },
            {
              key: 'nightVision',
              label: '夜视功能',
              type: 'boolean',
              defaultValue: true,
              description: '是否启用红外夜视'
            },
            {
              key: 'frameRate',
              label: '帧率',
              type: 'number',
              unit: 'fps',
              defaultValue: 25,
              min: 15,
              max: 60,
              description: '视频帧率'
            },
            {
              key: 'storageMode',
              label: '存储模式',
              type: 'select',
              options: [
                { label: '本地存储', value: 'local' },
                { label: '云端存储', value: 'cloud' },
                { label: '双重备份', value: 'both' }
              ],
              defaultValue: 'local',
              description: '视频存储方式'
            }
          ],
          createdAt: new Date().toISOString(),
          updatedAt: new Date().toISOString(),
        },
        {
          id: 'device-type-3',
          name: '油耗传感器',
          category: '油耗传感器',
          manufacturer: '博世',
          model: 'FS-100',
          communicationProtocol: 'RS485',
          dataFormat: 'JSON',
          description: '高精度油耗检测传感器，实时监测油耗数据',
          parameterDefinitions: [
            {
              key: 'sampleFrequency',
              label: '采集频率',
              type: 'number',
              unit: 'Hz',
              required: true,
              defaultValue: 1,
              min: 0.1,
              max: 10,
              description: '数据采集频率'
            },
            {
              key: 'flowRange',
              label: '流量范围',
              type: 'select',
              options: [
                { label: '0-10 L/h', value: 'low' },
                { label: '0-50 L/h', value: 'medium' },
                { label: '0-100 L/h', value: 'high' }
              ],
              defaultValue: 'medium',
              description: '油耗测量范围'
            },
            {
              key: 'alertThreshold',
              label: '报警阈值',
              type: 'number',
              unit: 'L/h',
              defaultValue: 80,
              min: 10,
              max: 100,
              description: '油耗超过此值时报警'
            }
          ],
          createdAt: new Date().toISOString(),
          updatedAt: new Date().toISOString(),
        },
        {
          id: 'device-type-4',
          name: '转速传感器',
          category: '转速传感器',
          manufacturer: '西门子',
          model: 'RS-500',
          communicationProtocol: 'CAN',
          dataFormat: 'Binary',
          description: '发动机转速实时监测传感器，支持异常报警',
          parameterDefinitions: [
            {
              key: 'sampleFrequency',
              label: '采集频率',
              type: 'number',
              unit: 'Hz',
              required: true,
              defaultValue: 10,
              min: 1,
              max: 100,
              description: '转速数据采集频率'
            },
            {
              key: 'uploadFrequency',
              label: '上传频率',
              type: 'number',
              unit: '秒',
              required: true,
              defaultValue: 10,
              min: 1,
              max: 60,
              description: '数据上传时间间隔'
            },
            {
              key: 'maxRpm',
              label: '最大转速',
              type: 'number',
              unit: 'RPM',
              defaultValue: 3000,
              min: 1000,
              max: 5000,
              description: '发动机最大转速限制'
            },
            {
              key: 'alarmThreshold',
              label: '报警阈值',
              type: 'number',
              unit: 'RPM',
              defaultValue: 3500,
              min: 2000,
              max: 5000,
              description: '转速超过此值时触发报警'
            },
            {
              key: 'alarmEnabled',
              label: '启用报警',
              type: 'boolean',
              defaultValue: true,
              description: '是否启用超速报警功能'
            },
            {
              key: 'displayMode',
              label: '显示模式',
              type: 'select',
              options: [
                { label: '实时曲线', value: 'realtime' },
                { label: '数字显示', value: 'digital' },
                { label: '仪表盘', value: 'gauge' }
              ],
              defaultValue: 'gauge',
              description: '转速数据显示模式'
            }
          ],
          createdAt: new Date().toISOString(),
          updatedAt: new Date().toISOString(),
        },
        {
          id: 'device-type-5',
          name: '温度传感器',
          category: '温度传感器',
          manufacturer: '霍尼韦尔',
          model: 'TS-300',
          communicationProtocol: 'MQTT',
          dataFormat: 'JSON',
          description: '发动机温度监测传感器，支持高低温报警',
          parameterDefinitions: [
            {
              key: 'sampleFrequency',
              label: '采集频率',
              type: 'number',
              unit: 'Hz',
              required: true,
              defaultValue: 0.5,
              min: 0.1,
              max: 10,
              description: '温度数据采集频率'
            },
            {
              key: 'uploadFrequency',
              label: '上传频率',
              type: 'number',
              unit: '秒',
              required: true,
              defaultValue: 60,
              min: 10,
              max: 300,
              description: '数据上传时间间隔'
            },
            {
              key: 'highAlarmThreshold',
              label: '高温报警阈值',
              type: 'number',
              unit: '°C',
              required: true,
              defaultValue: 90,
              min: 60,
              max: 120,
              description: '温度高于此值时报警'
            },
            {
              key: 'lowAlarmThreshold',
              label: '低温报警阈值',
              type: 'number',
              unit: '°C',
              defaultValue: -10,
              min: -30,
              max: 0,
              description: '温度低于此值时报警'
            },
            {
              key: 'temperatureUnit',
              label: '温度单位',
              type: 'select',
              options: [
                { label: '摄氏度 (°C)', value: 'celsius' },
                { label: '华氏度 (°F)', value: 'fahrenheit' }
              ],
              defaultValue: 'celsius',
              description: '温度显示单位'
            },
            {
              key: 'alarmSound',
              label: '声音报警',
              type: 'boolean',
              defaultValue: true,
              description: '是否启用声音报警'
            },
            {
              key: 'calibrationOffset',
              label: '校准偏移',
              type: 'number',
              unit: '°C',
              defaultValue: 0,
              min: -10,
              max: 10,
              description: '传感器校准偏移量'
            }
          ],
          createdAt: new Date().toISOString(),
          updatedAt: new Date().toISOString(),
        },
        {
          id: 'device-type-6',
          name: '湿度传感器',
          category: '湿度传感器',
          manufacturer: '施耐德',
          model: 'HS-200',
          communicationProtocol: 'RS485',
          dataFormat: 'JSON',
          description: '土壤湿度监测传感器，用于精准灌溉控制',
          parameterDefinitions: [
            {
              key: 'sampleFrequency',
              label: '采集频率',
              type: 'number',
              unit: '次/小时',
              required: true,
              defaultValue: 6,
              min: 1,
              max: 60,
              description: '每小时采集次数'
            },
            {
              key: 'depth',
              label: '监测深度',
              type: 'number',
              unit: 'cm',
              required: true,
              defaultValue: 20,
              min: 5,
              max: 100,
              description: '传感器埋设深度'
            },
            {
              key: 'alertLevel',
              label: '报警水位',
              type: 'select',
              options: [
                { label: '严重干旱 (<20%)', value: 'severe' },
                { label: '轻度干旱 (<40%)', value: 'moderate' },
                { label: '正常 (40-80%)', value: 'normal' }
              ],
              defaultValue: 'moderate',
              description: '湿度报警级别'
            },
            {
              key: 'autoIrrigation',
              label: '自动灌溉',
              type: 'boolean',
              defaultValue: false,
              description: '是否联动自动灌溉系统'
            },
            {
              key: 'soilType',
              label: '土壤类型',
              type: 'select',
              options: [
                { label: '沙土', value: 'sandy' },
                { label: '壤土', value: 'loam' },
                { label: '黏土', value: 'clay' }
              ],
              defaultValue: 'loam',
              description: '土壤类型校准'
            }
          ],
          createdAt: new Date().toISOString(),
          updatedAt: new Date().toISOString(),
        },
        {
          id: 'device-type-7',
          name: '深度传感器',
          category: '深度传感器',
          manufacturer: '约翰迪尔',
          model: 'DS-150',
          communicationProtocol: 'CAN',
          dataFormat: 'Binary',
          description: '耕作深度监测传感器，精确控制耕作质量',
          parameterDefinitions: [
            {
              key: 'measurementMode',
              label: '测量模式',
              type: 'select',
              options: [
                { label: '实时监测', value: 'realtime' },
                { label: '采样监测', value: 'sampling' },
                { label: '连续记录', value: 'continuous' }
              ],
              required: true,
              defaultValue: 'realtime',
              description: '深度测量工作模式'
            },
            {
              key: 'targetDepth',
              label: '目标深度',
              type: 'number',
              unit: 'cm',
              required: true,
              defaultValue: 25,
              min: 5,
              max: 50,
              description: '耕作目标深度'
            },
            {
              key: 'tolerance',
              label: '允许误差',
              type: 'number',
              unit: 'cm',
              defaultValue: 3,
              min: 1,
              max: 10,
              description: '深度允许偏差范围'
            },
            {
              key: 'alarmOnDeviation',
              label: '偏差报警',
              type: 'boolean',
              defaultValue: true,
              description: '深度偏差超出范围时报警'
            },
            {
              key: 'recordInterval',
              label: '记录间隔',
              type: 'number',
              unit: '米',
              defaultValue: 10,
              min: 1,
              max: 100,
              description: '每隔多少米记录一次深度数据'
            }
          ],
          createdAt: new Date().toISOString(),
          updatedAt: new Date().toISOString(),
        },
        {
          id: 'device-type-8',
          name: '流量传感器',
          category: '流量传感器',
          manufacturer: '艾默生',
          model: 'FL-500',
          communicationProtocol: 'MQTT',
          dataFormat: 'JSON',
          description: '液体流量监测传感器，用于施肥、喷药流量控制',
          parameterDefinitions: [
            {
              key: 'flowRange',
              label: '流量范围',
              type: 'select',
              options: [
                { label: '0-10 L/min', value: 'low' },
                { label: '0-50 L/min', value: 'medium' },
                { label: '0-100 L/min', value: 'high' }
              ],
              required: true,
              defaultValue: 'medium',
              description: '传感器测量流量范围'
            },
            {
              key: 'precision',
              label: '测量精度',
              type: 'select',
              options: [
                { label: '±0.5%', value: '0.5' },
                { label: '±1%', value: '1' },
                { label: '±2%', value: '2' }
              ],
              defaultValue: '1',
              description: '流量测量精度'
            },
            {
              key: 'totalizer',
              label: '累计流量',
              type: 'boolean',
              defaultValue: true,
              description: '是否启用累计流量统计'
            },
            {
              key: 'pulseOutput',
              label: '脉冲输出',
              type: 'boolean',
              defaultValue: false,
              description: '是否输出脉冲信号'
            },
            {
              key: 'minFlowAlarm',
              label: '最小流量报警',
              type: 'number',
              unit: 'L/min',
              defaultValue: 5,
              min: 0,
              max: 50,
              description: '流量低于此值时报警'
            },
            {
              key: 'maxFlowAlarm',
              label: '最大流量报警',
              type: 'number',
              unit: 'L/min',
              defaultValue: 45,
              min: 10,
              max: 100,
              description: '流量高于此值时报警'
            }
          ],
          createdAt: new Date().toISOString(),
          updatedAt: new Date().toISOString(),
        },
        {
          id: 'device-type-9',
          name: 'GPS定位终端',
          category: 'GPS终端',
          manufacturer: 'Trimble',
          model: 'AG-372',
          communicationProtocol: 'MQTT',
          dataFormat: 'JSON',
          description: 'RTK高精度GPS定位终端，支持厘米级定位',
          parameterDefinitions: [
            {
              key: 'positionMode',
              label: '定位模式',
              type: 'select',
              options: [
                { label: 'RTK固定解', value: 'rtk_fixed' },
                { label: 'RTK浮动解', value: 'rtk_float' },
                { label: 'DGPS', value: 'dgps' },
                { label: '单点定位', value: 'single' }
              ],
              required: true,
              defaultValue: 'rtk_fixed',
              description: 'GPS定位工作模式'
            },
            {
              key: 'updateRate',
              label: '更新频率',
              type: 'number',
              unit: 'Hz',
              required: true,
              defaultValue: 10,
              min: 1,
              max: 20,
              description: '位置更新频率'
            },
            {
              key: 'elevationMask',
              label: '卫星高度角',
              type: 'number',
              unit: '度',
              defaultValue: 10,
              min: 5,
              max: 20,
              description: '最小卫星高度角'
            },
            {
              key: 'pdopMask',
              label: 'PDOP阈值',
              type: 'number',
              defaultValue: 6,
              min: 1,
              max: 10,
              description: '位置精度因子阈值'
            },
            {
              key: 'recordTrack',
              label: '轨迹记录',
              type: 'boolean',
              defaultValue: true,
              description: '是否记录运行轨迹'
            },
            {
              key: 'trackInterval',
              label: '轨迹点间隔',
              type: 'number',
              unit: '米',
              defaultValue: 5,
              min: 1,
              max: 50,
              description: '轨迹点记录间隔距离'
            }
          ],
          createdAt: new Date().toISOString(),
          updatedAt: new Date().toISOString(),
        },
        {
          id: 'device-type-10',
          name: '作业监控摄像头',
          category: '摄像头',
          manufacturer: '大华',
          model: 'DH-IPC6222',
          communicationProtocol: 'HTTP',
          dataFormat: 'Binary',
          description: '农机作业监控专用摄像头，支持AI识别',
          parameterDefinitions: [
            {
              key: 'resolution',
              label: '视频分辨率',
              type: 'select',
              options: [
                { label: '720P (1280x720)', value: '720p' },
                { label: '1080P (1920x1080)', value: '1080p' },
                { label: '4K (3840x2160)', value: '4k' }
              ],
              required: true,
              defaultValue: '1080p',
              description: '视频录制分辨率'
            },
            {
              key: 'frameRate',
              label: '帧率',
              type: 'select',
              options: [
                { label: '15 fps', value: '15' },
                { label: '25 fps', value: '25' },
                { label: '30 fps', value: '30' }
              ],
              defaultValue: '25',
              description: '视频录制帧率'
            },
            {
              key: 'nightVision',
              label: '夜视功能',
              type: 'boolean',
              defaultValue: true,
              description: '是否启用红外夜视'
            },
            {
              key: 'motionDetection',
              label: '移动侦测',
              type: 'boolean',
              defaultValue: false,
              description: '是否启用移动侦测录像'
            },
            {
              key: 'aiRecognition',
              label: 'AI识别',
              type: 'select',
              options: [
                { label: '关闭', value: 'off' },
                { label: '作物识别', value: 'crop' },
                { label: '障碍物识别', value: 'obstacle' },
                { label: '全部启用', value: 'all' }
              ],
              defaultValue: 'off',
              description: 'AI识别功能'
            },
            {
              key: 'storageMode',
              label: '存储模式',
              type: 'select',
              options: [
                { label: '本地存储', value: 'local' },
                { label: '云端存储', value: 'cloud' },
                { label: '双重备份', value: 'both' }
              ],
              defaultValue: 'local',
              description: '视频存储方式'
            },
            {
              key: 'compressionRate',
              label: '压缩率',
              type: 'select',
              options: [
                { label: '高质量 (低压缩)', value: 'high' },
                { label: '平衡', value: 'medium' },
                { label: '高压缩 (省空间)', value: 'low' }
              ],
              defaultValue: 'medium',
              description: '视频压缩质量'
            }
          ],
          createdAt: new Date().toISOString(),
          updatedAt: new Date().toISOString(),
        },
      ];
      
      localStorage.setItem('smart_agriculture_device_types', JSON.stringify(mockDeviceTypes));
      setDeviceTypes(mockDeviceTypes);
    }
  };

  const getCategoryColor = (category: string) => {
    const colors: Record<string, string> = {
      '摄像头': 'bg-blue-100 text-blue-700',
      '北斗终端': 'bg-green-100 text-green-700',
      'GPS终端': 'bg-green-100 text-green-700',
      '转速传感器': 'bg-purple-100 text-purple-700',
      '油耗传感器': 'bg-orange-100 text-orange-700',
      '温度传感器': 'bg-red-100 text-red-700',
      '湿度传感器': 'bg-cyan-100 text-cyan-700',
      '深度传感器': 'bg-indigo-100 text-indigo-700',
      '流量传感器': 'bg-teal-100 text-teal-700',
      '其他': 'bg-gray-100 text-gray-700',
    };
    return colors[category] || 'bg-gray-100 text-gray-700';
  };

  const getParamTypeLabel = (type: string) => {
    const labels: Record<string, string> = {
      'number': '数字',
      'string': '文本',
      'boolean': '布尔',
      'select': '选择'
    };
    return labels[type] || type;
  };

  const handleManageParams = (type: DeviceType) => {
    setSelectedType(type);
  };

  const handleAddParam = () => {
    setEditingParam(null);
    setParamForm({
      key: '',
      label: '',
      type: 'string',
      required: false,
      defaultValue: '',
      unit: '',
      min: '',
      max: '',
      description: '',
      options: []
    });
    setShowParamDialog(true);
  };

  const handleEditParam = (param: ParameterDefinition) => {
    setEditingParam(param);
    setParamForm({
      key: param.key,
      label: param.label,
      type: param.type,
      required: param.required || false,
      defaultValue: param.defaultValue?.toString() || '',
      unit: param.unit || '',
      min: param.min?.toString() || '',
      max: param.max?.toString() || '',
      description: param.description || '',
      options: param.options || []
    });
    setShowParamDialog(true);
  };

  const handleDeleteParam = (key: string) => {
    setPendingDeleteParam(key);
    setShowDeleteConfirm(true);
  };

  const confirmDeleteParam = () => {
    if (!selectedType || !pendingDeleteParam) return;

    const updatedParams = selectedType.parameterDefinitions.filter(
      p => p.key !== pendingDeleteParam
    );

    const updatedType = {
      ...selectedType,
      parameterDefinitions: updatedParams,
      updatedAt: new Date().toISOString()
    };

    const updatedTypes = deviceTypes.map(t =>
      t.id === selectedType.id ? updatedType : t
    );

    setDeviceTypes(updatedTypes);
    setSelectedType(updatedType);
    localStorage.setItem('smart_agriculture_device_types', JSON.stringify(updatedTypes));
    
    toast.success('参数删除成功');
    setShowDeleteConfirm(false);
    setPendingDeleteParam(null);
  };

  const handleAddOption = () => {
    if (!optionLabel || !optionValue) {
      toast.error('请填写选项标签和值');
      return;
    }

    setParamForm({
      ...paramForm,
      options: [...paramForm.options, { label: optionLabel, value: optionValue }]
    });
    setOptionLabel('');
    setOptionValue('');
  };

  const handleRemoveOption = (index: number) => {
    setParamForm({
      ...paramForm,
      options: paramForm.options.filter((_, i) => i !== index)
    });
  };

  const handleSubmitParam = () => {
    if (!selectedType) return;

    // 验证
    if (!paramForm.key || !paramForm.label) {
      toast.error('请填写参数编码和参数名称');
      return;
    }

    // 构建参数定义
    const newParam: ParameterDefinition = {
      key: paramForm.key,
      label: paramForm.label,
      type: paramForm.type,
      required: paramForm.required,
      description: paramForm.description || undefined
    };

    if (paramForm.defaultValue) {
      if (paramForm.type === 'number') {
        newParam.defaultValue = Number(paramForm.defaultValue);
      } else if (paramForm.type === 'boolean') {
        newParam.defaultValue = paramForm.defaultValue === 'true';
      } else {
        newParam.defaultValue = paramForm.defaultValue;
      }
    }

    if (paramForm.unit) {
      newParam.unit = paramForm.unit;
    }

    if (paramForm.min) {
      newParam.min = Number(paramForm.min);
    }

    if (paramForm.max) {
      newParam.max = Number(paramForm.max);
    }

    if (paramForm.type === 'select' && paramForm.options.length > 0) {
      newParam.options = paramForm.options;
    }

    let updatedParams: ParameterDefinition[];
    if (editingParam) {
      // 编辑现有参数
      updatedParams = selectedType.parameterDefinitions.map(p =>
        p.key === editingParam.key ? newParam : p
      );
      toast.success('参数更新成功');
    } else {
      // 添加新参数
      // 检查key是否已存在
      if (selectedType.parameterDefinitions.find(p => p.key === paramForm.key)) {
        toast.error('参数编码已存在');
        return;
      }
      updatedParams = [...selectedType.parameterDefinitions, newParam];
      toast.success('参数添加成功');
    }

    const updatedType = {
      ...selectedType,
      parameterDefinitions: updatedParams,
      updatedAt: new Date().toISOString()
    };

    const updatedTypes = deviceTypes.map(t =>
      t.id === selectedType.id ? updatedType : t
    );

    setDeviceTypes(updatedTypes);
    setSelectedType(updatedType);
    localStorage.setItem('smart_agriculture_device_types', JSON.stringify(updatedTypes));
    
    setShowParamDialog(false);
  };

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h2 className="text-green-800">负载参数</h2>
          <p className="text-muted-foreground">为每种设备类型定义参数模板</p>
        </div>
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
        {/* 左侧：设备类型列表 */}
        <Card>
          <div className="p-4 border-b">
            <h3>设备类型列表</h3>
            <p className="text-sm text-muted-foreground">选择设备类型以管理参数模板</p>
          </div>
          <div className="p-4">
            {deviceTypes.length === 0 ? (
              <div className="text-center text-muted-foreground py-8">
                暂无设备类型，请先在"负载类型"页面添加
              </div>
            ) : (
              <div className="space-y-2">
                {deviceTypes.map(type => (
                  <div
                    key={type.id}
                    className={`p-4 rounded-lg border-2 cursor-pointer transition-all ${
                      selectedType?.id === type.id
                        ? 'border-green-500 bg-green-50'
                        : 'border-gray-200 hover:border-green-300'
                    }`}
                    onClick={() => handleManageParams(type)}
                  >
                    <div className="flex items-center justify-between">
                      <div className="flex items-center gap-3">
                        <Settings className="w-5 h-5 text-muted-foreground" />
                        <div>
                          <div className="flex items-center gap-2">
                            <span>{type.name}</span>
                            <Badge variant="secondary" className={getCategoryColor(type.category)}>
                              {type.category}
                            </Badge>
                          </div>
                          <div className="text-sm text-muted-foreground mt-1">
                            {type.manufacturer} {type.model}
                          </div>
                        </div>
                      </div>
                      <Badge variant="outline">
                        {type.parameterDefinitions.length} 个参数
                      </Badge>
                    </div>
                  </div>
                ))}
              </div>
            )}
          </div>
        </Card>

        {/* 右侧：参数列表 */}
        <Card>
          <div className="p-4 border-b">
            <div className="flex items-center justify-between">
              <div>
                <h3>参数模板</h3>
                {selectedType ? (
                  <p className="text-sm text-muted-foreground">{selectedType.name}</p>
                ) : (
                  <p className="text-sm text-muted-foreground">请选择设备类型</p>
                )}
              </div>
              {selectedType && (
                <Button onClick={handleAddParam}>
                  <Plus className="w-4 h-4 mr-2" />
                  添加参数
                </Button>
              )}
            </div>
          </div>
          <div className="p-4">
            {!selectedType ? (
              <div className="text-center text-muted-foreground py-12">
                ← 请在左侧选择设备类型
              </div>
            ) : selectedType.parameterDefinitions.length === 0 ? (
              <div className="text-center py-12">
                <p className="text-muted-foreground mb-4">该设备类型暂无参数定义</p>
                <Button onClick={handleAddParam} variant="outline">
                  <Plus className="w-4 h-4 mr-2" />
                  添加第一个参数
                </Button>
              </div>
            ) : (
              <div className="space-y-3">
                {selectedType.parameterDefinitions.map((param, index) => (
                  <Card key={param.key} className="p-4">
                    <div className="space-y-2">
                      <div className="flex items-center justify-between">
                        <div className="flex items-center gap-2">
                          <Badge variant="outline" className="text-xs">
                            {index + 1}
                          </Badge>
                          <span>
                            {param.label}
                            {param.required && <span className="text-destructive ml-1">*</span>}
                            {param.unit && <span className="text-muted-foreground ml-1">({param.unit})</span>}
                          </span>
                        </div>
                        <div className="flex items-center gap-2">
                          <Badge variant="secondary">
                            {getParamTypeLabel(param.type)}
                          </Badge>
                          <Button
                            variant="ghost"
                            size="sm"
                            onClick={() => handleEditParam(param)}
                          >
                            <Edit className="w-4 h-4" />
                          </Button>
                          <Button
                            variant="ghost"
                            size="sm"
                            onClick={() => handleDeleteParam(param.key)}
                          >
                            <Trash2 className="w-4 h-4 text-destructive" />
                          </Button>
                        </div>
                      </div>
                      <div className="grid grid-cols-2 gap-2 text-sm">
                        <div>
                          <span className="text-muted-foreground">参数编码：</span>
                          <code className="text-xs bg-muted px-1 py-0.5 rounded ml-1">
                            {param.key}
                          </code>
                        </div>
                        {param.defaultValue !== undefined && (
                          <div>
                            <span className="text-muted-foreground">默认值：</span>
                            <span className="ml-1">
                              {typeof param.defaultValue === 'boolean'
                                ? param.defaultValue ? '是' : '否'
                                : param.defaultValue}
                            </span>
                          </div>
                        )}
                        {(param.min !== undefined || param.max !== undefined) && (
                          <div>
                            <span className="text-muted-foreground">范围：</span>
                            <span className="ml-1">
                              {param.min ?? '∞'} ~ {param.max ?? '∞'}
                            </span>
                          </div>
                        )}
                        {param.options && param.options.length > 0 && (
                          <div className="col-span-2">
                            <span className="text-muted-foreground">选项：</span>
                            <div className="mt-1 flex flex-wrap gap-1">
                              {param.options.map((opt, i) => (
                                <Badge key={i} variant="outline" className="text-xs">
                                  {opt.label}
                                </Badge>
                              ))}
                            </div>
                          </div>
                        )}
                      </div>
                      {param.description && (
                        <div className="text-sm text-muted-foreground border-l-2 border-muted pl-3">
                          {param.description}
                        </div>
                      )}
                    </div>
                  </Card>
                ))}
              </div>
            )}
          </div>
        </Card>
      </div>

      {/* 使用说明 */}
      <Card className="p-6 bg-blue-50 border-blue-200">
        <h4 className="mb-3 text-blue-900">💡 参数模板使用说明</h4>
        <ul className="space-y-2 text-sm text-blue-800">
          <li>• 参数模板用于定义设备类型的可配置参数</li>
          <li>• 在"负载管理"中挂载设备时，会根据参数模板自动生成配置表单</li>
          <li>• 参数编码(key)用于系统内部识别，建议使用英文驼峰命名</li>
          <li>• 必填参数会在设备挂载时强制要求填写</li>
          <li>• 修改参数模板不会影响已挂载设备的参数配置</li>
        </ul>
      </Card>

      {/* 参数编辑对话框 */}
      <Dialog open={showParamDialog} onOpenChange={setShowParamDialog}>
        <DialogContent className="max-w-2xl max-h-[90vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle>
              {editingParam ? '编辑参数' : '添加参数'}
            </DialogTitle>
            <DialogDescription className="sr-only">
              {editingParam ? '编辑参数定义' : '添加新的参数定义'}
            </DialogDescription>
          </DialogHeader>

          <div className="space-y-4">
            {/* 基本信息 */}
            <div className="grid grid-cols-2 gap-4">
              <div className="space-y-2">
                <Label htmlFor="param-key">参数编码 *</Label>
                <Input
                  id="param-key"
                  value={paramForm.key}
                  onChange={(e) => setParamForm({ ...paramForm, key: e.target.value })}
                  placeholder="如：ipAddress"
                  disabled={!!editingParam}
                />
                <p className="text-xs text-muted-foreground">
                  系统内部使用，建议英文驼峰命名
                </p>
              </div>

              <div className="space-y-2">
                <Label htmlFor="param-label">参数名称 *</Label>
                <Input
                  id="param-label"
                  value={paramForm.label}
                  onChange={(e) => setParamForm({ ...paramForm, label: e.target.value })}
                  placeholder="如：IP地址"
                />
              </div>

              <div className="space-y-2">
                <Label>参数类型 *</Label>
                <Select
                  value={paramForm.type}
                  onValueChange={(value: any) => setParamForm({ ...paramForm, type: value })}
                >
                  <SelectTrigger>
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="string">文本 (string)</SelectItem>
                    <SelectItem value="number">数字 (number)</SelectItem>
                    <SelectItem value="boolean">布尔 (boolean)</SelectItem>
                    <SelectItem value="select">选择 (select)</SelectItem>
                  </SelectContent>
                </Select>
              </div>

              <div className="space-y-2">
                <Label htmlFor="param-unit">参数单位</Label>
                <Input
                  id="param-unit"
                  value={paramForm.unit}
                  onChange={(e) => setParamForm({ ...paramForm, unit: e.target.value })}
                  placeholder="如：秒、Hz、°C"
                />
              </div>
            </div>

            {/* 默认值和必填 */}
            <div className="grid grid-cols-2 gap-4">
              <div className="space-y-2">
                <Label htmlFor="param-default">默认值</Label>
                {paramForm.type === 'boolean' ? (
                  <Select
                    value={paramForm.defaultValue}
                    onValueChange={(value) => setParamForm({ ...paramForm, defaultValue: value })}
                  >
                    <SelectTrigger>
                      <SelectValue placeholder="选择默认值" />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="true">是</SelectItem>
                      <SelectItem value="false">否</SelectItem>
                    </SelectContent>
                  </Select>
                ) : (
                  <Input
                    id="param-default"
                    type={paramForm.type === 'number' ? 'number' : 'text'}
                    value={paramForm.defaultValue}
                    onChange={(e) => setParamForm({ ...paramForm, defaultValue: e.target.value })}
                    placeholder="参数的默认值"
                  />
                )}
              </div>

              <div className="space-y-2">
                <Label className="flex items-center gap-2">
                  <input
                    type="checkbox"
                    checked={paramForm.required}
                    onChange={(e) => setParamForm({ ...paramForm, required: e.target.checked })}
                    className="rounded"
                  />
                  必填参数
                </Label>
                <p className="text-xs text-muted-foreground">
                  勾选后，挂载设备时必须配置此参数
                </p>
              </div>
            </div>

            {/* 数字类型的范围 */}
            {paramForm.type === 'number' && (
              <div className="grid grid-cols-2 gap-4">
                <div className="space-y-2">
                  <Label htmlFor="param-min">最小值</Label>
                  <Input
                    id="param-min"
                    type="number"
                    value={paramForm.min}
                    onChange={(e) => setParamForm({ ...paramForm, min: e.target.value })}
                    placeholder="参数的最小值"
                  />
                </div>

                <div className="space-y-2">
                  <Label htmlFor="param-max">最大值</Label>
                  <Input
                    id="param-max"
                    type="number"
                    value={paramForm.max}
                    onChange={(e) => setParamForm({ ...paramForm, max: e.target.value })}
                    placeholder="参数的最大值"
                  />
                </div>
              </div>
            )}

            {/* 选择类型的选项 */}
            {paramForm.type === 'select' && (
              <div className="space-y-3">
                <Label>选项列表</Label>
                <div className="flex gap-2">
                  <Input
                    placeholder="选项标签（如：高精度）"
                    value={optionLabel}
                    onChange={(e) => setOptionLabel(e.target.value)}
                  />
                  <Input
                    placeholder="选项值（如：high）"
                    value={optionValue}
                    onChange={(e) => setOptionValue(e.target.value)}
                  />
                  <Button type="button" onClick={handleAddOption}>
                    <Plus className="w-4 h-4" />
                  </Button>
                </div>
                {paramForm.options.length > 0 && (
                  <div className="space-y-2">
                    {paramForm.options.map((opt, index) => (
                      <div key={index} className="flex items-center justify-between p-2 bg-muted rounded">
                        <div className="flex items-center gap-2">
                          <Badge variant="outline">{opt.label}</Badge>
                          <code className="text-xs">{opt.value}</code>
                        </div>
                        <Button
                          type="button"
                          variant="ghost"
                          size="sm"
                          onClick={() => handleRemoveOption(index)}
                        >
                          <Trash2 className="w-4 h-4" />
                        </Button>
                      </div>
                    ))}
                  </div>
                )}
              </div>
            )}

            {/* 参数说明 */}
            <div className="space-y-2">
              <Label htmlFor="param-desc">参数说明</Label>
              <Textarea
                id="param-desc"
                value={paramForm.description}
                onChange={(e) => setParamForm({ ...paramForm, description: e.target.value })}
                placeholder="描述参数的用途和注意事项"
                rows={3}
              />
            </div>
          </div>

          <DialogFooter>
            <Button variant="outline" onClick={() => setShowParamDialog(false)}>
              取消
            </Button>
            <Button onClick={handleSubmitParam}>
              {editingParam ? '更新' : '添加'}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* 删除确认对话框 */}
      <AlertDialog open={showDeleteConfirm} onOpenChange={setShowDeleteConfirm}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>确认删除参数</AlertDialogTitle>
            <AlertDialogDescription>
              确定要删除此参数定义吗？删除后，该参数将从设备类型的参数模板中移除。
              注意：这不会影响已挂载设备的现有参数配置。
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel onClick={() => setPendingDeleteParam(null)}>
              取消
            </AlertDialogCancel>
            <AlertDialogAction
              onClick={confirmDeleteParam}
              className="bg-red-600 hover:bg-red-700"
            >
              确认删除
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </div>
  );
}
