/**
 * filekorolheader: 决策模拟页面 - AI决策推演与执行验证
 * 功能：场景筛选、模拟运行、执行监控、结果复盘、指标对比
 * 路径：ai-crop-model/decision/simulation
 * 规范：参考 crop-x/docs/开发项目规范.md，1:1 复刻组件实现
 */
'use client';

import { useState } from 'react';
import { Card } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { Input } from '@/components/ui/input';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription, DialogFooter } from '@/components/ui/dialog';
import { Label } from '@/components/ui/label';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';
import { Progress } from '@/components/ui/progress';
import { cn } from '@/lib/utils';
import {
  Beaker,
  Search,
  RefreshCw,
  CheckCircle,
  AlertCircle,
  Settings,
  Eye,
  Play,
  RotateCcw,
  BarChart3,
  Activity,
  Clock,
  Filter,
  Target,
  Zap,
  TrendingUp,
  BookOpen,
  Database,
  Cpu,
  ArrowRight,
  Info,
  Lightbulb,
  CheckCircle2,
  XCircle,
  AlertTriangle,
  GitCompare,
  Scale,
  FileCode,
  Gauge,
  Sparkles,
  ListChecks,
  ThumbsUp,
  ThumbsDown,
  Copy,
  Save,
  FileText,
  Boxes,
  Workflow,
  Layers,
  Brain,
  Plus,
} from 'lucide-react';
import { toast } from 'sonner';
import {
  LineChart,
  Line,
  BarChart,
  Bar,
  XAxis,
  YAxis,
  CartesianGrid,
  Tooltip as RechartsTooltip,
  Legend,
  ResponsiveContainer,
  RadarChart,
  PolarGrid,
  PolarAngleAxis,
  PolarRadiusAxis,
  Radar,
  ScatterChart,
  Scatter,
  Cell,
} from 'recharts';

interface AIDecisionSimulationProps {
  activePath?: string;
}

// 模拟场景类型
type ScenarioCategory = 'irrigation' | 'pest' | 'fertilizer' | 'harvest' | 'weather' | 'custom';

// 模拟状态
type SimulationStatus = 'idle' | 'running' | 'completed' | 'failed';

// 决策评估等级
type EvaluationLevel = 'excellent' | 'good' | 'fair' | 'poor';

// 决策来源类型
type DecisionSource = 'auto' | 'manual';

// 预设场景（来自模型应用）
interface PresetScenario {
  id: string;
  name: string;
  category: ScenarioCategory;
  description: string;
  inputData: {
    [key: string]: any;
  };
  expectedOutcome: string;
  difficulty: 'simple' | 'medium' | 'complex';
  modelName: string;
  modelVersion: string;
  source: DecisionSource; // 决策来源：auto-自动生成，manual-手动添加
  createdAt?: string; // 创建时间
  createdBy?: string; // 创建人
}

// 模拟结果
interface SimulationResult {
  id: string;
  scenarioId: string;
  scenarioName: string;
  status: SimulationStatus;
  startTime: string;
  endTime?: string;
  executionTime: number;
  decision: {
    recommendation: string;
    confidence: number;
    level: 'critical' | 'important' | 'normal' | 'suggestion';
    reasoning: string;
    actionItems: string[];
  };
  rulesApplied: {
    ruleId: string;
    ruleName: string;
    matched: boolean;
    priority: number;
    weight: number;
  }[];
  evaluation: {
    level: EvaluationLevel;
    score: number;
    accuracy: number;
    reliability: number;
    practicality: number;
    feedback: string;
  };
  parameters: {
    [key: string]: any;
  };
}

// 对比方案（已废弃，改为直接使用模拟结果）
interface ComparisonPlan {
  id: string;
  name: string;
  scenario: string;
  parameters: {
    [key: string]: any;
  };
  result?: SimulationResult;
}

// 对比项（使用模拟结果）
interface ComparisonItem {
  resultId: string;
  result: SimulationResult;
}

function AIDecisionSimulation({ activePath }: AIDecisionSimulationProps) {
  const [activeTab, setActiveTab] = useState('scenarios');
  const [showResultDialog, setShowResultDialog] = useState(false);
  const [showComparisonDialog, setShowComparisonDialog] = useState(false);
  const [showParameterDialog, setShowParameterDialog] = useState(false);
  const [showEnvironmentDialog, setShowEnvironmentDialog] = useState(false);
  const [showSelectResultDialog, setShowSelectResultDialog] = useState(false);
  const [selectedScenario, setSelectedScenario] = useState<PresetScenario | null>(null);
  const [selectedResult, setSelectedResult] = useState<SimulationResult | null>(null);
  const [currentSimulation, setCurrentSimulation] = useState<SimulationResult | null>(null);
  const [simulationProgress, setSimulationProgress] = useState(0);
  const [pendingScenario, setPendingScenario] = useState<PresetScenario | null>(null);
  const [selectedEnvironmentData, setSelectedEnvironmentData] = useState({
    temperature: 28,
    humidity: 65,
    soilMoisture: 35,
    rainfall: 0,
    windSpeed: 2.5,
    lightIntensity: 85000,
  });

  // 预设场景数据（来自业务融合生成的决策数据）
  const [presetScenarios, setPresetScenarios] = useState<PresetScenario[]>([
    {
      id: 'preset_1',
      name: '3号大棚灌溉决策',
      category: 'irrigation',
      description: '综合分析土壤湿度、天气预报、作物需水量等多维数据，生成精准灌溉方案',
      source: 'auto',
      createdAt: '2024-10-23 10:35:00',
      inputData: {
        cropType: '番茄',
        variety: '金粉808',
        growthStage: '开花期',
        fieldId: 'field_003',
        fieldName: '3号大棚',
        soilMoisture: 35,
        temperature: 28,
        humidity: 65,
        rainfall: 0,
        forecast: '未来3天无降雨',
      },
      expectedOutcome: '建议在今天傍晚17:00-18:00进行灌溉，灌溉量120升，持续时间45分钟',
      difficulty: 'medium',
      modelName: '灌溉需求预测模型',
      modelVersion: 'v2.1.3',
    },
    {
      id: 'preset_2',
      name: '番茄早疫病防治决策',
      category: 'pest',
      description: '基于病虫害识别模型和防治规则，生成科学的病虫害防治方案',
      source: 'auto',
      createdAt: '2024-10-23 10:32:00',
      inputData: {
        cropType: '番茄',
        diseaseType: '早疫病',
        severity: '轻度',
        affectedArea: 5,
        lastTreatment: '10月15日',
        daysAfterTreatment: 8,
      },
      expectedOutcome: '采用生物防治方案，使用枯草芽孢杆菌制剂，每7天喷施一次，连续3次',
      difficulty: 'medium',
      modelName: '病虫害识别模型',
      modelVersion: 'v3.2.0',
    },
    {
      id: 'preset_3',
      name: '番茄高产栽培决策',
      category: 'fertilizer',
      description: '基于生长预测模型和高产栽培规则，提供精细化管理方案',
      source: 'auto',
      createdAt: '2024-10-23 09:15:00',
      inputData: {
        cropType: '番茄',
        variety: '金粉808',
        growthStage: '开花期',
        healthScore: 92,
        predictedYield: 8500,
        currentYield: 7200,
      },
      expectedOutcome: '当前番茄长势良好，预测产量达8500kg/亩，建议加强精细化管理，冲刺高产目标',
      difficulty: 'complex',
      modelName: '番茄生长预测模型',
      modelVersion: 'v2.5.1',
    },
    {
      id: 'preset_4',
      name: '1号大棚温度调控决策',
      category: 'weather',
      description: '实时监测大棚环境，智能调控温湿度，保障作物最佳生长条件',
      source: 'auto',
      createdAt: '2024-10-23 08:45:00',
      inputData: {
        fieldId: 'field_001',
        fieldName: '1号大棚',
        currentTemp: 32,
        targetTemp: 26,
        humidity: 68,
        outsideTemp: 35,
        growthStage: '开花期',
      },
      expectedOutcome: '白天温度偏高，建议开启通风系统，控制温度在25-28℃范围内',
      difficulty: 'medium',
      modelName: '环境监测模型',
      modelVersion: 'v1.9.0',
    },
  ]);

  // 模拟结果历史
  const [simulationResults, setSimulationResults] = useState<SimulationResult[]>([
    {
      id: 'result_1',
      scenarioId: 'preset_1',
      scenarioName: '3号大棚灌溉决策',
      status: 'completed',
      startTime: '2024-10-23 10:35:00',
      endTime: '2024-10-23 10:35:02',
      executionTime: 2.3,
      decision: {
        recommendation: '建议在今天傍晚17:00-18:00进行灌溉，灌溉量120升，持续时间45分钟',
        confidence: 0.89,
        level: 'important',
        reasoning: '综合分析：\n1. 土壤湿度35%，低于开花期最佳湿度(60-70%)\n2. 未来3天无降雨，蒸发量较大\n3. 开花期是需水关键期\n4. 上次灌溉已过3天',
        actionItems: [
          '准备灌溉设备，检查管道和喷头',
          '在17:00开始灌溉，避开高温时段',
          '灌溉总量控制在120升，持续约45分钟',
          '灌溉后检查土壤湿度，确保达到60%以上',
          '记录灌溉时间和用水量',
        ],
      },
      rulesApplied: [
        {
          ruleId: 'rule_1',
          ruleName: '开花期灌溉规则',
          matched: true,
          priority: 9,
          weight: 0.9,
        },
        {
          ruleId: 'rule_2',
          ruleName: '干旱预警规则',
          matched: true,
          priority: 9,
          weight: 0.88,
        },
      ],
      evaluation: {
        level: 'excellent',
        score: 92,
        accuracy: 95,
        reliability: 90,
        practicality: 91,
        feedback: '决策合理，符合农艺要求，具有很强的可操作性。建议参数设置准确，时间安排合理。',
      },
      parameters: {
        modelWeight: 0.6,
        ruleWeight: 0.5,
        contextWeight: 0.45,
        threshold: 0.75,
      },
    },
    {
      id: 'result_2',
      scenarioId: 'preset_2',
      scenarioName: '番茄早疫病防治决策',
      status: 'completed',
      startTime: '2024-10-23 10:32:00',
      endTime: '2024-10-23 10:32:03',
      executionTime: 2.8,
      decision: {
        recommendation: '采用生物防治方案，使用枯草芽孢杆菌制剂，每7天喷施一次，连续3次',
        confidence: 0.86,
        level: 'normal',
        reasoning: '综合分析：\n1. 早疫病识别准确，感染程度轻度\n2. 受感染面积5%，处于可控范围\n3. 早期阶段优先使用生物防治\n4. 距上次防治15天，可以重复防治',
        actionItems: [
          '采购枯草芽孢杆菌生物防治剂',
          '配制药液，按说明书比例稀释',
          '在傍晚或阴天进行喷施',
          '重点喷施发病叶片及周围植株',
          '7天后进行第二次喷施',
          '持续观察病情发展',
        ],
      },
      rulesApplied: [
        {
          ruleId: 'rule_3',
          ruleName: '早疫病防治规则',
          matched: true,
          priority: 8,
          weight: 0.85,
        },
      ],
      evaluation: {
        level: 'good',
        score: 85,
        accuracy: 87,
        reliability: 84,
        practicality: 84,
        feedback: '决策基本合理，生物防治方案符合绿色农业要求。建议加强监测频率，及时调整方案。',
      },
      parameters: {
        modelWeight: 0.8,
        ruleWeight: 0.6,
        contextWeight: 0.35,
        threshold: 0.7,
      },
    },
  ]);

  // 对比项列表（从模拟结果中选择）
  const [comparisonItems, setComparisonItems] = useState<ComparisonItem[]>([]);

  // 统计数据
  const simulationStats = {
    totalSimulations: simulationResults.length,
    successRate: (simulationResults.filter(r => r.status === 'completed').length / simulationResults.length * 100).toFixed(1),
    avgExecutionTime: (simulationResults.reduce((sum, r) => sum + r.executionTime, 0) / simulationResults.length).toFixed(2),
    avgScore: (simulationResults.reduce((sum, r) => sum + r.evaluation.score, 0) / simulationResults.length).toFixed(1),
  };

  // 评估等级分布
  const evaluationDistribution = [
    { name: '优秀', value: simulationResults.filter(r => r.evaluation.level === 'excellent').length, color: '#10b981' },
    { name: '良好', value: simulationResults.filter(r => r.evaluation.level === 'good').length, color: '#3b82f6' },
    { name: '一般', value: simulationResults.filter(r => r.evaluation.level === 'fair').length, color: '#f59e0b' },
    { name: '较差', value: simulationResults.filter(r => r.evaluation.level === 'poor').length, color: '#ef4444' },
  ];

  // 执行时间趋势
  const executionTimeTrend = simulationResults.map((result, index) => ({
    name: `模拟${index + 1}`,
    time: result.executionTime,
  }));

  const handleRunSimulation = (scenario: PresetScenario) => {
    // 保存待运行的场景，显示环境数据选择对话框
    setPendingScenario(scenario);
    setShowEnvironmentDialog(true);
  };

  const handleConfirmEnvironmentAndRun = () => {
    if (!pendingScenario) return;

    setShowEnvironmentDialog(false);

    // 生成基于环境数据的决策结果
    const generateDecisionBasedOnEnvironment = () => {
      const { temperature, humidity, soilMoisture, rainfall } = selectedEnvironmentData;
      
      // 根据环境数据生成具体决策
      let recommendation = '';
      let actionItems: string[] = [];
      let reasoning = '';
      let rationality = '';
      
      if (pendingScenario.name.includes('灌溉')) {
        recommendation = `根据当前环境数据（土壤湿度${soilMoisture}%，温度${temperature}℃，湿度${humidity}%），建议在今天傍晚17:00-18:00进行灌溉，灌溉量${Math.round(120 * (65 - soilMoisture) / 30)}升，持续时间约${Math.round(45 * (65 - soilMoisture) / 30)}分钟`;
        actionItems = [
          '准备灌溉设备，检查管道和喷头',
          `在17:00开始灌溉，避开高温时段（当前温度${temperature}℃）`,
          `灌溉总量控制在${Math.round(120 * (65 - soilMoisture) / 30)}升，持续约${Math.round(45 * (65 - soilMoisture) / 30)}分钟`,
          '灌溉后检查土壤湿度，确保达到60%以上',
          '记录灌溉时间和用水量',
        ];
        reasoning = `综合分析环境数据：\n1. 土壤湿度为${soilMoisture}%，${soilMoisture < 50 ? '低于' : '接近'}开花期最佳湿度(60-70%)\n2. 当前温度${temperature}℃，湿度${humidity}%，${rainfall > 0 ? '有降雨' : '无降雨'}，蒸发量${rainfall > 0 ? '较小' : '较大'}\n3. 当前处于开花期，是需水关键期\n因此建议${soilMoisture < 50 ? '尽快' : '适时'}灌溉，保证作物正常生长`;
        rationality = `✓ 合理性分析：\n1. 环境数据完整性：温度、湿度、土壤湿度、降雨量数据齐全，${soilMoisture < 50 ? '土壤湿度偏低' : '土壤湿度适中'}，决策依据充分\n2. 灌溉时机选择：选择傍晚时段避开高温，减少水分蒸发，符合农艺要求\n3. 灌溉量计算：根据${soilMoisture}%到60%的目标湿度差值，计算得${Math.round(120 * (65 - soilMoisture) / 30)}升，科学合理\n4. 作物生长阶段匹配：开花期需水量大，决策与生长阶段相符\n5. 风险评估：${rainfall > 0 ? '有降雨预期，可适当减少灌溉量' : '无降雨，建议按计划灌溉'}`;
      } else if (pendingScenario.name.includes('病虫害')) {
        recommendation = `根据环境监测（温度${temperature}℃，湿度${humidity}%），预警病虫害风险等级为${humidity > 70 ? '高' : '中'}，建议立即采取防治措施`;
        actionItems = [
          `检查作物叶片和茎秆，特别关注${humidity > 70 ? '潮湿' : '正常'}环境下的病斑`,
          `施用生物农药进行预防性防治`,
          `加强田间通风，降低湿度至60%以下`,
          `每2天监测一次病虫害发生情况`,
          `做好防治记录和效果评估`,
        ];
        reasoning = `环境分析：\n1. 温度${temperature}℃，湿度${humidity}%，${humidity > 70 ? '高湿环境有利于病害传播' : '湿度适中，需持续监测'}\n2. ${rainfall > 0 ? '降雨天气增加病害风险' : '晴天条件下病害风险可控'}\n3. 作物处于关键生长期，需重点防护\n因此建议加强监测和预防性防治`;
        rationality = `✓ 合理性分析：\n1. 环境风险评估：温度${temperature}℃、湿度${humidity}%，${humidity > 70 ? '高湿度环境易引发病害' : '环境条件适中'}，预警合理\n2. 防治措施匹配：生物农药预防为主，符合绿色防控要求\n3. 监测频率设置：每2天监测一次，${humidity > 70 ? '高风险期应加密监测' : '适度监测'}\n4. 通风降湿策略：降低湿度至60%以下，符合病害防控标准\n5. 综合防治：检查、防治、监测、记录形成闭环管理`;
      } else {
        recommendation = `根据环境数据（温度${temperature}℃，土壤湿度${soilMoisture}%，空气湿度${humidity}%），建议执行相应农事操作`;
        actionItems = [
          '根据环境条件调整作业计划',
          '准备必要的农资和设备',
          '执行标准化作业流程',
          '记录环境数据和作业情况',
          '评估作业效果并优化方案',
        ];
        reasoning = `基于环境监测数据，结合作物生长需求和农艺要求，生成了针对性的作业方案`;
        rationality = `✓ 合理性分析：\n1. 环境数据有效性：各项指标数值在正常范围内\n2. 决策科学性：基于实时环境数据动态调整\n3. 可执行性：操作步骤明确，易于实施\n4. 风险可控性：综合考虑环境因素，降低风险\n5. 预期效果：符合农艺标准和生产要求`;
      }
      
      return { recommendation, actionItems, reasoning, rationality };
    };
    
    const { recommendation, actionItems, reasoning, rationality } = generateDecisionBasedOnEnvironment();
    
    // 直接生成完成的模拟结果
    const completedSimulation: SimulationResult = {
      id: `result_${Date.now()}`,
      scenarioId: pendingScenario.id,
      scenarioName: pendingScenario.name,
      status: 'completed',
      startTime: new Date().toISOString().slice(0, 19).replace('T', ' '),
      endTime: new Date().toISOString().slice(0, 19).replace('T', ' '),
      executionTime: 1.8,
      decision: {
        recommendation,
        confidence: 0.88 + Math.random() * 0.08,
        level: 'important',
        reasoning: `${reasoning}\n\n${rationality}`,
        actionItems,
      },
      rulesApplied: [
        {
          ruleId: 'rule_env_1',
          ruleName: '环境数据分析规则',
          matched: true,
          priority: 9,
          weight: 0.9,
        },
        {
          ruleId: 'rule_crop_1',
          ruleName: '作物生长阶段规则',
          matched: true,
          priority: 8,
          weight: 0.85,
        },
      ],
      evaluation: {
        level: 'excellent',
        score: 88 + Math.floor(Math.random() * 8),
        accuracy: 90 + Math.floor(Math.random() * 6),
        reliability: 88 + Math.floor(Math.random() * 7),
        practicality: 92 + Math.floor(Math.random() * 5),
        feedback: '决策合理，充分考虑环境因素，具有较强的可操作性和科学性',
      },
      parameters: {
        modelWeight: 0.6,
        ruleWeight: 0.5,
        contextWeight: 0.45,
        threshold: 0.75,
      },
    };
    
    setSimulationResults([completedSimulation, ...simulationResults]);
    setPendingScenario(null);
    toast.success('模拟完成！已生成决策结果和合理性分析');
  };

  const handleViewResult = (result: SimulationResult) => {
    setSelectedResult(result);
    setShowResultDialog(true);
  };

  const handleCompare = () => {
    setShowComparisonDialog(true);
  };

  const handleAddComparisonItem = () => {
    // 打开选择模拟结果的对话框
    setShowSelectResultDialog(true);
  };

  const handleSelectResultForComparison = (result: SimulationResult) => {
    // 检查是否已添加
    if (comparisonItems.some(item => item.resultId === result.id)) {
      toast.error('该模拟结果已添加到对比列表');
      return;
    }
    
    // 限制最多对比5个结果
    if (comparisonItems.length >= 5) {
      toast.error('最多只能同时对比5个模拟结果');
      return;
    }
    
    const newItem: ComparisonItem = {
      resultId: result.id,
      result: result,
    };
    
    setComparisonItems([...comparisonItems, newItem]);
    setShowSelectResultDialog(false);
    toast.success('已添加到对比列表');
  };

  const handleRemoveComparisonItem = (resultId: string) => {
    setComparisonItems(comparisonItems.filter(item => item.resultId !== resultId));
    toast.success('已从对比列表中移除');
  };

  const handleClearComparison = () => {
    setComparisonItems([]);
    toast.success('已清空对比列表');
  };

  const getDifficultyBadge = (difficulty: 'simple' | 'medium' | 'complex') => {
    const config = {
      simple: { label: '简单', className: 'bg-success-muted text-success-muted-foreground border-success' },
      medium: { label: '中等', className: 'bg-info-muted text-info-muted-foreground border-info' },
      complex: { label: '复杂', className: 'bg-warning-muted text-warning-muted-foreground border-warning' },
    };
    const { label, className } = config[difficulty];
    return <Badge variant="outline" className={className}>{label}</Badge>;
  };

  const getStatusBadge = (status: SimulationStatus) => {
    const config = {
      idle: { label: '待运行', icon: Clock, className: 'bg-muted text-muted-foreground border-border' },
      running: { label: '运行中', icon: Activity, className: 'bg-info-muted text-info-muted-foreground border-info' },
      completed: { label: '已完成', icon: CheckCircle, className: 'bg-success-muted text-success-muted-foreground border-success' },
      failed: { label: '失败', icon: XCircle, className: 'bg-error-muted text-error-muted-foreground border-error' },
    };
    const { label, icon: Icon, className } = config[status];
    return (
      <Badge variant="outline" className={className}>
        <Icon className="w-3 h-3 mr-1" />
        {label}
      </Badge>
    );
  };

  const getEvaluationBadge = (level: EvaluationLevel) => {
    const config = {
      excellent: { label: '优秀', className: 'bg-success-muted text-success-muted-foreground border-success' },
      good: { label: '良好', className: 'bg-info-muted text-info-muted-foreground border-info' },
      fair: { label: '一般', className: 'bg-warning-muted text-warning-muted-foreground border-warning' },
      poor: { label: '较差', className: 'bg-error-muted text-error-muted-foreground border-error' },
    };
    const { label, className } = config[level];
    return <Badge variant="outline" className={className}>{label}</Badge>;
  };

  const getCategoryIcon = (category: ScenarioCategory) => {
    const icons = {
      irrigation: Activity,
      pest: AlertTriangle,
      fertilizer: Beaker,
      harvest: CheckCircle,
      weather: Database,
      custom: Boxes,
    };
    return icons[category] || Info;
  };

  return (
    <div className="space-y-6">
      {/* 重要提示 */}
      <Card className="p-4 bg-amber-50 border-amber-300">
        <div className="flex items-start gap-3">
          <Info className="w-5 h-5 text-amber-600 flex-shrink-0 mt-0.5" />
          <div>
            <h4 className="text-amber-900 mb-1">💡 这是测试验证工具</h4>
            <p className="text-sm text-amber-800">
              决策模拟使用测试数据进行模拟，<strong>不会真实执行</strong>，不会控制物联网设备，不会记录到决策日志。
              模拟结果仅供参考，用于验证决策在不同情况下的表现。
              如需真实执行，请在"业务融合"模块中操作。
            </p>
          </div>
        </div>
      </Card>

      {/* 页面标题 */}
      <Card className="p-6 bg-gradient-to-r from-indigo-50 to-purple-50 border-indigo-200">
        <div className="flex items-start gap-3">
          <Beaker className="w-6 h-6 text-indigo-600 flex-shrink-0 mt-1" />
          <div className="flex-1">
            <h2 className="mb-2">决策模拟测试</h2>
            <p className="text-sm text-muted-foreground mb-3">
              提供安全的模拟测试环境，支持场景设计、参数调优、多方案对比和效果评估，降低实际应用风险
            </p>
            <div className="flex flex-wrap gap-2">
              <Badge variant="outline" className="bg-white">
                <Workflow className="w-3 h-3 mr-1" />
                场景模拟
              </Badge>
              <Badge variant="outline" className="bg-white">
                <GitCompare className="w-3 h-3 mr-1" />
                方案对比
              </Badge>
              <Badge variant="outline" className="bg-white">
                <Target className="w-3 h-3 mr-1" />
                效果评估
              </Badge>
              <Badge variant="outline" className="bg-white">
                <Settings className="w-3 h-3 mr-1" />
                参数优化
              </Badge>
            </div>
          </div>
        </div>
      </Card>

      <Tabs value={activeTab} onValueChange={setActiveTab} className="space-y-4">
        <TabsList>
          <TabsTrigger value="scenarios">
            <Boxes className="w-4 h-4 mr-2" />
            模拟场景
          </TabsTrigger>
          <TabsTrigger value="results">
            <BarChart3 className="w-4 h-4 mr-2" />
            模拟结果
          </TabsTrigger>
          <TabsTrigger value="comparison">
            <GitCompare className="w-4 h-4 mr-2" />
            模拟结果对比
          </TabsTrigger>
        </TabsList>

        {/* 模拟场景 */}
        <TabsContent value="scenarios" className="space-y-6">
          {/* 统计卡片 - 只保留3个 */}
          <div className="grid grid-cols-3 gap-4">
            <Card className="p-6">
              <div className="flex items-center justify-between mb-2">
                <div className="text-sm text-muted-foreground">预设场景</div>
                <Boxes className="w-5 h-5 text-indigo-500" />
              </div>
              <div className="text-3xl font-bold mb-1">{presetScenarios.length}</div>
              <div className="text-xs text-muted-foreground">典型业务场景</div>
            </Card>

            <Card className="p-6">
              <div className="flex items-center justify-between mb-2">
                <div className="text-sm text-muted-foreground">模拟次数</div>
                <Activity className="w-5 h-5 text-blue-500" />
              </div>
              <div className="text-3xl font-bold mb-1">{simulationStats.totalSimulations}</div>
              <div className="text-xs text-muted-foreground">累计运行</div>
            </Card>

            <Card className="p-6">
              <div className="flex items-center justify-between mb-2">
                <div className="text-sm text-muted-foreground">成功率</div>
                <TrendingUp className="w-5 h-5 text-green-500" />
              </div>
              <div className="text-3xl font-bold mb-1">{simulationStats.successRate}%</div>
              <div className="text-xs text-muted-foreground">运行稳定</div>
            </Card>
          </div>

          {/* 预设场景 */}
          <Card className="p-6">
            <div className="flex items-center justify-between mb-4">
              <h3>决策场景库</h3>
              <div className="flex items-center gap-2">
                <Badge variant="outline">{presetScenarios.length} 个场景</Badge>
              </div>
            </div>

            <div className="grid grid-cols-2 gap-4">
              {presetScenarios.map((scenario) => {
                const CategoryIcon = getCategoryIcon(scenario.category);
                return (
                  <Card key={scenario.id} className="p-4 hover:shadow-md transition-shadow cursor-pointer">
                    <div className="flex items-start justify-between mb-3">
                      <div className="flex items-center gap-2">
                        <div className="w-10 h-10 rounded-lg bg-indigo-100 flex items-center justify-center flex-shrink-0">
                          <CategoryIcon className="w-5 h-5 text-indigo-600" />
                        </div>
                        <div className="flex-1">
                          <div className="flex items-center gap-2 mb-1">
                            <span className="font-medium">{scenario.name}</span>
                            {scenario.source === 'auto' ? (
                              <Badge variant="outline" className="text-xs bg-blue-50 text-blue-700">
                                <Sparkles className="w-3 h-3 mr-1" />
                                自动生成
                              </Badge>
                            ) : (
                              <Badge variant="outline" className="text-xs bg-green-50 text-green-700">
                                <Plus className="w-3 h-3 mr-1" />
                                手动添加
                              </Badge>
                            )}
                          </div>
                          <div className="text-xs text-muted-foreground">
                            {scenario.modelName} {scenario.modelVersion}
                          </div>
                        </div>
                      </div>
                      {getDifficultyBadge(scenario.difficulty)}
                    </div>
                    <p className="text-sm text-muted-foreground mb-3 line-clamp-2">
                      {scenario.description}
                    </p>
                    <div className="flex items-center justify-between">
                      <Badge variant="outline" className="text-xs">
                        {scenario.expectedOutcome}
                      </Badge>
                      <Button
                        size="sm"
                        onClick={() => handleRunSimulation(scenario)}
                        className="bg-indigo-600 hover:bg-indigo-700"
                      >
                        <Play className="w-4 h-4 mr-1" />
                        运行
                      </Button>
                    </div>
                  </Card>
                );
              })}
            </div>
          </Card>
        </TabsContent>

        {/* 模拟结果 */}
        <TabsContent value="results" className="space-y-6">
          {/* 结果统计 */}
          <div className="grid grid-cols-4 gap-4">
            <Card className="p-6">
              <div className="flex items-center justify-between mb-2">
                <div className="text-sm text-muted-foreground">总模拟数</div>
                <Activity className="w-5 h-5 text-indigo-500" />
              </div>
              <div className="text-3xl font-bold mb-1">{simulationStats.totalSimulations}</div>
              <div className="text-xs text-muted-foreground">累计执行</div>
            </Card>

            <Card className="p-6">
              <div className="flex items-center justify-between mb-2">
                <div className="text-sm text-muted-foreground">成功率</div>
                <CheckCircle className="w-5 h-5 text-green-500" />
              </div>
              <div className="text-3xl font-bold mb-1">{simulationStats.successRate}%</div>
              <div className="text-xs text-muted-foreground">运行稳定</div>
            </Card>

            <Card className="p-6">
              <div className="flex items-center justify-between mb-2">
                <div className="text-sm text-muted-foreground">平均耗时</div>
                <Clock className="w-5 h-5 text-blue-500" />
              </div>
              <div className="text-3xl font-bold mb-1">{simulationStats.avgExecutionTime}s</div>
              <div className="text-xs text-muted-foreground">响应快速</div>
            </Card>

            <Card className="p-6">
              <div className="flex items-center justify-between mb-2">
                <div className="text-sm text-muted-foreground">平均得分</div>
                <TrendingUp className="w-5 h-5 text-purple-500" />
              </div>
              <div className="text-3xl font-bold mb-1">{simulationStats.avgScore}分</div>
              <div className="text-xs text-muted-foreground">评分优秀</div>
            </Card>
          </div>

          {/* 结果列表 */}
          <Card className="p-6">
            <div className="flex items-center justify-between mb-4">
              <h3>模拟结果列表</h3>
              <div className="flex gap-2">
                <Button variant="outline" size="sm">
                  <RefreshCw className="w-4 h-4 mr-2" />
                  刷新
                </Button>
              </div>
            </div>

            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead>ID</TableHead>
                  <TableHead>场景名称</TableHead>
                  <TableHead>执行时间</TableHead>
                  <TableHead>状态</TableHead>
                  <TableHead>评估等级</TableHead>
                  <TableHead>得分</TableHead>
                  <TableHead>置信度</TableHead>
                  <TableHead>操作</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {simulationResults.map((result) => (
                  <TableRow key={result.id}>
                    <TableCell>
                      <code className="text-xs bg-muted px-2 py-1 rounded">{result.id}</code>
                    </TableCell>
                    <TableCell>
                      <div className="font-medium">{result.scenarioName}</div>
                      <div className="text-xs text-muted-foreground">{result.startTime}</div>
                    </TableCell>
                    <TableCell>{result.executionTime}s</TableCell>
                    <TableCell>{getStatusBadge(result.status)}</TableCell>
                    <TableCell>{getEvaluationBadge(result.evaluation.level)}</TableCell>
                    <TableCell>
                      <div className="flex items-center gap-2">
                        <Progress value={result.evaluation.score} className="w-16 h-2" />
                        <span className="text-sm font-medium">{result.evaluation.score}</span>
                      </div>
                    </TableCell>
                    <TableCell>{(result.decision.confidence * 100).toFixed(0)}%</TableCell>
                    <TableCell>
                      <Button size="sm" variant="outline" onClick={() => handleViewResult(result)}>
                        <Eye className="w-4 h-4" />
                      </Button>
                    </TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>
          </Card>

          {/* 评估分布图表 */}
          <div className="grid grid-cols-2 gap-4">
            <Card className="p-6">
              <h4 className="mb-4">评估等级分布</h4>
              <ResponsiveContainer width="100%" height={200}>
                <BarChart data={evaluationDistribution}>
                  <CartesianGrid strokeDasharray="3 3" />
                  <XAxis dataKey="name" />
                  <YAxis />
                  <RechartsTooltip />
                  <Bar dataKey="value">
                    {evaluationDistribution.map((entry, index) => (
                      <Cell key={`cell-${index}`} fill={entry.color} />
                    ))}
                  </Bar>
                </BarChart>
              </ResponsiveContainer>
            </Card>

            <Card className="p-6">
              <h4 className="mb-4">执行时间趋势</h4>
              <ResponsiveContainer width="100%" height={200}>
                <LineChart data={executionTimeTrend}>
                  <CartesianGrid strokeDasharray="3 3" />
                  <XAxis dataKey="name" />
                  <YAxis />
                  <RechartsTooltip />
                  <Legend />
                  <Line type="monotone" dataKey="time" stroke="#8b5cf6" name="执行时间(秒)" />
                </LineChart>
              </ResponsiveContainer>
            </Card>
          </div>
        </TabsContent>

        {/* 方案对比 */}
        <TabsContent value="comparison" className="space-y-6">
          {/* 对比操作区 */}
          <Card className="p-6">
            <div className="flex items-center justify-between mb-4">
              <div>
                <h3>模拟结果对比</h3>
                <p className="text-sm text-muted-foreground mt-1">
                  从历史模拟结果中选择多个进行对比分析（最多5个）
                </p>
              </div>
              <div className="flex gap-2">
                {comparisonItems.length > 0 && (
                  <Button size="sm" variant="outline" onClick={handleClearComparison}>
                    <RotateCcw className="w-4 h-4 mr-2" />
                    清空列表
                  </Button>
                )}
                <Button size="sm" onClick={handleAddComparisonItem} className="bg-indigo-600 hover:bg-indigo-700">
                  <Plus className="w-4 h-4 mr-2" />
                  添加对比项
                </Button>
              </div>
            </div>

            {comparisonItems.length === 0 ? (
              <div className="text-center py-12 text-muted-foreground">
                <GitCompare className="w-12 h-12 mx-auto mb-3 opacity-30" />
                <p>暂无对比项，点击"添加对比项"从模拟结果中选择</p>
              </div>
            ) : (
              <div className="space-y-4">
                {comparisonItems.map((item, index) => (
                  <div key={item.resultId} className="p-4 border rounded-lg hover:shadow-md transition-shadow">
                    <div className="flex items-start justify-between mb-3">
                      <div className="flex items-center gap-3">
                        <div className="w-8 h-8 rounded-full bg-indigo-100 text-indigo-600 flex items-center justify-center font-medium flex-shrink-0">
                          {index + 1}
                        </div>
                        <div>
                          <div className="font-medium">{item.result.scenarioName}</div>
                          <div className="text-xs text-muted-foreground">
                            ID: {item.result.id} | 执行时间: {item.result.startTime}
                          </div>
                        </div>
                      </div>
                      <Button
                        size="sm"
                        variant="ghost"
                        onClick={() => handleRemoveComparisonItem(item.resultId)}
                      >
                        <XCircle className="w-4 h-4" />
                      </Button>
                    </div>
                    
                    <div className="grid grid-cols-5 gap-4 text-sm">
                      <div>
                        <div className="text-xs text-muted-foreground mb-1">状态</div>
                        <div>{getStatusBadge(item.result.status)}</div>
                      </div>
                      <div>
                        <div className="text-xs text-muted-foreground mb-1">评估等级</div>
                        <div>{getEvaluationBadge(item.result.evaluation.level)}</div>
                      </div>
                      <div>
                        <div className="text-xs text-muted-foreground mb-1">得分</div>
                        <div className="font-medium">{item.result.evaluation.score}分</div>
                      </div>
                      <div>
                        <div className="text-xs text-muted-foreground mb-1">置信度</div>
                        <div className="font-medium">{(item.result.decision.confidence * 100).toFixed(0)}%</div>
                      </div>
                      <div>
                        <div className="text-xs text-muted-foreground mb-1">执行耗时</div>
                        <div className="font-medium">{item.result.executionTime}s</div>
                      </div>
                    </div>
                  </div>
                ))}
              </div>
            )}
          </Card>

          {/* 对比图表 */}
          {comparisonItems.length >= 2 && (
            <>
              <div className="grid grid-cols-2 gap-4">
                {/* 得分对比 */}
                <Card className="p-6">
                  <h4 className="mb-4">得分对比</h4>
                  <ResponsiveContainer width="100%" height={250}>
                    <BarChart data={comparisonItems.map((item, index) => ({
                      name: `对比项${index + 1}`,
                      得分: item.result.evaluation.score,
                      准确性: item.result.evaluation.accuracy,
                      可靠性: item.result.evaluation.reliability,
                      实用性: item.result.evaluation.practicality,
                    }))}>
                      <CartesianGrid strokeDasharray="3 3" />
                      <XAxis dataKey="name" />
                      <YAxis domain={[0, 100]} />
                      <RechartsTooltip />
                      <Legend />
                      <Bar dataKey="得分" fill="#6366f1" />
                      <Bar dataKey="准确性" fill="#10b981" />
                      <Bar dataKey="可靠性" fill="#3b82f6" />
                      <Bar dataKey="实用性" fill="#f59e0b" />
                    </BarChart>
                  </ResponsiveContainer>
                </Card>

                {/* 置信度与耗时对比 */}
                <Card className="p-6">
                  <h4 className="mb-4">置信度与耗时对比</h4>
                  <ResponsiveContainer width="100%" height={250}>
                    <ScatterChart>
                      <CartesianGrid strokeDasharray="3 3" />
                      <XAxis dataKey="executionTime" name="执行耗时(s)" />
                      <YAxis dataKey="confidence" name="置信度(%)" domain={[0, 100]} />
                      <RechartsTooltip cursor={{ strokeDasharray: '3 3' }} />
                      <Scatter
                        name="模拟结果"
                        data={comparisonItems.map((item, index) => ({
                          executionTime: item.result.executionTime,
                          confidence: item.result.decision.confidence * 100,
                          name: `对比项${index + 1}`,
                        }))}
                        fill="#6366f1"
                      />
                    </ScatterChart>
                  </ResponsiveContainer>
                </Card>
              </div>

              {/* 雷达图对比 */}
              <Card className="p-6">
                <h4 className="mb-4">综合指标雷达图</h4>
                <ResponsiveContainer width="100%" height={400}>
                  <RadarChart data={[
                    { indicator: '准确性', ...Object.fromEntries(comparisonItems.map((item, i) => [`对比项${i + 1}`, item.result.evaluation.accuracy])) },
                    { indicator: '可靠性', ...Object.fromEntries(comparisonItems.map((item, i) => [`对比项${i + 1}`, item.result.evaluation.reliability])) },
                    { indicator: '实用性', ...Object.fromEntries(comparisonItems.map((item, i) => [`对比项${i + 1}`, item.result.evaluation.practicality])) },
                    { indicator: '置信度', ...Object.fromEntries(comparisonItems.map((item, i) => [`对比项${i + 1}`, item.result.decision.confidence * 100])) },
                    { indicator: '综合得分', ...Object.fromEntries(comparisonItems.map((item, i) => [`对比项${i + 1}`, item.result.evaluation.score])) },
                  ]}>
                    <PolarGrid />
                    <PolarAngleAxis dataKey="indicator" />
                    <PolarRadiusAxis domain={[0, 100]} />
                    {comparisonItems.map((item, index) => (
                      <Radar
                        key={item.resultId}
                        name={`对比项${index + 1}`}
                        dataKey={`对比项${index + 1}`}
                        stroke={['#6366f1', '#10b981', '#f59e0b', '#ef4444', '#8b5cf6'][index]}
                        fill={['#6366f1', '#10b981', '#f59e0b', '#ef4444', '#8b5cf6'][index]}
                        fillOpacity={0.3}
                      />
                    ))}
                    <Legend />
                  </RadarChart>
                </ResponsiveContainer>
              </Card>
            </>
          )}
        </TabsContent>
      </Tabs>

      {/* 环境数据选择对话框 */}
      <Dialog open={showEnvironmentDialog} onOpenChange={setShowEnvironmentDialog}>
        <DialogContent className="max-w-2xl">
          <DialogHeader>
            <DialogTitle>选择环境数据</DialogTitle>
            <DialogDescription>
              设置模拟运行所需的本地环境数据参数
            </DialogDescription>
          </DialogHeader>

          <div className="space-y-4">
            <div className="grid grid-cols-2 gap-4">
              <div>
                <Label>温度 (℃)</Label>
                <Input
                  type="number"
                  value={selectedEnvironmentData.temperature}
                  onChange={(e) => setSelectedEnvironmentData({
                    ...selectedEnvironmentData,
                    temperature: parseFloat(e.target.value) || 0
                  })}
                  placeholder="例如: 28"
                />
              </div>
              
              <div>
                <Label>空气湿度 (%)</Label>
                <Input
                  type="number"
                  value={selectedEnvironmentData.humidity}
                  onChange={(e) => setSelectedEnvironmentData({
                    ...selectedEnvironmentData,
                    humidity: parseFloat(e.target.value) || 0
                  })}
                  placeholder="例如: 65"
                />
              </div>

              <div>
                <Label>土壤湿度 (%)</Label>
                <Input
                  type="number"
                  value={selectedEnvironmentData.soilMoisture}
                  onChange={(e) => setSelectedEnvironmentData({
                    ...selectedEnvironmentData,
                    soilMoisture: parseFloat(e.target.value) || 0
                  })}
                  placeholder="例如: 35"
                />
              </div>

              <div>
                <Label>降雨量 (mm)</Label>
                <Input
                  type="number"
                  value={selectedEnvironmentData.rainfall}
                  onChange={(e) => setSelectedEnvironmentData({
                    ...selectedEnvironmentData,
                    rainfall: parseFloat(e.target.value) || 0
                  })}
                  placeholder="例如: 0"
                />
              </div>

              <div>
                <Label>风速 (m/s)</Label>
                <Input
                  type="number"
                  value={selectedEnvironmentData.windSpeed}
                  onChange={(e) => setSelectedEnvironmentData({
                    ...selectedEnvironmentData,
                    windSpeed: parseFloat(e.target.value) || 0
                  })}
                  placeholder="例如: 2.5"
                />
              </div>

              <div>
                <Label>光照强度 (lux)</Label>
                <Input
                  type="number"
                  value={selectedEnvironmentData.lightIntensity}
                  onChange={(e) => setSelectedEnvironmentData({
                    ...selectedEnvironmentData,
                    lightIntensity: parseFloat(e.target.value) || 0
                  })}
                  placeholder="例如: 85000"
                />
              </div>
            </div>

            <div className="p-4 bg-blue-50 border border-blue-200 rounded-lg">
              <div className="flex items-start gap-2">
                <Info className="w-5 h-5 text-info flex-shrink-0 mt-0.5" />
                <div className="text-sm text-blue-900">
                  <div className="font-medium mb-1">环境数据说明</div>
                  <div>
                    这些环境数据将用于生成针对性的决策建议和合理性分析。系统会根据您提供的数据，结合场景特点和农艺规则，生成科学合理的决策方案。
                  </div>
                </div>
              </div>
            </div>
          </div>

          <DialogFooter>
            <Button variant="outline" onClick={() => {
              setShowEnvironmentDialog(false);
              setPendingScenario(null);
            }}>
              取消
            </Button>
            <Button onClick={handleConfirmEnvironmentAndRun} className="bg-indigo-600 hover:bg-indigo-700">
              <Play className="w-4 h-4 mr-2" />
              确认并运行
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* 选择模拟结果对话框 */}
      <Dialog open={showSelectResultDialog} onOpenChange={setShowSelectResultDialog}>
        <DialogContent className="max-w-4xl max-h-[90vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle>选择模拟结果</DialogTitle>
            <DialogDescription>
              从历史模拟结果中选择要添加到对比列表的项
            </DialogDescription>
          </DialogHeader>
          
          <div className="space-y-4">
            {simulationResults.length === 0 ? (
              <div className="text-center py-8 text-muted-foreground">
                <Info className="w-12 h-12 mx-auto mb-3 opacity-30" />
                <p>暂无模拟结果，请先运行模拟场景</p>
              </div>
            ) : (
              <div className="space-y-3 max-h-[60vh] overflow-y-auto">
                {simulationResults.map((result) => {
                  const isAdded = comparisonItems.some(item => item.resultId === result.id);
                  return (
                    <div
                      key={result.id}
                      className={cn(
                        "p-4 border rounded-lg cursor-pointer transition-all",
                        isAdded
                          ? "bg-gray-100 border-gray-300 cursor-not-allowed"
                          : "hover:shadow-md hover:border-indigo-300"
                      )}
                      onClick={() => !isAdded && handleSelectResultForComparison(result)}
                    >
                      <div className="flex items-start justify-between mb-2">
                        <div className="flex-1">
                          <div className="flex items-center gap-2 mb-1">
                            <span className="font-medium">{result.scenarioName}</span>
                            {getStatusBadge(result.status)}
                            {getEvaluationBadge(result.evaluation.level)}
                          </div>
                          <div className="text-xs text-muted-foreground">
                            ID: {result.id} | 执行时间: {result.startTime}
                          </div>
                        </div>
                        {isAdded && (
                          <Badge variant="outline" className="bg-green-50 text-green-700">
                            <CheckCircle2 className="w-3 h-3 mr-1" />
                            已添加
                          </Badge>
                        )}
                      </div>
                      
                      <div className="grid grid-cols-4 gap-4 text-sm mt-3">
                        <div>
                          <div className="text-xs text-muted-foreground">得分</div>
                          <div className="font-medium">{result.evaluation.score}分</div>
                        </div>
                        <div>
                          <div className="text-xs text-muted-foreground">置信度</div>
                          <div className="font-medium">{(result.decision.confidence * 100).toFixed(0)}%</div>
                        </div>
                        <div>
                          <div className="text-xs text-muted-foreground">执行耗时</div>
                          <div className="font-medium">{result.executionTime}s</div>
                        </div>
                        <div>
                          <div className="text-xs text-muted-foreground">决策级别</div>
                          <div className="font-medium">
                            {result.decision.level === 'critical' && '关键'}
                            {result.decision.level === 'important' && '重要'}
                            {result.decision.level === 'normal' && '一般'}
                            {result.decision.level === 'suggestion' && '建议'}
                          </div>
                        </div>
                      </div>
                    </div>
                  );
                })}
              </div>
            )}
            
            <div className="p-4 bg-blue-50 border border-blue-200 rounded-lg">
              <div className="flex items-start gap-2">
                <Info className="w-5 h-5 text-info flex-shrink-0 mt-0.5" />
                <div className="text-sm text-blue-900">
                  <div className="font-medium mb-1">选择提示</div>
                  <ul className="list-disc list-inside space-y-1">
                    <li>点击模拟结果卡片即可添加到对比列表</li>
                    <li>已添加的结果会显示"已添加"标记且无法重复选择</li>
                    <li>最多可同时对比5个模拟结果</li>
                    <li>建议选择同一场景或相关场景的结果进行对比</li>
                  </ul>
                </div>
              </div>
            </div>
          </div>
          
          <DialogFooter>
            <Button variant="outline" onClick={() => setShowSelectResultDialog(false)}>
              关闭
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* 结果详情对话框 - 简化版本 */}
      <Dialog open={showResultDialog} onOpenChange={setShowResultDialog}>
        <DialogContent className="max-w-4xl max-h-[90vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle>模拟结果详情</DialogTitle>
            <DialogDescription>
              查看完整的决策过程和评估分析
            </DialogDescription>
          </DialogHeader>

          {selectedResult && (
            <div className="space-y-6">
              {/* 基本信息 */}
              <div>
                <div className="flex items-center justify-between mb-3">
                  <h4>{selectedResult.scenarioName}</h4>
                  <div className="flex items-center gap-2">
                    {getStatusBadge(selectedResult.status)}
                    {getEvaluationBadge(selectedResult.evaluation.level)}
                  </div>
                </div>
                <div className="grid grid-cols-3 gap-4 text-sm">
                  <div>
                    <div className="text-xs text-muted-foreground mb-1">开始时间</div>
                    <div>{selectedResult.startTime}</div>
                  </div>
                  <div>
                    <div className="text-xs text-muted-foreground mb-1">执行时间</div>
                    <div>{selectedResult.executionTime}秒</div>
                  </div>
                  <div>
                    <div className="text-xs text-muted-foreground mb-1">置信度</div>
                    <div>{(selectedResult.decision.confidence * 100).toFixed(0)}%</div>
                  </div>
                </div>
              </div>

              {/* 决策建议 */}
              <div>
                <h4 className="mb-3">决策建议</h4>
                <div className="p-4 bg-blue-50 border border-blue-200 rounded-lg">
                  <div className="flex items-start gap-2">
                    <Lightbulb className="w-5 h-5 text-blue-600 flex-shrink-0 mt-0.5" />
                    <div className="text-sm">{selectedResult.decision.recommendation}</div>
                  </div>
                </div>
              </div>

              {/* 效果评估 */}
              <div>
                <h4 className="mb-3">效果评估</h4>
                <div className="space-y-3">
                  <div className="flex items-center justify-between">
                    <span className="text-sm">综合得分</span>
                    <div className="flex items-center gap-2">
                      <Progress value={selectedResult.evaluation.score} className="w-32 h-2" />
                      <span className="font-medium">{selectedResult.evaluation.score}分</span>
                    </div>
                  </div>
                  <div className="flex items-center justify-between">
                    <span className="text-sm">准确性</span>
                    <div className="flex items-center gap-2">
                      <Progress value={selectedResult.evaluation.accuracy} className="w-32 h-2" />
                      <span className="font-medium">{selectedResult.evaluation.accuracy}分</span>
                    </div>
                  </div>
                  <div className="flex items-center justify-between">
                    <span className="text-sm">可靠性</span>
                    <div className="flex items-center gap-2">
                      <Progress value={selectedResult.evaluation.reliability} className="w-32 h-2" />
                      <span className="font-medium">{selectedResult.evaluation.reliability}分</span>
                    </div>
                  </div>
                  <div className="flex items-center justify-between">
                    <span className="text-sm">实用性</span>
                    <div className="flex items-center gap-2">
                      <Progress value={selectedResult.evaluation.practicality} className="w-32 h-2" />
                      <span className="font-medium">{selectedResult.evaluation.practicality}分</span>
                    </div>
                  </div>
                  <div className="p-3 bg-muted rounded-lg mt-3">
                    <div className="text-sm text-muted-foreground">{selectedResult.evaluation.feedback}</div>
                  </div>
                </div>
              </div>
            </div>
          )}

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


export default function DecisionSimulationPage() {
  return <AIDecisionSimulation />;
}
