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 { Checkbox } from '../ui/checkbox';
import {
  Rocket,
  Plus,
  CheckCircle,
  XCircle,
  AlertCircle,
  PlayCircle,
  PauseCircle,
  StopCircle,
  Eye,
  Edit,
  Clock,
  Zap,
  BarChart3,
  Activity,
  Droplets,
  Bug,
  Sprout,
  Terminal,
  FileText,
  Timer,
  TrendingUp,
  Server,
  Cpu,
  AlertTriangle,
  CheckCircle2,
  ChevronRight,
  ChevronLeft,
  Sparkles,
  Table as TableIcon,
  Type,
  PieChart as PieChartIcon,
  LineChart as LineChartIcon,
} from 'lucide-react';
import { toast } from 'sonner@2.0.3';
import {
  LineChart,
  Line,
  PieChart,
  Pie,
  Cell,
  XAxis,
  YAxis,
  CartesianGrid,
  Tooltip as RechartsTooltip,
  Legend,
  ResponsiveContainer,
} from 'recharts';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '../ui/table';

interface AIModelApplicationProps {
  activePath?: string;
}

type ApplicationType = '智能灌溉' | '病虫害预警' | '施肥推荐' | '产量预测' | '生长监测' | '其他';
type ApplicationStatus = '运行中' | '已停止' | '故障';
type TriggerType = '定时触发' | '周期触发' | '事件触发' | '手动触发';
type TaskStatus = '等待中' | '运行中' | '已完成' | '失败' | '已取消';
type Priority = '高' | '中' | '低';
type OutputFormat = '折线图' | '饼状图' | '表格' | '文字';

interface Application {
  id: string;
  name: string;
  type: ApplicationType;
  description: string;
  modelName: string;
  modelVersion: string;
  inputConfig: {
    fields: string[];
  };
  outputConfig: {
    format: OutputFormat;
  };
  status: ApplicationStatus;
  createTime: string;
  lastRunTime?: string;
  runCount: number;
  successRate: number;
  avgExecutionTime: number;
}

interface ExecutionHistory {
  id: string;
  executeTime: string;
  status: TaskStatus;
  executionTime: number;
  result?: string;
  errorMessage?: string;
}

interface ScheduleTask {
  id: string;
  taskNo: string;
  applicationName: string;
  triggerType: TriggerType;
  priority: Priority;
  scheduledTime: string;
  actualStartTime?: string;
  actualEndTime?: string;
  status: TaskStatus;
  executionTime?: number;
  retryCount: number;
  maxRetry: number;
  errorMessage?: string;
  result?: string;
  executionHistory?: ExecutionHistory[];
}

interface TaskQueue {
  waiting: number;
  running: number;
  completed: number;
  failed: number;
}

interface ModelService {
  id: string;
  name: string;
  version: string;
  type: string;
  status: string;
}

export function AIModelApplication({ activePath }: AIModelApplicationProps) {
  const [activeTab, setActiveTab] = useState('generation');
  const [showTaskDialog, setShowTaskDialog] = useState(false);
  const [selectedTask, setSelectedTask] = useState<ScheduleTask | null>(null);
  
  // 新增调度任务对话框状态
  const [showNewTaskDialog, setShowNewTaskDialog] = useState(false);
  const [newTaskStep, setNewTaskStep] = useState(1);
  const [newTaskData, setNewTaskData] = useState({
    name: '',
    application: null as Application | null,
    inputSources: {} as Record<string, string>,
    priority: '' as Priority | '',
    timeStrategy: '' as '定时' | '周期' | '每天' | '',
    scheduledTime: '',
    cronExpression: '',
    enableManualTrigger: false,
  });
  
  // 应用生成多步骤对话框状态
  const [showGenerateDialog, setShowGenerateDialog] = useState(false);
  const [generateStep, setGenerateStep] = useState(1);
  const [newAppData, setNewAppData] = useState({
    name: '',
    type: '' as ApplicationType | '',
    description: '',
    modelName: '',
    modelVersion: '',
    inputFields: [] as string[],
    outputFormat: '' as OutputFormat | '',
  });

  // 应用运行对话框状态
  const [showRunDialog, setShowRunDialog] = useState(false);
  const [runningApp, setRunningApp] = useState<Application | null>(null);
  const [inputData, setInputData] = useState<Record<string, string>>({});
  const [isRunning, setIsRunning] = useState(false);
  const [runResult, setRunResult] = useState<any>(null);

  // 数据源选项
  const [dataSourceOptions] = useState([
    '传感器实时数据',
    '数据库查询',
    '手动输入',
    '第三方API',
    '历史数据',
    '配置文件',
    'IoT设备',
    '气象站',
  ]);

  // 物联设备选项
  const [iotDeviceOptions] = useState([
    '土壤传感器01 (SN:SS-001)',
    '温湿度传感器02 (SN:TH-002)',
    '光照传感器03 (SN:LS-003)',
    'pH传感器04 (SN:PH-004)',
    '水肥一体机05 (SN:WF-005)',
    '气象站06 (SN:WS-006)',
    '作物图像采集器07 (SN:IC-007)',
    '水泵控制器08 (SN:PC-008)',
  ]);

  // 应用编辑对话框状态
  const [showEditDialog, setShowEditDialog] = useState(false);
  const [editingApp, setEditingApp] = useState<Application | null>(null);
  const [editStep, setEditStep] = useState(1);
  const [editAppData, setEditAppData] = useState({
    name: '',
    type: '' as ApplicationType | '',
    description: '',
    modelName: '',
    modelVersion: '',
    inputFields: [] as string[],
    outputFormat: '' as OutputFormat | '',
  });

  // 根据路径自动切换Tab
  useEffect(() => {
    if (activePath) {
      if (activePath.includes('/model-application/generation')) {
        setActiveTab('generation');
      } else if (activePath.includes('/model-application/scheduling')) {
        setActiveTab('scheduling');
      }
    }
  }, [activePath]);

  // 应用数据 - 改为可修改的状态
  const [applications, setApplications] = useState<Application[]>([
    {
      id: 'app-1',
      name: '智能灌溉策略生成',
      type: '智能灌溉',
      description: '基于土壤湿度、天气预报和作物需水模型，自动生成最优灌溉方案',
      modelName: '灌溉优化模型',
      modelVersion: 'v2.1.0',
      inputConfig: {
        fields: ['土壤湿度', '温度', '降水预报', '作物类型', '生长阶段'],
      },
      outputConfig: {
        format: '折线图',
      },
      status: '运行中',
      createTime: '2024-08-15',
      lastRunTime: '2024-10-15 18:00:00',
      runCount: 1850,
      successRate: 99.5,
      avgExecutionTime: 2.3,
    },
    {
      id: 'app-2',
      name: '病虫害智能预警',
      type: '病虫害预警',
      description: '实时分析作物图像和环境数据，及时发现病虫害并推送预警',
      modelName: '病虫害识别模型',
      modelVersion: 'v1.8.0',
      inputConfig: {
        fields: ['作物图像', '温湿度', '历史病害记录'],
      },
      outputConfig: {
        format: '表格',
      },
      status: '运行中',
      createTime: '2024-09-01',
      lastRunTime: '2024-10-15 16:23:15',
      runCount: 856,
      successRate: 97.8,
      avgExecutionTime: 3.1,
    },
    {
      id: 'app-3',
      name: '精准施肥智能推荐',
      type: '施肥推荐',
      description: '根据土壤养分检测结果和作物生长需求，生成精准施肥方案',
      modelName: '营养需求模型',
      modelVersion: 'v1.5.0',
      inputConfig: {
        fields: ['N含量', 'P含量', 'K含量', '作物品种', 'pH值'],
      },
      outputConfig: {
        format: '饼状图',
      },
      status: '已停止',
      createTime: '2024-10-01',
      lastRunTime: '2024-10-14 08:00:00',
      runCount: 12,
      successRate: 100,
      avgExecutionTime: 1.8,
    },
  ]);

  // 可用模型列表
  const [availableModels] = useState<ModelService[]>([
    { id: 'm1', name: '灌溉优化模型', version: 'v2.1.0', type: 'TensorFlow', status: '运行中' },
    { id: 'm2', name: '病虫害识别模型', version: 'v1.8.0', type: 'PyTorch', status: '运行中' },
    { id: 'm3', name: '营养需求模型', version: 'v1.5.0', type: 'TensorFlow', status: '运行中' },
    { id: 'm4', name: '产量预测模型', version: 'v2.0.0', type: 'XGBoost', status: '运行中' },
    { id: 'm5', name: '生长监测模型', version: 'v1.3.0', type: 'PyTorch', status: '运行中' },
    { id: 'm6', name: '天气预测模型', version: 'v1.6.0', type: 'LSTM', status: '运行中' },
  ]);

  // 可用输入字段选项
  const [inputFieldOptions] = useState<string[]>([
    '土壤湿度', '土壤温度', '空气温度', '空气湿度', '光照强度',
    '降水量', '风速', 'pH值', 'N含量', 'P含量', 'K含量',
    '作物类型', '作物品种', '生长阶段', '种植日期', '种植密度',
    '作物图像', '叶片颜色', '病害症状', '虫害种类',
    '历史产量', '历史病害', '天气预报', '市场价格',
  ]);

  // 调度任务数据 - 改为可修改的状态
  const [scheduleTasks, setScheduleTasks] = useState<ScheduleTask[]>([
    {
      id: 'task-1',
      taskNo: 'T202410150001',
      applicationName: '智能灌溉策略生成',
      triggerType: '周期触发',
      priority: '高',
      scheduledTime: '2024-10-15 18:00:00',
      actualStartTime: '2024-10-15 18:00:02',
      actualEndTime: '2024-10-15 18:00:04',
      status: '已完成',
      executionTime: 2,
      retryCount: 0,
      maxRetry: 3,
      result: '成功生成灌溉方案：3号地块需灌溉10mm',
      executionHistory: [
        {
          id: 'exec-1-5',
          executeTime: '2024-10-15 18:00:00',
          status: '已完成',
          executionTime: 2,
          result: '成功生成灌溉方案：3号地块需灌溉10mm',
        },
        {
          id: 'exec-1-4',
          executeTime: '2024-10-14 18:00:00',
          status: '已完成',
          executionTime: 2,
          result: '成功生成灌溉方案：1号地块需灌溉8mm，5号地块需灌溉12mm',
        },
        {
          id: 'exec-1-3',
          executeTime: '2024-10-13 18:00:00',
          status: '已完成',
          executionTime: 3,
          result: '成功生成灌溉方案：无需灌溉',
        },
        {
          id: 'exec-1-2',
          executeTime: '2024-10-12 18:00:00',
          status: '失败',
          executionTime: 1,
          errorMessage: '数据源连接失败：土壤传感器01离线',
        },
        {
          id: 'exec-1-1',
          executeTime: '2024-10-11 18:00:00',
          status: '已完成',
          executionTime: 2,
          result: '成功生成灌溉方案：2号地块需灌溉15mm，4号地块需灌溉9mm',
        },
      ],
    },
    {
      id: 'task-2',
      taskNo: 'T202410150002',
      applicationName: '病虫害智能预警',
      triggerType: '事件触发',
      priority: '高',
      scheduledTime: '2024-10-15 16:23:15',
      actualStartTime: '2024-10-15 16:23:16',
      actualEndTime: '2024-10-15 16:23:19',
      status: '已完成',
      executionTime: 3,
      retryCount: 0,
      maxRetry: 3,
      result: '正常，未发现病虫害',
      executionHistory: [
        {
          id: 'exec-2-3',
          executeTime: '2024-10-15 16:23:15',
          status: '已完成',
          executionTime: 3,
          result: '正常，未发现病虫害',
        },
        {
          id: 'exec-2-2',
          executeTime: '2024-10-14 09:15:32',
          status: '已完成',
          executionTime: 4,
          result: '预警：2号大棚发现轻微蚜虫，建议喷施生物农药',
        },
        {
          id: 'exec-2-1',
          executeTime: '2024-10-13 14:45:18',
          status: '已完成',
          executionTime: 3,
          result: '正常，未发现病虫害',
        },
      ],
    },
    {
      id: 'task-3',
      taskNo: 'T202410150003',
      applicationName: '精准施肥智能推荐',
      triggerType: '定时触发',
      priority: '中',
      scheduledTime: '2024-10-21 08:00:00',
      status: '等待中',
      retryCount: 0,
      maxRetry: 3,
      executionHistory: [
        {
          id: 'exec-3-2',
          executeTime: '2024-10-14 08:00:00',
          status: '已完成',
          executionTime: 2,
          result: '推荐施肥方案：氮肥15kg/亩，磷肥8kg/亩，钾肥10kg/亩',
        },
        {
          id: 'exec-3-1',
          executeTime: '2024-10-07 08:00:00',
          status: '已完成',
          executionTime: 2,
          result: '推荐施肥方案：有机肥50kg/亩，复合肥20kg/亩',
        },
      ],
    },
  ]);

  // 任务队列统计
  const [taskQueue] = useState<TaskQueue>({
    waiting: 3,
    running: 1,
    completed: 1856,
    failed: 12,
  });

  // 统计数据
  const totalApps = applications.length;
  const runningApps = applications.filter(app => app.status === '运行中').length;
  const avgSuccessRate = applications.reduce((sum, app) => sum + app.successRate, 0) / applications.length;
  const totalRuns = applications.reduce((sum, app) => sum + app.runCount, 0);

  // 新增调度任务处理函数
  const handleCreateScheduleTask = () => {
    setNewTaskData({
      name: '',
      application: null,
      inputSources: {},
      priority: '',
      timeStrategy: '',
      scheduledTime: '',
      cronExpression: '',
      enableManualTrigger: false,
    });
    setNewTaskStep(1);
    setShowNewTaskDialog(true);
  };

  const handleNewTaskNextStep = () => {
    if (newTaskStep === 1) {
      if (!newTaskData.name || !newTaskData.application) {
        toast.error('请填写任务名称并选择应用');
        return;
      }
    } else if (newTaskStep === 2) {
      // 验证输入源配置
      const fields = newTaskData.application?.inputConfig.fields || [];
      const emptyFields = fields.filter(field => !newTaskData.inputSources[field]);
      if (emptyFields.length > 0) {
        toast.error(`请为所有输入参数配置数据源：${emptyFields.join('、')}`);
        return;
      }
    } else if (newTaskStep === 3) {
      if (!newTaskData.priority || !newTaskData.timeStrategy) {
        toast.error('请选择优先级和时间策略');
        return;
      }
      if (newTaskData.timeStrategy === '定时' && !newTaskData.scheduledTime) {
        toast.error('请设置定时执行时间');
        return;
      }
      if (newTaskData.timeStrategy === '周期' && !newTaskData.cronExpression) {
        toast.error('请设置周期表达式');
        return;
      }
    }
    setNewTaskStep(newTaskStep + 1);
  };

  const handleNewTaskPrevStep = () => {
    setNewTaskStep(newTaskStep - 1);
  };

  const handleCreateTask = () => {
    if (!newTaskData.application) return;

    const newTask: ScheduleTask = {
      id: `task-${Date.now()}`,
      taskNo: `T${new Date().getFullYear()}${String(new Date().getMonth() + 1).padStart(2, '0')}${String(new Date().getDate()).padStart(2, '0')}${String(scheduleTasks.length + 1).padStart(4, '0')}`,
      applicationName: newTaskData.application.name,
      triggerType: newTaskData.timeStrategy === '定时' ? '定时触发' : newTaskData.timeStrategy === '周期' ? '周期触发' : '事件触发',
      priority: newTaskData.priority as Priority,
      scheduledTime: newTaskData.scheduledTime || new Date().toLocaleString('zh-CN'),
      status: '等待中',
      retryCount: 0,
      maxRetry: 3,
    };

    setScheduleTasks([newTask, ...scheduleTasks]);
    setShowNewTaskDialog(false);
    toast.success(`调度任务"${newTaskData.name}"创建成功！`);
  };

  const handleManualTriggerTask = (task: ScheduleTask) => {
    toast.success(`任务"${task.applicationName}"已手动触发执行`);
    // 模拟任务状态更新
    setTimeout(() => {
      setScheduleTasks(scheduleTasks.map(t => 
        t.id === task.id 
          ? { ...t, status: '运行中' as TaskStatus, actualStartTime: new Date().toLocaleString('zh-CN') }
          : t
      ));
    }, 500);
  };

  // 处理函数
  const handleStartApp = (app: Application) => {
    setApplications(applications.map(a => 
      a.id === app.id ? { ...a, status: '运行中' as ApplicationStatus } : a
    ));
    toast.success(`应用"${app.name}"已启动`);
  };

  const handleStopApp = (app: Application) => {
    setApplications(applications.map(a => 
      a.id === app.id ? { ...a, status: '已停止' as ApplicationStatus } : a
    ));
    toast.success(`应用"${app.name}"已停止`);
  };

  const handleRunTask = (name: string) => {
    toast.success(`应用"${name}"手动执行任务已提交`);
  };

  // 打开运行应用对话框
  const handleOpenRunDialog = (app: Application) => {
    setRunningApp(app);
    // 初始化输入数据
    const initialInputData: Record<string, string> = {};
    app.inputConfig.fields.forEach(field => {
      initialInputData[field] = '';
    });
    setInputData(initialInputData);
    setRunResult(null);
    setShowRunDialog(true);
  };

  // 生成模拟输出数据
  const generateMockResult = (app: Application, inputs: Record<string, string>) => {
    const format = app.outputConfig.format;
    
    switch (format) {
      case '折线图':
        return {
          type: 'line',
          data: [
            { date: '第1天', value: Math.floor(Math.random() * 50) + 50 },
            { date: '第2天', value: Math.floor(Math.random() * 50) + 50 },
            { date: '第3天', value: Math.floor(Math.random() * 50) + 50 },
            { date: '第4天', value: Math.floor(Math.random() * 50) + 50 },
            { date: '第5天', value: Math.floor(Math.random() * 50) + 50 },
            { date: '第6天', value: Math.floor(Math.random() * 50) + 50 },
            { date: '第7天', value: Math.floor(Math.random() * 50) + 50 },
          ],
        };
      
      case '饼状图':
        return {
          type: 'pie',
          data: [
            { name: '优秀', value: Math.floor(Math.random() * 30) + 20 },
            { name: '良好', value: Math.floor(Math.random() * 30) + 20 },
            { name: '一般', value: Math.floor(Math.random() * 20) + 10 },
            { name: '较差', value: Math.floor(Math.random() * 10) + 5 },
          ],
        };
      
      case '表格':
        return {
          type: 'table',
          columns: ['序号', '项目', '数值', '状态'],
          data: [
            ['1', '土壤湿度', `${(Math.random() * 30 + 40).toFixed(1)}%`, '正常'],
            ['2', '温度', `${(Math.random() * 10 + 20).toFixed(1)}°C`, '正常'],
            ['3', '光照强度', `${(Math.random() * 5000 + 20000).toFixed(0)} Lux`, '正常'],
            ['4', 'pH值', `${(Math.random() * 2 + 6).toFixed(1)}`, '适宜'],
            ['5', 'N含量', `${(Math.random() * 50 + 100).toFixed(0)} mg/kg`, '充足'],
          ],
        };
      
      case '文字':
        return {
          type: 'text',
          content: `基于您输入的参数分析，${app.name}给出以下建议：\n\n1. 根据当前${Object.keys(inputs)[0] || '环境条件'}，建议采取优化措施。\n2. 预计可提升效率约${Math.floor(Math.random() * 20) + 10}%。\n3. 建议执行时间：${new Date(Date.now() + 86400000).toLocaleDateString()}。\n4. 预期效果：显著改善作物生长状况。\n\n请根据实际情况调整方案参数。`,
        };
      
      default:
        return null;
    }
  };

  // 执行运行
  const handleExecuteRun = async () => {
    if (!runningApp) return;

    // 验证输入
    const emptyFields = runningApp.inputConfig.fields.filter(
      field => !inputData[field] || inputData[field].trim() === ''
    );
    
    if (emptyFields.length > 0) {
      toast.error(`请填写完整的输入参数：${emptyFields.join('、')}`);
      return;
    }

    setIsRunning(true);
    
    // 模拟运行过程
    setTimeout(() => {
      const result = generateMockResult(runningApp, inputData);
      setRunResult(result);
      setIsRunning(false);
      toast.success('应用运行成功！');
      
      // 更新应用运行统计
      setApplications(applications.map(app => 
        app.id === runningApp.id 
          ? { 
              ...app, 
              runCount: app.runCount + 1,
              lastRunTime: new Date().toLocaleString('zh-CN'),
            } 
          : app
      ));
    }, 2000);
  };

  // 生成应用 - 重置并打开对话框
  const handleCreateApp = () => {
    setNewAppData({
      name: '',
      type: '',
      description: '',
      modelName: '',
      modelVersion: '',
      inputFields: [],
      outputFormat: '',
    });
    setGenerateStep(1);
    setShowGenerateDialog(true);
  };

  // 下一步
  const handleNextStep = () => {
    if (generateStep === 1) {
      if (!newAppData.name || !newAppData.type || !newAppData.description) {
        toast.error('请填写完整的基本信息');
        return;
      }
    } else if (generateStep === 2) {
      if (!newAppData.modelName || !newAppData.modelVersion) {
        toast.error('请选择模型');
        return;
      }
    } else if (generateStep === 3) {
      if (newAppData.inputFields.length === 0) {
        toast.error('请选择至少一个输入字段');
        return;
      }
    } else if (generateStep === 4) {
      if (!newAppData.outputFormat) {
        toast.error('请选择输出格式');
        return;
      }
    }
    setGenerateStep(generateStep + 1);
  };

  // 上一步
  const handlePrevStep = () => {
    setGenerateStep(generateStep - 1);
  };

  // 发布应用
  const handlePublishApp = () => {
    const newApp: Application = {
      id: `app-${Date.now()}`,
      name: newAppData.name,
      type: newAppData.type as ApplicationType,
      description: newAppData.description,
      modelName: newAppData.modelName,
      modelVersion: newAppData.modelVersion,
      inputConfig: {
        fields: newAppData.inputFields,
      },
      outputConfig: {
        format: newAppData.outputFormat as OutputFormat,
      },
      status: '已停止',
      createTime: new Date().toISOString().split('T')[0],
      runCount: 0,
      successRate: 0,
      avgExecutionTime: 0,
    };

    setApplications([...applications, newApp]);
    setShowGenerateDialog(false);
    toast.success(`应用"${newApp.name}"创建成功！`);
  };

  // 打开编辑应用对话框
  const handleEditApp = (app: Application) => {
    setEditingApp(app);
    setEditAppData({
      name: app.name,
      type: app.type,
      description: app.description,
      modelName: app.modelName,
      modelVersion: app.modelVersion,
      inputFields: app.inputConfig.fields,
      outputFormat: app.outputConfig.format,
    });
    setEditStep(1);
    setShowEditDialog(true);
  };

  // 编辑-下一步
  const handleEditNextStep = () => {
    if (editStep === 1) {
      if (!editAppData.name || !editAppData.type || !editAppData.description) {
        toast.error('请填写完整的基本信息');
        return;
      }
    } else if (editStep === 2) {
      if (!editAppData.modelName || !editAppData.modelVersion) {
        toast.error('请选择模型');
        return;
      }
    } else if (editStep === 3) {
      if (editAppData.inputFields.length === 0) {
        toast.error('请选择至少一个输入字段');
        return;
      }
    } else if (editStep === 4) {
      if (!editAppData.outputFormat) {
        toast.error('请选择输出格式');
        return;
      }
    }
    setEditStep(editStep + 1);
  };

  // 编辑-上一步
  const handleEditPrevStep = () => {
    setEditStep(editStep - 1);
  };

  // 保存编辑
  const handleSaveEdit = () => {
    if (!editingApp) return;

    const updatedApp: Application = {
      ...editingApp,
      name: editAppData.name,
      type: editAppData.type as ApplicationType,
      description: editAppData.description,
      modelName: editAppData.modelName,
      modelVersion: editAppData.modelVersion,
      inputConfig: {
        fields: editAppData.inputFields,
      },
      outputConfig: {
        format: editAppData.outputFormat as OutputFormat,
      },
    };

    setApplications(applications.map(app => 
      app.id === editingApp.id ? updatedApp : app
    ));
    setShowEditDialog(false);
    toast.success(`应用"${updatedApp.name}"更新成功！`);
  };

  // 辅助函数
  const getAppTypeIcon = (type: ApplicationType) => {
    switch (type) {
      case '智能灌溉': return <Droplets className="w-4 h-4 text-success" />;
      case '病虫害预警': return <Bug className="w-4 h-4 text-warning" />;
      case '施肥推荐': return <Sprout className="w-4 h-4 text-accent-foreground" />;
      case '产量预测': return <TrendingUp className="w-4 h-4 text-info" />;
      case '生长监测': return <Activity className="w-4 h-4 text-info" />;
      default: return <Rocket className="w-4 h-4 text-muted-foreground" />;
    }
  };

  const getOutputFormatIcon = (format: OutputFormat) => {
    switch (format) {
      case '折线图': return <LineChartIcon className="w-4 h-4 text-info" />;
      case '饼状图': return <PieChartIcon className="w-4 h-4 text-success" />;
      case '表格': return <TableIcon className="w-4 h-4 text-accent-foreground" />;
      case '文字': return <Type className="w-4 h-4 text-muted-foreground" />;
      default: return <BarChart3 className="w-4 h-4 text-muted-foreground" />;
    }
  };

  const getStatusIcon = (status: ApplicationStatus | TaskStatus) => {
    switch (status) {
      case '运行中': return <PlayCircle className="w-4 h-4 text-green-600" />;
      case '已停止': return <StopCircle className="w-4 h-4 text-gray-600" />;
      case '故障': return <XCircle className="w-4 h-4 text-red-600" />;
      case '已完成': return <CheckCircle className="w-4 h-4 text-green-600" />;
      case '失败': return <XCircle className="w-4 h-4 text-red-600" />;
      case '等待中': return <Clock className="w-4 h-4 text-yellow-600" />;
      case '已取消': return <XCircle className="w-4 h-4 text-gray-600" />;
      default: return <AlertCircle className="w-4 h-4 text-gray-600" />;
    }
  };

  const getStatusColor = (status: ApplicationStatus | TaskStatus) => {
    switch (status) {
      case '运行中': return 'bg-green-100 text-green-700 border-green-300';
      case '已停止': return 'bg-gray-100 text-gray-700 border-gray-300';
      case '故障': return 'bg-red-100 text-red-700 border-red-300';
      case '已完成': return 'bg-green-100 text-green-700 border-green-300';
      case '失败': return 'bg-red-100 text-red-700 border-red-300';
      case '等待中': return 'bg-yellow-100 text-yellow-700 border-yellow-300';
      case '已取消': return 'bg-gray-100 text-gray-700 border-gray-300';
      default: return 'bg-gray-100 text-gray-700 border-gray-300';
    }
  };

  const getPriorityColor = (priority: Priority) => {
    switch (priority) {
      case '高': return 'bg-red-100 text-red-700 border-red-300';
      case '中': return 'bg-orange-100 text-orange-700 border-orange-300';
      case '低': return 'bg-blue-100 text-blue-700 border-blue-300';
      default: return 'bg-gray-100 text-gray-700 border-gray-300';
    }
  };

  const getStepStatus = (step: number) => {
    if (step < generateStep) return 'completed';
    if (step === generateStep) return 'current';
    return 'pending';
  };

  const getEditStepStatus = (step: number) => {
    if (step < editStep) return 'completed';
    if (step === editStep) return 'current';
    return 'pending';
  };

  return (
    <div className="space-y-6">
      <div>
        <h2>模型应用中心</h2>
        <p className="text-sm text-muted-foreground mt-1">
          AI模型应用快速生成与智能调度平台
        </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-blue-600">{totalApps}</p>
              <p className="text-xs text-blue-600 mt-1">已创建应用</p>
            </div>
            <Rocket className="w-12 h-12 text-blue-600 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-green-600">{runningApps}</p>
              <p className="text-xs text-green-600 mt-1">正常运行</p>
            </div>
            <PlayCircle className="w-12 h-12 text-green-600 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-purple-600">{totalRuns}</p>
              <p className="text-xs text-purple-600 mt-1">累计运行</p>
            </div>
            <Zap className="w-12 h-12 text-purple-600 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-orange-600">{avgSuccessRate.toFixed(1)}%</p>
              <p className="text-xs text-orange-600 mt-1">平均成功率</p>
            </div>
            <CheckCircle2 className="w-12 h-12 text-orange-600 opacity-50" />
          </div>
        </Card>
      </div>

      <Tabs value={activeTab} onValueChange={setActiveTab}>
        <TabsList className="grid w-full grid-cols-2">
          <TabsTrigger value="generation">应用生成</TabsTrigger>
          <TabsTrigger value="scheduling">调度管理</TabsTrigger>
        </TabsList>

        {/* 应用生成 */}
        <TabsContent value="generation" className="space-y-4">
          <Card className="p-4 bg-gradient-to-r from-blue-50 to-cyan-50 border-blue-200">
            <div className="flex items-start gap-2">
              <Rocket className="w-5 h-5 text-blue-600 flex-shrink-0 mt-0.5" />
              <div className="text-sm text-blue-900">
                <p className="mb-2">应用生成功能：</p>
                <ul className="space-y-1 text-xs">
                  <li>• <strong>可视化配置</strong>: 通过配置化方式快速生成业务应用</li>
                  <li>• <strong>灵活定制</strong>: 自定义输入字段与输出格式</li>
                  <li>• <strong>多种输出</strong>: 支持折线图、饼状图、表格、文字等多种输出格式</li>
                  <li>• <strong>场景融合</strong>: 实现AI模型与农业生产场景深度融合</li>
                </ul>
              </div>
            </div>
          </Card>

          <div className="flex gap-4">
            <Button className="bg-blue-600 hover:bg-blue-700" onClick={handleCreateApp}>
              <Plus className="w-4 h-4 mr-2" />
              创建应用
            </Button>
          </div>

          {/* 应用卡片列表 */}
          <div>
            <h3 className="mb-4 flex items-center gap-2">
              <Rocket className="w-5 h-5 text-blue-600" />
              我的应用
            </h3>
            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
              {applications.map((app) => (
                <Card key={app.id} className="p-6 hover:shadow-lg transition-shadow">
                  <div className="space-y-4">
                    {/* 头部 */}
                    <div className="flex items-start justify-between">
                      <div className="flex items-center gap-3">
                        <div className="w-12 h-12 bg-blue-50 rounded-lg flex items-center justify-center">
                          {getAppTypeIcon(app.type)}
                        </div>
                        <div>
                          <h4 className="text-base">{app.name}</h4>
                          <Badge variant="outline" className="mt-1">{app.type}</Badge>
                        </div>
                      </div>
                    </div>

                    {/* 描述 */}
                    <p className="text-sm text-muted-foreground line-clamp-2">
                      {app.description}
                    </p>

                    {/* 模型信息 */}
                    <div className="space-y-2">
                      <div className="flex items-center gap-2 text-sm">
                        <Server className="w-4 h-4 text-gray-500" />
                        <span className="text-muted-foreground">模型:</span>
                        <span>{app.modelName}</span>
                      </div>
                      <div className="flex items-center gap-2 text-sm">
                        <Terminal className="w-4 h-4 text-gray-500" />
                        <span className="text-muted-foreground">版本:</span>
                        <span>{app.modelVersion}</span>
                      </div>
                    </div>

                    {/* 输入字段 */}
                    <div>
                      <p className="text-xs text-muted-foreground mb-2">输入字段:</p>
                      <div className="flex flex-wrap gap-1">
                        {app.inputConfig.fields.slice(0, 3).map((field, idx) => (
                          <Badge key={idx} variant="outline" className="text-xs">
                            {field}
                          </Badge>
                        ))}
                        {app.inputConfig.fields.length > 3 && (
                          <Badge variant="outline" className="text-xs">
                            +{app.inputConfig.fields.length - 3}
                          </Badge>
                        )}
                      </div>
                    </div>

                    {/* 输出格式 */}
                    <div className="flex items-center gap-2">
                      {getOutputFormatIcon(app.outputConfig.format)}
                      <span className="text-sm text-muted-foreground">输出:</span>
                      <Badge className="bg-purple-100 text-purple-700 border-purple-300">
                        {app.outputConfig.format}
                      </Badge>
                    </div>

                    {/* 统计信息 */}
                    <div className="pt-4 border-t">
                      <div className="grid grid-cols-2 gap-4 text-sm">
                        <div>
                          <p className="text-xs text-muted-foreground">执行次数</p>
                          <p className="text-lg">{app.runCount}</p>
                        </div>
                        <div>
                          <p className="text-xs text-muted-foreground">成功率</p>
                          <p className="text-lg text-green-600">{app.successRate}%</p>
                        </div>
                      </div>
                    </div>

                    {/* 状态和操作 */}
                    <div className="space-y-3 pt-4 border-t">
                      <div className="flex items-center gap-2">
                        {getStatusIcon(app.status)}
                        <Badge className={getStatusColor(app.status)}>{app.status}</Badge>
                      </div>
                      <div className="flex gap-2">
                        {/* 运行按钮 - 仅在非停止状态显示 */}
                        {app.status !== '已停止' && (
                          <Button 
                            size="sm" 
                            className="flex-1 bg-blue-600 hover:bg-blue-700" 
                            onClick={() => handleOpenRunDialog(app)}
                          >
                            <PlayCircle className="w-3 h-3 mr-1" />
                            运行
                          </Button>
                        )}
                        {app.status === '运行中' ? (
                          <Button 
                            size="sm" 
                            variant="outline" 
                            className={app.status === '已停止' ? 'flex-1' : ''}
                            onClick={() => handleStopApp(app)}
                          >
                            <PauseCircle className="w-3 h-3" />
                          </Button>
                        ) : (
                          <Button 
                            size="sm" 
                            variant="outline" 
                            className={app.status === '已停止' ? 'flex-1' : ''}
                            onClick={() => handleStartApp(app)}
                          >
                            <PlayCircle className="w-3 h-3" />
                          </Button>
                        )}
                        <Button size="sm" variant="outline" onClick={() => handleEditApp(app)}>
                          <Edit className="w-3 h-3" />
                        </Button>
                      </div>
                    </div>
                  </div>
                </Card>
              ))}
            </div>
          </div>
        </TabsContent>

        {/* 调度管理 */}
        <TabsContent value="scheduling" className="space-y-4">
          <Card className="p-4 bg-gradient-to-r from-purple-50 to-pink-50 border-purple-200">
            <div className="flex items-start gap-2">
              <Timer className="w-5 h-5 text-purple-600 flex-shrink-0 mt-0.5" />
              <div className="text-sm text-purple-900">
                <p className="mb-2">智能调度管理：</p>
                <ul className="space-y-1 text-xs">
                  <li>• <strong>任务队列</strong>: 实时查看任务执行队列与状态</li>
                  <li>• <strong>优先级调度</strong>: 根据任务优先级智能调度资源</li>
                  <li>• <strong>异常重试</strong>: 自动重试机制，保障任务执行成功</li>
                  <li>• <strong>全程记录</strong>: 完整记录任务生命周期全过程</li>
                  <li>• <strong>7×24运行</strong>: 无人值守稳定运行，智能化调度</li>
                </ul>
              </div>
            </div>
          </Card>

          {/* 任务队列状态 */}
          <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
            <Card className="p-4 bg-yellow-50">
              <div className="flex items-center gap-3">
                <div className="w-10 h-10 bg-yellow-100 rounded-full flex items-center justify-center">
                  <Clock className="w-5 h-5 text-yellow-600" />
                </div>
                <div>
                  <p className="text-xs text-muted-foreground">等待中</p>
                  <p className="text-2xl text-yellow-600">{taskQueue.waiting}</p>
                </div>
              </div>
            </Card>
            <Card className="p-4 bg-blue-50">
              <div className="flex items-center gap-3">
                <div className="w-10 h-10 bg-blue-100 rounded-full flex items-center justify-center">
                  <Activity className="w-5 h-5 text-blue-600" />
                </div>
                <div>
                  <p className="text-xs text-muted-foreground">运行中</p>
                  <p className="text-2xl text-blue-600">{taskQueue.running}</p>
                </div>
              </div>
            </Card>
            <Card className="p-4 bg-green-50">
              <div className="flex items-center gap-3">
                <div className="w-10 h-10 bg-green-100 rounded-full flex items-center justify-center">
                  <CheckCircle className="w-5 h-5 text-green-600" />
                </div>
                <div>
                  <p className="text-xs text-muted-foreground">已完成</p>
                  <p className="text-2xl text-green-600">{taskQueue.completed}</p>
                </div>
              </div>
            </Card>
            <Card className="p-4 bg-red-50">
              <div className="flex items-center gap-3">
                <div className="w-10 h-10 bg-red-100 rounded-full flex items-center justify-center">
                  <XCircle className="w-5 h-5 text-red-600" />
                </div>
                <div>
                  <p className="text-xs text-muted-foreground">失败</p>
                  <p className="text-2xl text-red-600">{taskQueue.failed}</p>
                </div>
              </div>
            </Card>
          </div>

          {/* 调度任务列表卡片 */}
          <div>
            <div className="mb-4 flex items-center justify-between">
              <h3 className="flex items-center gap-2">
                <Timer className="w-5 h-5 text-purple-600" />
                调度任务列表
              </h3>
              <Button 
                className="bg-purple-600 hover:bg-purple-700"
                onClick={handleCreateScheduleTask}
              >
                <Plus className="w-4 h-4 mr-2" />
                新增调度任务
              </Button>
            </div>
            <div className="grid grid-cols-1 gap-4">
              {scheduleTasks.map((task) => (
                <Card key={task.id} className="p-6">
                  <div className="flex items-start justify-between">
                    <div className="flex-1 space-y-3">
                      <div className="flex items-center gap-4">
                        <span className="font-mono text-sm text-muted-foreground">{task.taskNo}</span>
                        <h4>{task.applicationName}</h4>
                        <Badge variant="outline">{task.triggerType}</Badge>
                        <Badge className={getPriorityColor(task.priority)}>{task.priority}</Badge>
                      </div>

                      <div className="grid grid-cols-4 gap-4 text-sm">
                        <div>
                          <p className="text-xs text-muted-foreground">计划时间</p>
                          <p>{task.scheduledTime}</p>
                        </div>
                        <div>
                          <p className="text-xs text-muted-foreground">实际开始</p>
                          <p>{task.actualStartTime || '-'}</p>
                        </div>
                        <div>
                          <p className="text-xs text-muted-foreground">执行耗时</p>
                          <p>{task.executionTime ? `${task.executionTime}秒` : '-'}</p>
                        </div>
                        <div>
                          <p className="text-xs text-muted-foreground">重试次数</p>
                          <p>{task.retryCount}/{task.maxRetry}</p>
                        </div>
                      </div>

                      {task.result && (
                        <div className="text-sm">
                          <p className="text-xs text-muted-foreground">执行结果</p>
                          <p className="text-green-600">{task.result}</p>
                        </div>
                      )}
                    </div>

                    <div className="flex flex-col items-end gap-3">
                      <div className="flex items-center gap-2">
                        {getStatusIcon(task.status)}
                        <Badge className={getStatusColor(task.status)}>{task.status}</Badge>
                      </div>
                      <div className="flex gap-2">
                        {task.status === '等待中' && (
                          <Button
                            size="sm"
                            className="bg-green-600 hover:bg-green-700"
                            onClick={() => handleManualTriggerTask(task)}
                          >
                            <Zap className="w-3 h-3 mr-1" />
                            手动执行
                          </Button>
                        )}
                        <Button
                          size="sm"
                          variant="outline"
                          onClick={() => {
                            setSelectedTask(task);
                            setShowTaskDialog(true);
                          }}
                        >
                          <Eye className="w-3 h-3 mr-1" />
                          详情
                        </Button>
                      </div>
                    </div>
                  </div>
                </Card>
              ))}
            </div>
          </div>
        </TabsContent>
      </Tabs>

      {/* 任务详情对话框 */}
      <Dialog open={showTaskDialog} onOpenChange={setShowTaskDialog}>
        <DialogContent className="max-w-2xl">
          <DialogHeader>
            <DialogTitle>任务详情</DialogTitle>
            <DialogDescription>
              任务编号: {selectedTask?.taskNo}
            </DialogDescription>
          </DialogHeader>

          {selectedTask && (
            <div className="space-y-4">
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <Label>应用名称</Label>
                  <div className="field-value">{selectedTask.applicationName}</div>
                </div>
                <div>
                  <Label>触发方式</Label>
                  <div className="field-value">
                    <Badge variant="outline">{selectedTask.triggerType}</Badge>
                  </div>
                </div>
              </div>

              <div className="grid grid-cols-2 gap-4">
                <div>
                  <Label>优先级</Label>
                  <div className="field-value">
                    <Badge className={getPriorityColor(selectedTask.priority)}>{selectedTask.priority}</Badge>
                  </div>
                </div>
                <div>
                  <Label>任务状态</Label>
                  <div className="field-value">
                    <div className="flex items-center gap-2">
                      {getStatusIcon(selectedTask.status)}
                      <Badge className={getStatusColor(selectedTask.status)}>{selectedTask.status}</Badge>
                    </div>
                  </div>
                </div>
              </div>

              <div className="grid grid-cols-2 gap-4">
                <div>
                  <Label>计划执行时间</Label>
                  <div className="field-value">{selectedTask.scheduledTime}</div>
                </div>
                <div>
                  <Label>实际开始时间</Label>
                  <div className="field-value">{selectedTask.actualStartTime || '-'}</div>
                </div>
              </div>

              <div className="grid grid-cols-2 gap-4">
                <div>
                  <Label>实际结束时间</Label>
                  <div className="field-value">{selectedTask.actualEndTime || '-'}</div>
                </div>
                <div>
                  <Label>执行耗时</Label>
                  <div className="field-value">{selectedTask.executionTime ? `${selectedTask.executionTime}秒` : '-'}</div>
                </div>
              </div>

              <div>
                <Label>重试信息</Label>
                <div className="field-value">
                  已重试 {selectedTask.retryCount} 次，最大重试 {selectedTask.maxRetry} 次
                </div>
              </div>

              {/* 执行状态监控 */}
              <Card className="p-4 bg-blue-50 border-blue-200">
                <h4 className="mb-3 flex items-center gap-2">
                  <Activity className="w-4 h-4 text-blue-600" />
                  执行状态监控
                </h4>
                
                {/* 状态时间轴 */}
                <div className="space-y-3">
                  <div className="flex items-start gap-3">
                    <div className={`w-8 h-8 rounded-full flex items-center justify-center flex-shrink-0 ${
                      selectedTask.status !== '等待中' ? 'bg-green-500' : 'bg-gray-300'
                    }`}>
                      {selectedTask.status !== '等待中' ? (
                        <CheckCircle2 className="w-4 h-4 text-white" />
                      ) : (
                        <Clock className="w-4 h-4 text-gray-600" />
                      )}
                    </div>
                    <div className="flex-1">
                      <p className="text-sm">任务创建</p>
                      <p className="text-xs text-muted-foreground">{selectedTask.scheduledTime}</p>
                    </div>
                  </div>

                  {selectedTask.actualStartTime && (
                    <div className="flex items-start gap-3">
                      <div className={`w-8 h-8 rounded-full flex items-center justify-center flex-shrink-0 ${
                        selectedTask.status === '已完成' || selectedTask.status === '失败' ? 'bg-green-500' : 'bg-blue-500'
                      }`}>
                        {selectedTask.status === '运行中' ? (
                          <Activity className="w-4 h-4 text-white animate-pulse" />
                        ) : (
                          <CheckCircle2 className="w-4 h-4 text-white" />
                        )}
                      </div>
                      <div className="flex-1">
                        <p className="text-sm">开始执行</p>
                        <p className="text-xs text-muted-foreground">{selectedTask.actualStartTime}</p>
                      </div>
                    </div>
                  )}

                  {selectedTask.actualEndTime && (
                    <div className="flex items-start gap-3">
                      <div className={`w-8 h-8 rounded-full flex items-center justify-center flex-shrink-0 ${
                        selectedTask.status === '已完成' ? 'bg-green-500' : 'bg-red-500'
                      }`}>
                        {selectedTask.status === '已完成' ? (
                          <CheckCircle className="w-4 h-4 text-white" />
                        ) : (
                          <XCircle className="w-4 h-4 text-white" />
                        )}
                      </div>
                      <div className="flex-1">
                        <p className="text-sm">执行完成</p>
                        <p className="text-xs text-muted-foreground">{selectedTask.actualEndTime}</p>
                      </div>
                    </div>
                  )}
                </div>

                {/* 执行进度 */}
                {selectedTask.status === '运行中' && (
                  <div className="mt-4">
                    <div className="flex items-center justify-between mb-2">
                      <span className="text-sm">执行进度</span>
                      <span className="text-sm">65%</span>
                    </div>
                    <div className="w-full bg-border rounded-full h-2">
                      <div className="bg-primary h-2 rounded-full transition-all duration-500" style={{ width: '65%' }}></div>
                    </div>
                  </div>
                )}

                {/* 重试记录 */}
                {selectedTask.retryCount > 0 && (
                  <Card className="p-3 mt-3 bg-yellow-50 border-yellow-200">
                    <div className="flex items-center gap-2 text-yellow-800">
                      <AlertTriangle className="w-4 h-4" />
                      <span className="text-sm">已重试 {selectedTask.retryCount} 次</span>
                    </div>
                  </Card>
                )}
              </Card>

              {selectedTask.result && (
                <div>
                  <Label>执行结果</Label>
                  <div className="field-value text-green-600">{selectedTask.result}</div>
                </div>
              )}

              {selectedTask.errorMessage && (
                <div>
                  <Label>错误信息</Label>
                  <div className="field-value text-red-600">{selectedTask.errorMessage}</div>
                </div>
              )}

              {/* 执行历史记录 */}
              {selectedTask.executionHistory && selectedTask.executionHistory.length > 0 && (
                <Card className="p-4 bg-muted">
                  <h4 className="mb-3 flex items-center gap-2">
                    <Clock className="w-4 h-4 text-muted-foreground" />
                    执行历史记录
                  </h4>
                  <p className="text-xs text-muted-foreground mb-4">
                    共 {selectedTask.executionHistory.length} 次执行记录
                  </p>
                  
                  <div className="space-y-3 max-h-80 overflow-y-auto">
                    {selectedTask.executionHistory.map((history, index) => (
                      <Card 
                        key={history.id} 
                        className={`p-4 ${
                          history.status === '已完成' 
                            ? 'bg-white border-green-200' 
                            : 'bg-white border-red-200'
                        }`}
                      >
                        <div className="flex items-start justify-between mb-3">
                          <div className="flex items-center gap-2">
                            <div className={`w-6 h-6 rounded-full flex items-center justify-center ${
                              history.status === '已完成' 
                                ? 'bg-green-100' 
                                : 'bg-red-100'
                            }`}>
                              {history.status === '已完成' ? (
                                <CheckCircle className="w-4 h-4 text-green-600" />
                              ) : (
                                <XCircle className="w-4 h-4 text-red-600" />
                              )}
                            </div>
                            <div>
                              <p className="text-sm font-medium">第 {selectedTask.executionHistory.length - index} 次执行</p>
                              <p className="text-xs text-muted-foreground">{history.executeTime}</p>
                            </div>
                          </div>
                          <Badge className={
                            history.status === '已完成'
                              ? 'bg-green-100 text-green-800 border-green-300'
                              : 'bg-red-100 text-red-800 border-red-300'
                          }>
                            {history.status}
                          </Badge>
                        </div>

                        <div className="grid grid-cols-2 gap-3 mb-3">
                          <div>
                            <p className="text-xs text-muted-foreground">执行耗时</p>
                            <p className="text-sm font-medium">{history.executionTime}秒</p>
                          </div>
                          <div>
                            <p className="text-xs text-muted-foreground">执行状态</p>
                            <p className="text-sm font-medium">{history.status}</p>
                          </div>
                        </div>

                        {history.result && (
                          <div className="p-2 bg-green-50 border border-green-200 rounded">
                            <p className="text-xs text-muted-foreground mb-1">执行结果</p>
                            <p className="text-sm text-green-700">{history.result}</p>
                          </div>
                        )}

                        {history.errorMessage && (
                          <div className="p-2 bg-red-50 border border-red-200 rounded">
                            <p className="text-xs text-muted-foreground mb-1">错误信息</p>
                            <p className="text-sm text-red-700">{history.errorMessage}</p>
                          </div>
                        )}
                      </Card>
                    ))}
                  </div>
                </Card>
              )}
            </div>
          )}

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

      {/* 新增调度任务对话框 */}
      <Dialog open={showNewTaskDialog} onOpenChange={setShowNewTaskDialog}>
        <DialogContent className="max-w-4xl max-h-[90vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle className="flex items-center gap-2">
              <Plus className="w-5 h-5 text-purple-600" />
              新增调度任务 - {['基本信息', '配置数据源', '调度策略'][newTaskStep - 1]}
            </DialogTitle>
            <DialogDescription>
              步骤 {newTaskStep} / 3
            </DialogDescription>
          </DialogHeader>

          {/* 步骤指示器 */}
          <div className="flex items-center justify-between mb-6">
            {[1, 2, 3].map((step) => (
              <div key={step} className="flex items-center">
                <div className="flex flex-col items-center">
                  <div
                    className={`w-10 h-10 rounded-full flex items-center justify-center transition-all ${
                      step < newTaskStep
                        ? 'bg-green-500 text-white'
                        : step === newTaskStep
                        ? 'bg-purple-500 text-white'
                        : 'bg-gray-200 text-gray-500'
                    }`}
                  >
                    {step < newTaskStep ? (
                      <CheckCircle className="w-5 h-5" />
                    ) : (
                      step
                    )}
                  </div>
                  <p className="text-xs mt-2 text-center">
                    {['基本信息', '配置数据源', '调度策略'][step - 1]}
                  </p>
                </div>
                {step < 3 && (
                  <div
                    className={`w-24 h-1 mx-2 ${
                      step < newTaskStep ? 'bg-green-500' : 'bg-gray-200'
                    }`}
                  />
                )}
              </div>
            ))}
          </div>

          {/* 步骤1: 基本信息 */}
          {newTaskStep === 1 && (
            <div className="space-y-4">
              <Card className="p-4 bg-purple-50 border-purple-200">
                <div className="flex items-center gap-2 text-purple-900">
                  <FileText className="w-4 h-4" />
                  <span className="text-sm">请填写调度任务的基本信息</span>
                </div>
              </Card>

              <div>
                <Label>任务名称 *</Label>
                <Input
                  placeholder="请输入任务名称，如：每日灌溉计划生成"
                  value={newTaskData.name}
                  onChange={(e) => setNewTaskData({ ...newTaskData, name: e.target.value })}
                />
              </div>

              <div>
                <Label>选择应用 *</Label>
                <Select
                  value={newTaskData.application?.id || ''}
                  onValueChange={(value) => {
                    const app = applications.find(a => a.id === value);
                    setNewTaskData({ ...newTaskData, application: app || null, inputSources: {} });
                  }}
                >
                  <SelectTrigger>
                    <SelectValue placeholder="选择要调度的应用" />
                  </SelectTrigger>
                  <SelectContent>
                    {applications.filter(app => app.status === '运行中').map((app) => (
                      <SelectItem key={app.id} value={app.id}>
                        <div className="flex items-center gap-2">
                          {app.type === '智能灌溉' && <Droplets className="w-4 h-4 text-green-600" />}
                          {app.type === '病虫害预警' && <Bug className="w-4 h-4 text-orange-600" />}
                          {app.type === '施肥推荐' && <Sprout className="w-4 h-4 text-purple-600" />}
                          {app.name}
                        </div>
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>

              {newTaskData.application && (
                <Card className="p-4 bg-blue-50 border-blue-200">
                  <div className="space-y-2 text-sm">
                    <p><strong>应用描述：</strong>{newTaskData.application.description}</p>
                    <p><strong>使用模型：</strong>{newTaskData.application.modelName} {newTaskData.application.modelVersion}</p>
                    <p><strong>输入参数：</strong>{newTaskData.application.inputConfig.fields.join('、')}</p>
                    <p><strong>输出格式：</strong>{newTaskData.application.outputConfig.format}</p>
                  </div>
                </Card>
              )}
            </div>
          )}

          {/* 步骤2: 配置数据源 */}
          {newTaskStep === 2 && newTaskData.application && (
            <div className="space-y-4">
              <Card className="p-4 bg-blue-50 border-blue-200">
                <div className="flex items-center gap-2 text-blue-900 text-sm">
                  <AlertCircle className="w-4 h-4" />
                  <span>请为应用的每个输入参数配置数据源</span>
                </div>
              </Card>

              <div className="space-y-4">
                {newTaskData.application.inputConfig.fields.map((field) => (
                  <Card key={field} className="p-4">
                    <div className="mb-3">
                      <Label className="flex items-center gap-2">
                        <span className="text-base">{field}</span>
                        <Badge variant="outline" className="text-xs">必填</Badge>
                      </Label>
                    </div>
                    <div className="grid grid-cols-2 gap-4">
                      <div>
                        <Label className="text-xs text-muted-foreground mb-2">多源数据</Label>
                        <Select
                          value={newTaskData.inputSources[field] || ''}
                          onValueChange={(value) =>
                            setNewTaskData({
                              ...newTaskData,
                              inputSources: { ...newTaskData.inputSources, [field]: value }
                            })
                          }
                        >
                          <SelectTrigger>
                            <SelectValue placeholder="选择数据源" />
                          </SelectTrigger>
                          <SelectContent>
                            {dataSourceOptions.map((source) => (
                              <SelectItem key={source} value={source}>
                                {source}
                              </SelectItem>
                            ))}
                          </SelectContent>
                        </Select>
                      </div>
                      <div>
                        <Label className="text-xs text-muted-foreground mb-2">物联设备数据</Label>
                        <Select
                          value={newTaskData.inputSources[field] || ''}
                          onValueChange={(value) =>
                            setNewTaskData({
                              ...newTaskData,
                              inputSources: { ...newTaskData.inputSources, [field]: value }
                            })
                          }
                        >
                          <SelectTrigger>
                            <SelectValue placeholder="选择物联设备" />
                          </SelectTrigger>
                          <SelectContent>
                            {iotDeviceOptions.map((device) => (
                              <SelectItem key={device} value={device}>
                                {device}
                              </SelectItem>
                            ))}
                          </SelectContent>
                        </Select>
                      </div>
                    </div>
                  </Card>
                ))}
              </div>
            </div>
          )}

          {/* 步骤3: 调度策略 */}
          {newTaskStep === 3 && (
            <div className="space-y-4">
              <Card className="p-4 bg-green-50 border-green-200">
                <div className="flex items-center gap-2 text-green-900 text-sm">
                  <Timer className="w-4 h-4" />
                  <span>配置任务的调度策略和执行时间</span>
                </div>
              </Card>

              <div className="grid grid-cols-2 gap-4">
                <div>
                  <Label>优先级 *</Label>
                  <Select
                    value={newTaskData.priority}
                    onValueChange={(value) => setNewTaskData({ ...newTaskData, priority: value as Priority })}
                  >
                    <SelectTrigger>
                      <SelectValue placeholder="选择优先级" />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="高">
                        <div className="flex items-center gap-2">
                          <div className="w-2 h-2 rounded-full bg-red-500"></div>
                          高优先级
                        </div>
                      </SelectItem>
                      <SelectItem value="中">
                        <div className="flex items-center gap-2">
                          <div className="w-2 h-2 rounded-full bg-yellow-500"></div>
                          中优先级
                        </div>
                      </SelectItem>
                      <SelectItem value="低">
                        <div className="flex items-center gap-2">
                          <div className="w-2 h-2 rounded-full bg-green-500"></div>
                          低优先级
                        </div>
                      </SelectItem>
                    </SelectContent>
                  </Select>
                </div>

                <div>
                  <Label>时间策略 *</Label>
                  <Select
                    value={newTaskData.timeStrategy}
                    onValueChange={(value) => setNewTaskData({ ...newTaskData, timeStrategy: value as any })}
                  >
                    <SelectTrigger>
                      <SelectValue placeholder="选择时间策略" />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="定时">定时执行（一次性）</SelectItem>
                      <SelectItem value="周期">周期执行（Cron表达式）</SelectItem>
                      <SelectItem value="每天">每天执行（固定时间）</SelectItem>
                    </SelectContent>
                  </Select>
                </div>
              </div>

              {newTaskData.timeStrategy === '定时' && (
                <div>
                  <Label>执行时间 *</Label>
                  <Input
                    type="datetime-local"
                    value={newTaskData.scheduledTime}
                    onChange={(e) => setNewTaskData({ ...newTaskData, scheduledTime: e.target.value })}
                  />
                </div>
              )}

              {newTaskData.timeStrategy === '周期' && (
                <div>
                  <Label>Cron表达式 *</Label>
                  <Input
                    placeholder="如：0 0 * * * (每小时执行)"
                    value={newTaskData.cronExpression}
                    onChange={(e) => setNewTaskData({ ...newTaskData, cronExpression: e.target.value })}
                  />
                  <p className="text-xs text-muted-foreground mt-1">
                    格式：秒 分 时 日 月 周。示例：0 0 */6 * * * (每6小时)
                  </p>
                </div>
              )}

              {newTaskData.timeStrategy === '每天' && (
                <div>
                  <Label>每日执行时间 *</Label>
                  <Input
                    type="time"
                    value={newTaskData.scheduledTime}
                    onChange={(e) => setNewTaskData({ ...newTaskData, scheduledTime: e.target.value })}
                  />
                </div>
              )}

              <div className="flex items-center gap-2">
                <Checkbox
                  id="manualTrigger"
                  checked={newTaskData.enableManualTrigger}
                  onCheckedChange={(checked) => 
                    setNewTaskData({ ...newTaskData, enableManualTrigger: checked as boolean })
                  }
                />
                <Label htmlFor="manualTrigger" className="text-sm">
                  支持手动执行触发
                </Label>
              </div>

              {/* 预览卡片 */}
              <Card className="p-4 bg-purple-50 border-purple-200">
                <h4 className="mb-3">任务预览</h4>
                <div className="space-y-2 text-sm">
                  <p><strong>任务名称：</strong>{newTaskData.name}</p>
                  <p><strong>应用：</strong>{newTaskData.application?.name}</p>
                  <p><strong>优先级：</strong>{newTaskData.priority}</p>
                  <p><strong>时间策略：</strong>{newTaskData.timeStrategy}</p>
                  <p><strong>数据源配置：</strong>已配置 {Object.keys(newTaskData.inputSources).length} 个参数</p>
                  <p><strong>手动触发：</strong>{newTaskData.enableManualTrigger ? '已启用' : '未启用'}</p>
                </div>
              </Card>
            </div>
          )}

          <DialogFooter>
            <div className="flex justify-between w-full">
              <div>
                {newTaskStep > 1 && (
                  <Button variant="outline" onClick={handleNewTaskPrevStep}>
                    <ChevronLeft className="w-4 h-4 mr-2" />
                    上一步
                  </Button>
                )}
              </div>
              <div className="flex gap-2">
                <Button variant="outline" onClick={() => setShowNewTaskDialog(false)}>
                  取消
                </Button>
                {newTaskStep < 3 ? (
                  <Button className="bg-purple-600 hover:bg-purple-700" onClick={handleNewTaskNextStep}>
                    下一步
                    <ChevronRight className="w-4 h-4 ml-2" />
                  </Button>
                ) : (
                  <Button className="bg-green-600 hover:bg-green-700" onClick={handleCreateTask}>
                    <Rocket className="w-4 h-4 mr-2" />
                    创建任务
                  </Button>
                )}
              </div>
            </div>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* 应用运行对话框 */}
      <Dialog open={showRunDialog} onOpenChange={setShowRunDialog}>
        <DialogContent className="max-w-5xl max-h-[90vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle className="flex items-center gap-2">
              <PlayCircle className="w-5 h-5 text-blue-600" />
              运行应用：{runningApp?.name}
            </DialogTitle>
            <DialogDescription>
              填写输入参数并运行应用，查看分析结果
            </DialogDescription>
          </DialogHeader>

          {runningApp && (
            <div className="space-y-6">
              {/* 应用信息 */}
              <Card className="p-4 bg-gradient-to-r from-blue-50 to-cyan-50 border-blue-200">
                <div className="grid grid-cols-3 gap-4 text-sm">
                  <div>
                    <p className="text-xs text-muted-foreground mb-1">应用类型</p>
                    <Badge variant="outline">{runningApp.type}</Badge>
                  </div>
                  <div>
                    <p className="text-xs text-muted-foreground mb-1">使用模型</p>
                    <p>{runningApp.modelName} {runningApp.modelVersion}</p>
                  </div>
                  <div>
                    <p className="text-xs text-muted-foreground mb-1">输出格式</p>
                    <div className="flex items-center gap-1">
                      {getOutputFormatIcon(runningApp.outputConfig.format)}
                      <span>{runningApp.outputConfig.format}</span>
                    </div>
                  </div>
                </div>
              </Card>

              {/* 输入参数 */}
              <div>
                <h4 className="mb-4 flex items-center gap-2">
                  <FileText className="w-5 h-5 text-green-600" />
                  输入参数配置
                </h4>
                <Card className="p-4 bg-blue-50 border-blue-200 mb-4">
                  <div className="flex items-center gap-2 text-blue-900 text-sm">
                    <AlertCircle className="w-4 h-4" />
                    <span>请为每个输入字段选择数据源或物联设备</span>
                  </div>
                </Card>
                <div className="space-y-4">
                  {runningApp.inputConfig.fields.map((field) => (
                    <Card key={field} className="p-4">
                      <div className="mb-3">
                        <Label className="flex items-center gap-2">
                          <span className="text-base">{field}</span>
                          <Badge variant="outline" className="text-xs">必填</Badge>
                        </Label>
                      </div>
                      <div className="grid grid-cols-2 gap-4">
                        <div>
                          <Label className="text-xs text-muted-foreground mb-2">多源数据</Label>
                          <Select
                            value={inputData[field] || ''}
                            onValueChange={(value) =>
                              setInputData({ ...inputData, [field]: value })
                            }
                            disabled={isRunning}
                          >
                            <SelectTrigger>
                              <SelectValue placeholder="选择数据源" />
                            </SelectTrigger>
                            <SelectContent>
                              {dataSourceOptions.map((source) => (
                                <SelectItem key={source} value={source}>
                                  {source}
                                </SelectItem>
                              ))}
                            </SelectContent>
                          </Select>
                        </div>
                        <div>
                          <Label className="text-xs text-muted-foreground mb-2">物联设备数据</Label>
                          <Select
                            value={inputData[field] || ''}
                            onValueChange={(value) =>
                              setInputData({ ...inputData, [field]: value })
                            }
                            disabled={isRunning}
                          >
                            <SelectTrigger>
                              <SelectValue placeholder="选择物联设备" />
                            </SelectTrigger>
                            <SelectContent>
                              {iotDeviceOptions.map((device) => (
                                <SelectItem key={device} value={device}>
                                  {device}
                                </SelectItem>
                              ))}
                            </SelectContent>
                          </Select>
                        </div>
                      </div>
                    </Card>
                  ))}
                </div>
              </div>

              {/* 运行按钮 */}
              <div className="flex justify-center">
                <Button
                  className="bg-green-600 hover:bg-green-700 px-8"
                  onClick={handleExecuteRun}
                  disabled={isRunning}
                >
                  {isRunning ? (
                    <>
                      <Activity className="w-4 h-4 mr-2 animate-spin" />
                      运行中...
                    </>
                  ) : (
                    <>
                      <Zap className="w-4 h-4 mr-2" />
                      执行运行
                    </>
                  )}
                </Button>
              </div>

              {/* 输出结果 */}
              {runResult && (
                <div>
                  <h4 className="mb-4 flex items-center gap-2">
                    <BarChart3 className="w-5 h-5 text-purple-600" />
                    运行结果
                  </h4>

                  {/* 折线图 */}
                  {runResult.type === 'line' && (
                    <Card className="p-6">
                      <ResponsiveContainer width="100%" height={300}>
                        <LineChart data={runResult.data}>
                          <CartesianGrid strokeDasharray="3 3" />
                          <XAxis dataKey="date" />
                          <YAxis />
                          <RechartsTooltip />
                          <Legend />
                          <Line
                            type="monotone"
                            dataKey="value"
                            stroke="#3b82f6"
                            strokeWidth={2}
                            name="数值"
                          />
                        </LineChart>
                      </ResponsiveContainer>
                    </Card>
                  )}

                  {/* 饼状图 */}
                  {runResult.type === 'pie' && (
                    <Card className="p-6">
                      <ResponsiveContainer width="100%" height={300}>
                        <PieChart>
                          <Pie
                            data={runResult.data}
                            cx="50%"
                            cy="50%"
                            labelLine={false}
                            label={(entry) => `${entry.name}: ${entry.value}%`}
                            outerRadius={100}
                            fill="#8884d8"
                            dataKey="value"
                          >
                            {runResult.data.map((_: any, index: number) => (
                              <Cell
                                key={`cell-${index}`}
                                fill={['#3b82f6', '#10b981', '#f59e0b', '#ef4444'][index % 4]}
                              />
                            ))}
                          </Pie>
                          <RechartsTooltip />
                          <Legend />
                        </PieChart>
                      </ResponsiveContainer>
                    </Card>
                  )}

                  {/* 表格 */}
                  {runResult.type === 'table' && (
                    <Card>
                      <Table>
                        <TableHeader>
                          <TableRow>
                            {runResult.columns.map((col: string) => (
                              <TableHead key={col}>{col}</TableHead>
                            ))}
                          </TableRow>
                        </TableHeader>
                        <TableBody>
                          {runResult.data.map((row: string[], idx: number) => (
                            <TableRow key={idx}>
                              {row.map((cell: string, cellIdx: number) => (
                                <TableCell key={cellIdx}>{cell}</TableCell>
                              ))}
                            </TableRow>
                          ))}
                        </TableBody>
                      </Table>
                    </Card>
                  )}

                  {/* 文字 */}
                  {runResult.type === 'text' && (
                    <Card className="p-6">
                      <div className="whitespace-pre-wrap text-sm leading-relaxed">
                        {runResult.content}
                      </div>
                    </Card>
                  )}

                  {/* 运行成功提示 */}
                  <Card className="p-4 bg-green-50 border-green-200 mt-4">
                    <div className="flex items-center gap-2 text-green-800">
                      <CheckCircle className="w-4 h-4" />
                      <span className="text-sm">应用运行成功！结果已生成。</span>
                    </div>
                  </Card>
                </div>
              )}
            </div>
          )}

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

      {/* 应用生成多步骤对话框 */}
      <Dialog open={showGenerateDialog} onOpenChange={setShowGenerateDialog}>
        <DialogContent className="max-w-4xl max-h-[90vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle className="flex items-center gap-2">
              <Sparkles className="w-5 h-5 text-blue-600" />
              创建应用 - {['填写基本信息', '选择模型', '配置输入', '配置输出', '预览发布'][generateStep - 1]}
            </DialogTitle>
            <DialogDescription>
              步骤 {generateStep} / 5
            </DialogDescription>
          </DialogHeader>

          {/* 步骤指示器 */}
          <div className="flex items-center justify-between mb-6">
            {[1, 2, 3, 4, 5].map((step) => (
              <div key={step} className="flex items-center">
                <div className="flex flex-col items-center">
                  <div
                    className={`w-10 h-10 rounded-full flex items-center justify-center transition-all ${
                      getStepStatus(step) === 'completed'
                        ? 'bg-green-500 text-white'
                        : getStepStatus(step) === 'current'
                        ? 'bg-blue-500 text-white'
                        : 'bg-gray-200 text-gray-500'
                    }`}
                  >
                    {getStepStatus(step) === 'completed' ? (
                      <CheckCircle className="w-5 h-5" />
                    ) : (
                      step
                    )}
                  </div>
                  <p className="text-xs mt-2 text-center">
                    {['基本信息', '选择模型', '配置输入', '配置输出', '预览发布'][step - 1]}
                  </p>
                </div>
                {step < 5 && (
                  <div
                    className={`w-16 h-1 mx-2 ${
                      getStepStatus(step) === 'completed' ? 'bg-green-500' : 'bg-gray-200'
                    }`}
                  />
                )}
              </div>
            ))}
          </div>

          {/* 步骤1: 填写基本信息 */}
          {generateStep === 1 && (
            <div className="space-y-4">
              <Card className="p-4 bg-blue-50 border-blue-200">
                <div className="flex items-center gap-2 text-blue-900">
                  <FileText className="w-4 h-4" />
                  <span className="text-sm">请填写应用的基本信息</span>
                </div>
              </Card>

              <div>
                <Label>应用名称 *</Label>
                <Input
                  placeholder="请输入应用名称，如：智能灌溉策略生成"
                  value={newAppData.name}
                  onChange={(e) => setNewAppData({ ...newAppData, name: e.target.value })}
                />
              </div>

              <div>
                <Label>应用类型 *</Label>
                <Select
                  value={newAppData.type}
                  onValueChange={(value) => setNewAppData({ ...newAppData, type: value as ApplicationType })}
                >
                  <SelectTrigger>
                    <SelectValue placeholder="选择应用类型" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="智能灌溉">
                      <div className="flex items-center gap-2">
                        <Droplets className="w-4 h-4 text-green-600" />
                        智能灌溉
                      </div>
                    </SelectItem>
                    <SelectItem value="病虫害预警">
                      <div className="flex items-center gap-2">
                        <Bug className="w-4 h-4 text-orange-600" />
                        病虫害预警
                      </div>
                    </SelectItem>
                    <SelectItem value="施肥推荐">
                      <div className="flex items-center gap-2">
                        <Sprout className="w-4 h-4 text-purple-600" />
                        施肥推荐
                      </div>
                    </SelectItem>
                    <SelectItem value="产量预测">
                      <div className="flex items-center gap-2">
                        <TrendingUp className="w-4 h-4 text-blue-600" />
                        产量预测
                      </div>
                    </SelectItem>
                    <SelectItem value="生长监测">
                      <div className="flex items-center gap-2">
                        <Activity className="w-4 h-4 text-cyan-600" />
                        生长监测
                      </div>
                    </SelectItem>
                    <SelectItem value="其他">其他</SelectItem>
                  </SelectContent>
                </Select>
              </div>

              <div>
                <Label>应用描述 *</Label>
                <Textarea
                  placeholder="请输入应用的详细描述，包括功能、使用场景等"
                  value={newAppData.description}
                  onChange={(e) => setNewAppData({ ...newAppData, description: e.target.value })}
                  rows={4}
                />
              </div>
            </div>
          )}

          {/* 步骤2: 选择模型 */}
          {generateStep === 2 && (
            <div className="space-y-4">
              <Card className="p-4 bg-purple-50 border-purple-200">
                <div className="flex items-center gap-2 text-purple-900">
                  <Server className="w-4 h-4" />
                  <span className="text-sm">选择用于此应用的AI模型</span>
                </div>
              </Card>

              <div>
                <Label>选择模型 *</Label>
                <div className="grid grid-cols-1 gap-3 mt-2">
                  {availableModels.map((model) => (
                    <div
                      key={model.id}
                      className={`p-4 border-2 rounded-lg cursor-pointer transition-all ${
                        newAppData.modelName === model.name
                          ? 'border-blue-500 bg-blue-50'
                          : 'border-gray-200 hover:border-blue-300'
                      }`}
                      onClick={() =>
                        setNewAppData({
                          ...newAppData,
                          modelName: model.name,
                          modelVersion: model.version,
                        })
                      }
                    >
                      <div className="flex items-center justify-between">
                        <div className="flex items-center gap-3">
                          <div className="w-10 h-10 bg-blue-100 rounded-lg flex items-center justify-center">
                            <Cpu className="w-5 h-5 text-blue-600" />
                          </div>
                          <div>
                            <div className="font-medium">{model.name}</div>
                            <div className="text-xs text-muted-foreground">
                              {model.version} • {model.type}
                            </div>
                          </div>
                        </div>
                        <Badge className="bg-green-100 text-green-700 border-green-300">
                          {model.status}
                        </Badge>
                      </div>
                    </div>
                  ))}
                </div>
              </div>
            </div>
          )}

          {/* 步骤3: 配置输入 */}
          {generateStep === 3 && (
            <div className="space-y-4">
              <Card className="p-4 bg-green-50 border-green-200">
                <div className="flex items-center gap-2 text-green-900">
                  <FileText className="w-4 h-4" />
                  <span className="text-sm">配置应用的输入字段</span>
                </div>
              </Card>

              <div>
                <Label>输入字段 * (选择至少一个)</Label>
                <div className="grid grid-cols-2 md:grid-cols-3 gap-3 mt-2 max-h-64 overflow-y-auto p-2 border rounded-lg">
                  {inputFieldOptions.map((field) => (
                    <div key={field} className="flex items-center space-x-2">
                      <Checkbox
                        id={field}
                        checked={newAppData.inputFields.includes(field)}
                        onCheckedChange={(checked) => {
                          if (checked) {
                            setNewAppData({
                              ...newAppData,
                              inputFields: [...newAppData.inputFields, field],
                            });
                          } else {
                            setNewAppData({
                              ...newAppData,
                              inputFields: newAppData.inputFields.filter((f) => f !== field),
                            });
                          }
                        }}
                      />
                      <label htmlFor={field} className="text-sm cursor-pointer">
                        {field}
                      </label>
                    </div>
                  ))}
                </div>
                <p className="text-xs text-muted-foreground mt-2">
                  已选择 {newAppData.inputFields.length} 个字段
                </p>
              </div>
            </div>
          )}

          {/* 步骤4: 配置输出 */}
          {generateStep === 4 && (
            <div className="space-y-4">
              <Card className="p-4 bg-orange-50 border-orange-200">
                <div className="flex items-center gap-2 text-orange-900">
                  <BarChart3 className="w-4 h-4" />
                  <span className="text-sm">配置应用的输出格式</span>
                </div>
              </Card>

              <div>
                <Label>输出格式 *</Label>
                <div className="grid grid-cols-2 gap-3 mt-2">
                  <div
                    className={`p-4 border-2 rounded-lg cursor-pointer transition-all ${
                      newAppData.outputFormat === '折线图'
                        ? 'border-blue-500 bg-blue-50'
                        : 'border-gray-200 hover:border-blue-300'
                    }`}
                    onClick={() => setNewAppData({ ...newAppData, outputFormat: '折线图' })}
                  >
                    <div className="flex items-center gap-3">
                      <div className="w-10 h-10 bg-blue-100 rounded-lg flex items-center justify-center">
                        <LineChartIcon className="w-5 h-5 text-blue-600" />
                      </div>
                      <div>
                        <div className="font-medium">折线图</div>
                        <div className="text-xs text-muted-foreground">趋势数据可视化</div>
                      </div>
                    </div>
                  </div>

                  <div
                    className={`p-4 border-2 rounded-lg cursor-pointer transition-all ${
                      newAppData.outputFormat === '饼状图'
                        ? 'border-green-500 bg-green-50'
                        : 'border-gray-200 hover:border-green-300'
                    }`}
                    onClick={() => setNewAppData({ ...newAppData, outputFormat: '饼状图' })}
                  >
                    <div className="flex items-center gap-3">
                      <div className="w-10 h-10 bg-green-100 rounded-lg flex items-center justify-center">
                        <PieChartIcon className="w-5 h-5 text-green-600" />
                      </div>
                      <div>
                        <div className="font-medium">饼状图</div>
                        <div className="text-xs text-muted-foreground">占比分布展示</div>
                      </div>
                    </div>
                  </div>

                  <div
                    className={`p-4 border-2 rounded-lg cursor-pointer transition-all ${
                      newAppData.outputFormat === '表格'
                        ? 'border-purple-500 bg-purple-50'
                        : 'border-gray-200 hover:border-purple-300'
                    }`}
                    onClick={() => setNewAppData({ ...newAppData, outputFormat: '表格' })}
                  >
                    <div className="flex items-center gap-3">
                      <div className="w-10 h-10 bg-purple-100 rounded-lg flex items-center justify-center">
                        <TableIcon className="w-5 h-5 text-purple-600" />
                      </div>
                      <div>
                        <div className="font-medium">表格</div>
                        <div className="text-xs text-muted-foreground">结构化数据展示</div>
                      </div>
                    </div>
                  </div>

                  <div
                    className={`p-4 border-2 rounded-lg cursor-pointer transition-all ${
                      newAppData.outputFormat === '文字'
                        ? 'border-primary bg-muted'
                        : 'border-border hover:border-muted-foreground'
                    }`}
                    onClick={() => setNewAppData({ ...newAppData, outputFormat: '文字' })}
                  >
                    <div className="flex items-center gap-3">
                      <div className="w-10 h-10 bg-accent rounded-lg flex items-center justify-center">
                        <Type className="w-5 h-5 text-muted-foreground" />
                      </div>
                      <div>
                        <div className="font-medium">文字</div>
                        <div className="text-xs text-muted-foreground">文本描述输出</div>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          )}

          {/* 步骤5: 预览发布 */}
          {generateStep === 5 && (
            <div className="space-y-4">
              <Card className="p-4 bg-cyan-50 border-cyan-200">
                <div className="flex items-center gap-2 text-cyan-900">
                  <Eye className="w-4 h-4" />
                  <span className="text-sm">预览应用配置，确认无误后发布</span>
                </div>
              </Card>

              <Card className="p-6">
                <h4 className="mb-4 flex items-center gap-2">
                  <Rocket className="w-5 h-5 text-blue-600" />
                  应用配置预览
                </h4>

                <div className="space-y-4">
                  <div className="grid grid-cols-2 gap-4">
                    <div>
                      <Label>应用名称</Label>
                      <div className="field-value">{newAppData.name}</div>
                    </div>
                    <div>
                      <Label>应用类型</Label>
                      <div className="field-value">
                        <Badge variant="outline">{newAppData.type}</Badge>
                      </div>
                    </div>
                  </div>

                  <div>
                    <Label>应用描述</Label>
                    <div className="field-value">{newAppData.description}</div>
                  </div>

                  <div className="grid grid-cols-2 gap-4">
                    <div>
                      <Label>使用模型</Label>
                      <div className="field-value">{newAppData.modelName}</div>
                    </div>
                    <div>
                      <Label>模型版本</Label>
                      <div className="field-value">{newAppData.modelVersion}</div>
                    </div>
                  </div>

                  <div>
                    <Label>输入字段</Label>
                    <div className="field-value">
                      <div className="flex flex-wrap gap-2">
                        {newAppData.inputFields.map((field) => (
                          <Badge key={field} variant="outline">
                            {field}
                          </Badge>
                        ))}
                      </div>
                    </div>
                  </div>

                  <div>
                    <Label>输出格式</Label>
                    <div className="field-value">
                      <div className="flex items-center gap-2">
                        {newAppData.outputFormat && getOutputFormatIcon(newAppData.outputFormat as OutputFormat)}
                        <Badge className="bg-purple-100 text-purple-700 border-purple-300">
                          {newAppData.outputFormat}
                        </Badge>
                      </div>
                    </div>
                  </div>
                </div>
              </Card>

              <Card className="p-4 bg-yellow-50 border-yellow-300">
                <div className="flex items-center gap-2 text-yellow-800">
                  <AlertTriangle className="w-4 h-4" />
                  <span className="text-sm">
                    发布后应用将进入测试状态，您可以在应用列表中启动或停止应用
                  </span>
                </div>
              </Card>
            </div>
          )}

          <DialogFooter>
            <div className="flex justify-between w-full">
              <div>
                {generateStep > 1 && (
                  <Button variant="outline" onClick={handlePrevStep}>
                    <ChevronLeft className="w-4 h-4 mr-2" />
                    上一步
                  </Button>
                )}
              </div>
              <div className="flex gap-2">
                <Button variant="outline" onClick={() => setShowGenerateDialog(false)}>
                  取消
                </Button>
                {generateStep < 5 ? (
                  <Button className="bg-blue-600 hover:bg-blue-700" onClick={handleNextStep}>
                    下一步
                    <ChevronRight className="w-4 h-4 ml-2" />
                  </Button>
                ) : (
                  <Button className="bg-green-600 hover:bg-green-700" onClick={handlePublishApp}>
                    <Rocket className="w-4 h-4 mr-2" />
                    发布应用
                  </Button>
                )}
              </div>
            </div>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* 应用编辑多步骤对话框 */}
      <Dialog open={showEditDialog} onOpenChange={setShowEditDialog}>
        <DialogContent className="max-w-4xl max-h-[90vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle className="flex items-center gap-2">
              <Edit className="w-5 h-5 text-blue-600" />
              编辑应用 - {['填写基本信息', '选择模型', '配置输入', '配置输出', '预览保存'][editStep - 1]}
            </DialogTitle>
            <DialogDescription>
              步骤 {editStep} / 5
            </DialogDescription>
          </DialogHeader>

          {/* 步骤指示器 */}
          <div className="flex items-center justify-between mb-6">
            {[1, 2, 3, 4, 5].map((step) => (
              <div key={step} className="flex items-center">
                <div className="flex flex-col items-center">
                  <div
                    className={`w-10 h-10 rounded-full flex items-center justify-center transition-all ${
                      getEditStepStatus(step) === 'completed'
                        ? 'bg-green-500 text-white'
                        : getEditStepStatus(step) === 'current'
                        ? 'bg-blue-500 text-white'
                        : 'bg-gray-200 text-gray-500'
                    }`}
                  >
                    {getEditStepStatus(step) === 'completed' ? (
                      <CheckCircle className="w-5 h-5" />
                    ) : (
                      step
                    )}
                  </div>
                  <p className="text-xs mt-2 text-center">
                    {['基本信息', '选择模型', '配置输入', '配置输出', '预览保存'][step - 1]}
                  </p>
                </div>
                {step < 5 && (
                  <div
                    className={`w-16 h-1 mx-2 ${
                      getEditStepStatus(step) === 'completed' ? 'bg-green-500' : 'bg-gray-200'
                    }`}
                  />
                )}
              </div>
            ))}
          </div>

          {/* 步骤1: 填写基本信息 */}
          {editStep === 1 && (
            <div className="space-y-4">
              <Card className="p-4 bg-blue-50 border-blue-200">
                <div className="flex items-center gap-2 text-blue-900">
                  <FileText className="w-4 h-4" />
                  <span className="text-sm">请填写应用的基本信息</span>
                </div>
              </Card>

              <div>
                <Label>应用名称 *</Label>
                <Input
                  placeholder="请输入应用名称，如：智能灌溉策略生成"
                  value={editAppData.name}
                  onChange={(e) => setEditAppData({ ...editAppData, name: e.target.value })}
                />
              </div>

              <div>
                <Label>应用类型 *</Label>
                <Select
                  value={editAppData.type}
                  onValueChange={(value) => setEditAppData({ ...editAppData, type: value as ApplicationType })}
                >
                  <SelectTrigger>
                    <SelectValue placeholder="选择应用类型" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="智能灌溉">
                      <div className="flex items-center gap-2">
                        <Droplets className="w-4 h-4 text-green-600" />
                        智能灌溉
                      </div>
                    </SelectItem>
                    <SelectItem value="病虫害预警">
                      <div className="flex items-center gap-2">
                        <Bug className="w-4 h-4 text-orange-600" />
                        病虫害预警
                      </div>
                    </SelectItem>
                    <SelectItem value="施肥推荐">
                      <div className="flex items-center gap-2">
                        <Sprout className="w-4 h-4 text-purple-600" />
                        施肥推荐
                      </div>
                    </SelectItem>
                    <SelectItem value="产量预测">
                      <div className="flex items-center gap-2">
                        <TrendingUp className="w-4 h-4 text-blue-600" />
                        产量预测
                      </div>
                    </SelectItem>
                    <SelectItem value="生长监测">
                      <div className="flex items-center gap-2">
                        <Activity className="w-4 h-4 text-cyan-600" />
                        生长监测
                      </div>
                    </SelectItem>
                    <SelectItem value="其他">其他</SelectItem>
                  </SelectContent>
                </Select>
              </div>

              <div>
                <Label>应用描述 *</Label>
                <Textarea
                  placeholder="请输入应用的详细描述，包括功能、使用场景等"
                  value={editAppData.description}
                  onChange={(e) => setEditAppData({ ...editAppData, description: e.target.value })}
                  rows={4}
                />
              </div>
            </div>
          )}

          {/* 步骤2: 选择模型 */}
          {editStep === 2 && (
            <div className="space-y-4">
              <Card className="p-4 bg-purple-50 border-purple-200">
                <div className="flex items-center gap-2 text-purple-900">
                  <Server className="w-4 h-4" />
                  <span className="text-sm">选择用于此应用的AI模型</span>
                </div>
              </Card>

              <div>
                <Label>选择模型 *</Label>
                <div className="grid grid-cols-1 gap-3 mt-2">
                  {availableModels.map((model) => (
                    <div
                      key={model.id}
                      className={`p-4 border-2 rounded-lg cursor-pointer transition-all ${
                        editAppData.modelName === model.name
                          ? 'border-blue-500 bg-blue-50'
                          : 'border-gray-200 hover:border-blue-300'
                      }`}
                      onClick={() =>
                        setEditAppData({
                          ...editAppData,
                          modelName: model.name,
                          modelVersion: model.version,
                        })
                      }
                    >
                      <div className="flex items-center justify-between">
                        <div className="flex items-center gap-3">
                          <div className="w-10 h-10 bg-blue-100 rounded-lg flex items-center justify-center">
                            <Cpu className="w-5 h-5 text-blue-600" />
                          </div>
                          <div>
                            <div className="font-medium">{model.name}</div>
                            <div className="text-xs text-muted-foreground">
                              {model.version} • {model.type}
                            </div>
                          </div>
                        </div>
                        <Badge className="bg-green-100 text-green-700 border-green-300">
                          {model.status}
                        </Badge>
                      </div>
                    </div>
                  ))}
                </div>
              </div>
            </div>
          )}

          {/* 步骤3: 配置输入 */}
          {editStep === 3 && (
            <div className="space-y-4">
              <Card className="p-4 bg-green-50 border-green-200">
                <div className="flex items-center gap-2 text-green-900">
                  <FileText className="w-4 h-4" />
                  <span className="text-sm">配置应用的输入字段</span>
                </div>
              </Card>

              <div>
                <Label>输入字段 * (选择至少一个)</Label>
                <div className="grid grid-cols-2 md:grid-cols-3 gap-3 mt-2 max-h-64 overflow-y-auto p-2 border rounded-lg">
                  {inputFieldOptions.map((field) => (
                    <div key={field} className="flex items-center space-x-2">
                      <Checkbox
                        id={`edit-${field}`}
                        checked={editAppData.inputFields.includes(field)}
                        onCheckedChange={(checked) => {
                          if (checked) {
                            setEditAppData({
                              ...editAppData,
                              inputFields: [...editAppData.inputFields, field],
                            });
                          } else {
                            setEditAppData({
                              ...editAppData,
                              inputFields: editAppData.inputFields.filter((f) => f !== field),
                            });
                          }
                        }}
                      />
                      <label htmlFor={`edit-${field}`} className="text-sm cursor-pointer">
                        {field}
                      </label>
                    </div>
                  ))}
                </div>
                <p className="text-xs text-muted-foreground mt-2">
                  已选择 {editAppData.inputFields.length} 个字段
                </p>
              </div>
            </div>
          )}

          {/* 步骤4: 配置输出 */}
          {editStep === 4 && (
            <div className="space-y-4">
              <Card className="p-4 bg-orange-50 border-orange-200">
                <div className="flex items-center gap-2 text-orange-900">
                  <BarChart3 className="w-4 h-4" />
                  <span className="text-sm">配置应用的输出格式</span>
                </div>
              </Card>

              <div>
                <Label>输出格式 *</Label>
                <div className="grid grid-cols-2 gap-3 mt-2">
                  <div
                    className={`p-4 border-2 rounded-lg cursor-pointer transition-all ${
                      editAppData.outputFormat === '折线图'
                        ? 'border-blue-500 bg-blue-50'
                        : 'border-gray-200 hover:border-blue-300'
                    }`}
                    onClick={() => setEditAppData({ ...editAppData, outputFormat: '折线图' })}
                  >
                    <div className="flex items-center gap-3">
                      <div className="w-10 h-10 bg-blue-100 rounded-lg flex items-center justify-center">
                        <LineChartIcon className="w-5 h-5 text-blue-600" />
                      </div>
                      <div>
                        <div className="font-medium">折线图</div>
                        <div className="text-xs text-muted-foreground">趋势数据可视化</div>
                      </div>
                    </div>
                  </div>

                  <div
                    className={`p-4 border-2 rounded-lg cursor-pointer transition-all ${
                      editAppData.outputFormat === '饼状图'
                        ? 'border-green-500 bg-green-50'
                        : 'border-gray-200 hover:border-green-300'
                    }`}
                    onClick={() => setEditAppData({ ...editAppData, outputFormat: '饼状图' })}
                  >
                    <div className="flex items-center gap-3">
                      <div className="w-10 h-10 bg-green-100 rounded-lg flex items-center justify-center">
                        <PieChartIcon className="w-5 h-5 text-green-600" />
                      </div>
                      <div>
                        <div className="font-medium">饼状图</div>
                        <div className="text-xs text-muted-foreground">占比分布展示</div>
                      </div>
                    </div>
                  </div>

                  <div
                    className={`p-4 border-2 rounded-lg cursor-pointer transition-all ${
                      editAppData.outputFormat === '表格'
                        ? 'border-purple-500 bg-purple-50'
                        : 'border-gray-200 hover:border-purple-300'
                    }`}
                    onClick={() => setEditAppData({ ...editAppData, outputFormat: '表格' })}
                  >
                    <div className="flex items-center gap-3">
                      <div className="w-10 h-10 bg-purple-100 rounded-lg flex items-center justify-center">
                        <TableIcon className="w-5 h-5 text-purple-600" />
                      </div>
                      <div>
                        <div className="font-medium">表格</div>
                        <div className="text-xs text-muted-foreground">结构化数据展示</div>
                      </div>
                    </div>
                  </div>

                  <div
                    className={`p-4 border-2 rounded-lg cursor-pointer transition-all ${
                      editAppData.outputFormat === '文字'
                        ? 'border-gray-500 bg-gray-50'
                        : 'border-gray-200 hover:border-gray-300'
                    }`}
                    onClick={() => setEditAppData({ ...editAppData, outputFormat: '文字' })}
                  >
                    <div className="flex items-center gap-3">
                      <div className="w-10 h-10 bg-accent rounded-lg flex items-center justify-center">
                        <Type className="w-5 h-5 text-muted-foreground" />
                      </div>
                      <div>
                        <div className="font-medium">文字</div>
                        <div className="text-xs text-muted-foreground">文本描述输出</div>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          )}

          {/* 步骤5: 预览保存 */}
          {editStep === 5 && (
            <div className="space-y-4">
              <Card className="p-4 bg-cyan-50 border-cyan-200">
                <div className="flex items-center gap-2 text-cyan-900">
                  <Eye className="w-4 h-4" />
                  <span className="text-sm">预览应用配置，确认无误后保存</span>
                </div>
              </Card>

              <Card className="p-6">
                <h4 className="mb-4 flex items-center gap-2">
                  <Rocket className="w-5 h-5 text-blue-600" />
                  应用配置预览
                </h4>

                <div className="space-y-4">
                  <div className="grid grid-cols-2 gap-4">
                    <div>
                      <Label>应用名称</Label>
                      <div className="field-value">{editAppData.name}</div>
                    </div>
                    <div>
                      <Label>应用类型</Label>
                      <div className="field-value">
                        <Badge variant="outline">{editAppData.type}</Badge>
                      </div>
                    </div>
                  </div>

                  <div>
                    <Label>应用描述</Label>
                    <div className="field-value">{editAppData.description}</div>
                  </div>

                  <div className="grid grid-cols-2 gap-4">
                    <div>
                      <Label>使用模型</Label>
                      <div className="field-value">{editAppData.modelName}</div>
                    </div>
                    <div>
                      <Label>模型版本</Label>
                      <div className="field-value">{editAppData.modelVersion}</div>
                    </div>
                  </div>

                  <div>
                    <Label>输入字段</Label>
                    <div className="field-value">
                      <div className="flex flex-wrap gap-2">
                        {editAppData.inputFields.map((field) => (
                          <Badge key={field} variant="outline">
                            {field}
                          </Badge>
                        ))}
                      </div>
                    </div>
                  </div>

                  <div>
                    <Label>输出格式</Label>
                    <div className="field-value">
                      <div className="flex items-center gap-2">
                        {editAppData.outputFormat && getOutputFormatIcon(editAppData.outputFormat as OutputFormat)}
                        <Badge className="bg-purple-100 text-purple-700 border-purple-300">
                          {editAppData.outputFormat}
                        </Badge>
                      </div>
                    </div>
                  </div>
                </div>
              </Card>

              <Card className="p-4 bg-yellow-50 border-yellow-300">
                <div className="flex items-center gap-2 text-yellow-800">
                  <AlertTriangle className="w-4 h-4" />
                  <span className="text-sm">
                    保存后将更新应用配置，请确认修改内容正确
                  </span>
                </div>
              </Card>
            </div>
          )}

          <DialogFooter>
            <div className="flex justify-between w-full">
              <div>
                {editStep > 1 && (
                  <Button variant="outline" onClick={handleEditPrevStep}>
                    <ChevronLeft className="w-4 h-4 mr-2" />
                    上一步
                  </Button>
                )}
              </div>
              <div className="flex gap-2">
                <Button variant="outline" onClick={() => setShowEditDialog(false)}>
                  取消
                </Button>
                {editStep < 5 ? (
                  <Button className="bg-blue-600 hover:bg-blue-700" onClick={handleEditNextStep}>
                    下一步
                    <ChevronRight className="w-4 h-4 ml-2" />
                  </Button>
                ) : (
                  <Button className="bg-green-600 hover:bg-green-700" onClick={handleSaveEdit}>
                    <CheckCircle className="w-4 h-4 mr-2" />
                    保存修改
                  </Button>
                )}
              </div>
            </div>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
}
