import { useState, useEffect } from 'react';
import { Button } from '../../ui/button';
import { Card } from '../../ui/card';
import { Badge } from '../../ui/badge';
import { Plus, Edit, Trash2, Eye } from 'lucide-react';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '../../ui/table';
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle, DialogFooter } from '../../ui/dialog';
import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle } from '../../ui/alert-dialog';
import { Input } from '../../ui/input';
import { Label } from '../../ui/label';
import { Textarea } from '../../ui/textarea';
import { toast } from 'sonner@2.0.3';
import { useForm } from 'react-hook-form@7.55.0';

// 参数定义接口
interface ParameterDefinition {
  key: string;
  label: string;
  type: 'string' | 'number' | 'boolean' | 'select';
  required?: boolean;
  defaultValue?: any;
  options?: { label: string; value: any }[];
  unit?: string;
  min?: number;
  max?: number;
  description?: string;
}

// 负载类型接口（简化版 + 参数模板）
interface LoadType {
  id: string;
  name: string;
  manufacturer?: string;
  model?: string;
  description?: string;
  parameterDefinitions: ParameterDefinition[]; // 参数模板
  createdAt: string;
  updatedAt: string;
}

export function LoadType() {
  const [loadTypes, setLoadTypes] = useState<LoadType[]>([]);
  const [showDialog, setShowDialog] = useState(false);
  const [showViewDialog, setShowViewDialog] = useState(false);
  const [showParamsDialog, setShowParamsDialog] = useState(false);
  const [editingType, setEditingType] = useState<LoadType | null>(null);
  const [viewingType, setViewingType] = useState<LoadType | null>(null);
  const [viewingParams, setViewingParams] = useState<LoadType | null>(null);
  const [showDeleteConfirm, setShowDeleteConfirm] = useState(false);
  const [pendingDeleteId, setPendingDeleteId] = useState<string | null>(null);

  const { register, handleSubmit, setValue, reset, formState: { errors } } = useForm();

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

  const loadData = () => {
    const data = localStorage.getItem('smart_agriculture_load_types');
    if (data) {
      const types = JSON.parse(data);
      // 确保所有类型都有parameterDefinitions字段
      const normalizedTypes = types.map((type: any) => ({
        ...type,
        parameterDefinitions: type.parameterDefinitions || []
      }));
      setLoadTypes(normalizedTypes);
    } else {
      const mockTypes: LoadType[] = [
        {
          id: 'type-1',
          name: '北斗定位终端',
          manufacturer: '华为',
          model: 'BD-200',
          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' }
              ],
              defaultValue: 'high',
              description: '定位精度模式'
            }
          ],
          createdAt: new Date().toISOString(),
          updatedAt: new Date().toISOString(),
        },
        {
          id: 'type-2',
          name: '高清摄像头',
          manufacturer: '海康威视',
          model: 'DS-2CD2345',
          description: '4K高清网络摄像头，支持夜视功能和远程监控',
          parameterDefinitions: [
            {
              key: 'resolution',
              label: '分辨率',
              type: 'select',
              options: [
                { label: '1080P', value: '1080p' },
                { label: '4K', value: '4k' }
              ],
              defaultValue: '4k'
            },
            {
              key: 'nightVision',
              label: '夜视功能',
              type: 'boolean',
              defaultValue: true
            }
          ],
          createdAt: new Date().toISOString(),
          updatedAt: new Date().toISOString(),
        },
        {
          id: 'type-3',
          name: '油耗传感器',
          manufacturer: '博世',
          model: 'FS-100',
          description: '高精度油耗检测传感器，实时监测油耗数据',
          parameterDefinitions: [
            {
              key: 'sampleFrequency',
              label: '采集频率',
              type: 'number',
              unit: 'Hz',
              required: true,
              defaultValue: 1,
              min: 0.1,
              max: 10,
              description: '数据采集频率'
            }
          ],
          createdAt: new Date().toISOString(),
          updatedAt: new Date().toISOString(),
        },
        {
          id: 'type-4',
          name: '转速传感器',
          manufacturer: '西门子',
          model: 'RS-500',
          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: 'type-5',
          name: '温度传感器',
          manufacturer: '霍尼韦尔',
          model: 'TS-300',
          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: 'type-6',
          name: '湿度传感器',
          manufacturer: '施耐德',
          model: 'HS-200',
          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: '是否联动自动灌溉系统'
            }
          ],
          createdAt: new Date().toISOString(),
          updatedAt: new Date().toISOString(),
        },
        {
          id: 'type-7',
          name: '深度传感器',
          manufacturer: '约翰迪尔',
          model: 'DS-150',
          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: 'type-8',
          name: '流量传感器',
          manufacturer: '艾默生',
          model: 'FL-500',
          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: 'type-9',
          name: 'GPS定位终端',
          manufacturer: 'TrimbleOEM',
          model: 'AG-372',
          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: 'type-10',
          name: '作业监控摄像头',
          manufacturer: '大华',
          model: 'DH-IPC6222',
          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_load_types', JSON.stringify(mockTypes));
      setLoadTypes(mockTypes);
    }
  };

  const onSubmit = (data: any) => {
    if (editingType) {
      const updated: LoadType = {
        ...editingType,
        ...data,
        updatedAt: new Date().toISOString(),
      };
      const newTypes = loadTypes.map(t => t.id === updated.id ? updated : t);
      setLoadTypes(newTypes);
      localStorage.setItem('smart_agriculture_load_types', JSON.stringify(newTypes));
      toast.success('负载类型更新成功');
    } else {
      const newType: LoadType = {
        id: `type-${Date.now()}`,
        ...data,
        parameterDefinitions: [], // 新建时参数模板为空
        createdAt: new Date().toISOString(),
        updatedAt: new Date().toISOString(),
      };
      const newTypes = [...loadTypes, newType];
      setLoadTypes(newTypes);
      localStorage.setItem('smart_agriculture_load_types', JSON.stringify(newTypes));
      toast.success('负载类型添加成功');
    }

    setShowDialog(false);
    setEditingType(null);
    reset();
  };

  const handleEdit = (type: LoadType) => {
    setEditingType(type);
    setValue('name', type.name);
    setValue('manufacturer', type.manufacturer || '');
    setValue('model', type.model || '');
    setValue('description', type.description || '');
    setShowDialog(true);
  };

  const handleView = (type: LoadType) => {
    setViewingType(type);
    setShowViewDialog(true);
  };

  const handleViewParams = (type: LoadType) => {
    setViewingParams(type);
    setShowParamsDialog(true);
  };

  const handleDeleteClick = (id: string) => {
    setPendingDeleteId(id);
    setShowDeleteConfirm(true);
  };

  const confirmDelete = () => {
    if (pendingDeleteId) {
      const newTypes = loadTypes.filter(t => t.id !== pendingDeleteId);
      setLoadTypes(newTypes);
      localStorage.setItem('smart_agriculture_load_types', JSON.stringify(newTypes));
      toast.success('负载类型删除成功');
    }
    setShowDeleteConfirm(false);
    setPendingDeleteId(null);
  };

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

  // 参数统计
  const totalParams = loadTypes.reduce((sum, type) => sum + (type.parameterDefinitions?.length || 0), 0);
  const typesWithParams = loadTypes.filter(type => (type.parameterDefinitions?.length || 0) > 0).length;

  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>
        <Button onClick={() => {
          setEditingType(null);
          reset();
          setShowDialog(true);
        }}>
          <Plus className="w-4 h-4 mr-2" />
          新增类型
        </Button>
      </div>

      {/* 统计卡片 */}
      <div className="grid grid-cols-2 md:grid-cols-5 gap-4">
        <Card className="p-4">
          <div className="text-sm text-muted-foreground">总类型数</div>
          <div className="mt-1">{loadTypes.length}</div>
        </Card>
        <Card className="p-4">
          <div className="text-sm text-muted-foreground">参数模板总数</div>
          <div className="mt-1 text-green-600">{totalParams}</div>
        </Card>
        <Card className="p-4">
          <div className="text-sm text-muted-foreground">已配置模板</div>
          <div className="mt-1">{typesWithParams} / {loadTypes.length}</div>
        </Card>
        <Card className="p-4">
          <div className="text-sm text-muted-foreground">已填写品牌</div>
          <div className="mt-1 text-blue-600">
            {loadTypes.filter(t => t.manufacturer).length}
          </div>
        </Card>
        <Card className="p-4">
          <div className="text-sm text-muted-foreground">已填写型号</div>
          <div className="mt-1">
            {loadTypes.filter(t => t.model).length}
          </div>
        </Card>
      </div>

      {/* 类型列表 */}
      <Card>
        <Table>
          <TableHeader>
            <TableRow>
              <TableHead>类型名称</TableHead>
              <TableHead>品牌</TableHead>
              <TableHead>型号</TableHead>
              <TableHead>描述</TableHead>
              <TableHead>参数模板</TableHead>
              <TableHead className="text-right">操作</TableHead>
            </TableRow>
          </TableHeader>
          <TableBody>
            {loadTypes.length === 0 ? (
              <TableRow>
                <TableCell colSpan={6} className="text-center text-muted-foreground py-8">
                  暂无数据
                </TableCell>
              </TableRow>
            ) : (
              loadTypes.map(type => (
                <TableRow key={type.id}>
                  <TableCell>{type.name}</TableCell>
                  <TableCell>{type.manufacturer || '-'}</TableCell>
                  <TableCell>{type.model || '-'}</TableCell>
                  <TableCell className="max-w-md">
                    <div className="truncate">
                      {type.description || '-'}
                    </div>
                  </TableCell>
                  <TableCell>
                    {(type.parameterDefinitions?.length || 0) > 0 ? (
                      <Button
                        variant="ghost"
                        size="sm"
                        onClick={() => handleViewParams(type)}
                        className="text-green-600 hover:text-green-700"
                      >
                        <Eye className="w-4 h-4 mr-1" />
                        {type.parameterDefinitions.length} 个参数
                      </Button>
                    ) : (
                      <span className="text-muted-foreground text-sm">未定义</span>
                    )}
                  </TableCell>
                  <TableCell className="text-right">
                    <div className="flex justify-end gap-2">
                      <Button 
                        variant="ghost" 
                        size="sm" 
                        onClick={() => handleView(type)}
                        title="查看"
                      >
                        <Eye className="w-4 h-4" />
                      </Button>
                      <Button 
                        variant="ghost" 
                        size="sm" 
                        onClick={() => handleEdit(type)}
                        title="编辑"
                      >
                        <Edit className="w-4 h-4" />
                      </Button>
                      <Button
                        variant="ghost"
                        size="sm"
                        onClick={() => handleDeleteClick(type.id)}
                        title="删除"
                      >
                        <Trash2 className="w-4 h-4 text-destructive" />
                      </Button>
                    </div>
                  </TableCell>
                </TableRow>
              ))
            )}
          </TableBody>
        </Table>
      </Card>

      {/* 添加/编辑对话框 */}
      <Dialog open={showDialog} onOpenChange={setShowDialog}>
        <DialogContent className="max-w-2xl">
          <DialogHeader>
            <DialogTitle>{editingType ? '编辑负载类型' : '新增负载类型'}</DialogTitle>
            <DialogDescription>
              {editingType ? '修改负载类型基本信息（参数模板请在"负载参数"页面管理）' : '填写负载类型基本信息（参数模板可在创建后通过"负载参数"页面添加）'}
            </DialogDescription>
          </DialogHeader>
          <form onSubmit={handleSubmit(onSubmit)}>
            <div className="space-y-4">
              <div className="space-y-2">
                <Label htmlFor="name">
                  类型名称 <span className="text-destructive">*</span>
                </Label>
                <Input 
                  id="name" 
                  {...register('name', { required: '请输入类型名称' })} 
                  placeholder="如：北斗定位终端"
                />
                {errors.name && (
                  <p className="text-sm text-destructive">{errors.name.message as string}</p>
                )}
              </div>

              <div className="grid grid-cols-2 gap-4">
                <div className="space-y-2">
                  <Label htmlFor="manufacturer">品牌</Label>
                  <Input 
                    id="manufacturer" 
                    {...register('manufacturer')} 
                    placeholder="如：华为"
                  />
                </div>

                <div className="space-y-2">
                  <Label htmlFor="model">型号</Label>
                  <Input 
                    id="model" 
                    {...register('model')} 
                    placeholder="如：BD-200"
                  />
                </div>
              </div>

              <div className="space-y-2">
                <Label htmlFor="description">描述</Label>
                <Textarea 
                  id="description" 
                  {...register('description')} 
                  rows={4} 
                  placeholder="请输入负载类型的详细描述..."
                />
              </div>

              {editingType && (editingType.parameterDefinitions?.length || 0) > 0 && (
                <Card className="p-4 bg-blue-50 border-blue-200">
                  <div className="flex items-center justify-between">
                    <div>
                      <div className="text-sm text-blue-900">
                        此类型已配置 {editingType.parameterDefinitions?.length || 0} 个参数模板
                      </div>
                      <div className="text-xs text-blue-700 mt-1">
                        如需修改参数模板，请前往"负载参数"页面
                      </div>
                    </div>
                    <Button
                      type="button"
                      variant="outline"
                      size="sm"
                      onClick={() => {
                        setShowDialog(false);
                        handleViewParams(editingType);
                      }}
                    >
                      <Eye className="w-4 h-4 mr-1" />
                      查看参数
                    </Button>
                  </div>
                </Card>
              )}
            </div>

            <DialogFooter className="mt-6">
              <Button type="button" variant="outline" onClick={() => {
                setShowDialog(false);
                setEditingType(null);
                reset();
              }}>
                取消
              </Button>
              <Button type="submit">
                保存
              </Button>
            </DialogFooter>
          </form>
        </DialogContent>
      </Dialog>

      {/* 查看对话框 */}
      <Dialog open={showViewDialog} onOpenChange={setShowViewDialog}>
        <DialogContent className="max-w-2xl">
          <DialogHeader>
            <DialogTitle>查看负载类型</DialogTitle>
            <DialogDescription>
              负载类型详细信息
            </DialogDescription>
          </DialogHeader>

          {viewingType && (
            <div className="space-y-4">
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <div className="text-sm text-muted-foreground mb-1">类型名称</div>
                  <div>{viewingType.name}</div>
                </div>
                <div>
                  <div className="text-sm text-muted-foreground mb-1">品牌</div>
                  <div>{viewingType.manufacturer || '-'}</div>
                </div>
                <div>
                  <div className="text-sm text-muted-foreground mb-1">型号</div>
                  <div>{viewingType.model || '-'}</div>
                </div>
                <div>
                  <div className="text-sm text-muted-foreground mb-1">参数模板</div>
                  <div>
                    {(viewingType.parameterDefinitions?.length || 0) > 0 ? (
                      <Button
                        variant="link"
                        size="sm"
                        className="p-0 h-auto text-green-600"
                        onClick={() => {
                          setShowViewDialog(false);
                          handleViewParams(viewingType);
                        }}
                      >
                        {viewingType.parameterDefinitions?.length || 0} 个参数
                      </Button>
                    ) : (
                      <span className="text-muted-foreground text-sm">未定义</span>
                    )}
                  </div>
                </div>
              </div>

              <div>
                <div className="text-sm text-muted-foreground mb-1">描述</div>
                <Card className="p-3 bg-muted/50">
                  <div className="text-sm whitespace-pre-wrap">
                    {viewingType.description || '暂无描述'}
                  </div>
                </Card>
              </div>

              <div className="grid grid-cols-2 gap-4 text-sm">
                <div>
                  <div className="text-sm text-muted-foreground mb-1">创建时间</div>
                  <div>{new Date(viewingType.createdAt).toLocaleString('zh-CN')}</div>
                </div>
                <div>
                  <div className="text-sm text-muted-foreground mb-1">更新时间</div>
                  <div>{new Date(viewingType.updatedAt).toLocaleString('zh-CN')}</div>
                </div>
              </div>
            </div>
          )}

          <DialogFooter>
            <Button variant="outline" onClick={() => setShowViewDialog(false)}>
              关闭
            </Button>
            <Button onClick={() => {
              setShowViewDialog(false);
              if (viewingType) {
                handleEdit(viewingType);
              }
            }}>
              编辑
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* 参数模板查看对话框 */}
      <Dialog open={showParamsDialog} onOpenChange={setShowParamsDialog}>
        <DialogContent className="max-w-3xl max-h-[80vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle>参数模板 - {viewingParams?.name}</DialogTitle>
            <DialogDescription>
              查看负载类型的参数模板定义（如需修改，请前往"负载参数"页面）
            </DialogDescription>
          </DialogHeader>

          {viewingParams && (
            <div className="space-y-6">
              {/* 设备类型信息 */}
              <Card className="p-4 bg-muted/50">
                <div className="grid grid-cols-2 gap-4 text-sm">
                  <div>
                    <span className="text-muted-foreground">品牌：</span>
                    <span className="ml-2">{viewingParams.manufacturer || '-'}</span>
                  </div>
                  <div>
                    <span className="text-muted-foreground">型号：</span>
                    <span className="ml-2">{viewingParams.model || '-'}</span>
                  </div>
                </div>
              </Card>

              {/* 参数列表标题 */}
              <div className="flex items-center justify-between">
                <h4>
                  参数定义 ({viewingParams.parameterDefinitions?.length || 0})
                </h4>
                <Badge variant="outline" className="text-red-600">
                  {viewingParams.parameterDefinitions?.filter(p => p.required).length || 0} 个必填
                </Badge>
              </div>

              {/* 参数详情列表 */}
              {(viewingParams.parameterDefinitions?.length || 0) === 0 ? (
                <Card className="p-6">
                  <div className="text-center text-muted-foreground">
                    此设备类型暂未定义参数模板
                  </div>
                  <div className="text-center text-sm text-muted-foreground mt-2">
                    请前往"负载参数"页面添加参数模板
                  </div>
                </Card>
              ) : (
                <div className="space-y-3">
                  {(viewingParams.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 className="font-medium">
                              {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>
                          <Badge variant="secondary">
                            {getParamTypeLabel(param.type)}
                          </Badge>
                        </div>

                        {/* 参数详情 */}
                        <div className="grid grid-cols-2 gap-3 text-sm">
                          <div>
                            <span className="text-muted-foreground">参数编码：</span>
                            <code className="ml-2 text-xs bg-muted px-2 py-1 rounded">
                              {param.key}
                            </code>
                          </div>
                          {param.defaultValue !== undefined && (
                            <div>
                              <span className="text-muted-foreground">默认值：</span>
                              <span className="ml-2">
                                {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-2">
                                {param.min !== undefined ? param.min : '∞'} ~ {param.max !== undefined ? 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>
              )}

              {/* 使用说明 */}
              <Card className="p-4 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>• 如需修改参数模板，请前往"负载参数"页面</li>
                </ul>
              </Card>
            </div>
          )}

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

      {/* 删除确认对话框 */}
      <AlertDialog open={showDeleteConfirm} onOpenChange={setShowDeleteConfirm}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>确认删除</AlertDialogTitle>
            <AlertDialogDescription>
              确定要删除此负载类型吗？此操作不可恢复。
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel onClick={() => {
              setShowDeleteConfirm(false);
              setPendingDeleteId(null);
            }}>
              取消
            </AlertDialogCancel>
            <AlertDialogAction onClick={confirmDelete}>
              确定删除
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </div>
  );
}
