/**
 * filekorolheader: 决策日志追溯页面 - AI决策日志管理与审计追踪
 * 功能：决策日志记录、日志查询筛选、详细信息查看、审计追踪管理
 * 路径：/ai-crop-model/decision/log
 * 规范：遵循crop-x/docs/开发项目规范.md，1:1参考AIDecisionLog.tsx实现
 */
'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 { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
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 { ScrollArea } from '@/components/ui/scroll-area';
import { Separator } from '@/components/ui/separator';
import {
  FileText,
  Search,
  Download,
  Filter,
  Eye,
  RefreshCw,
  Clock,
  CheckCircle,
  AlertCircle,
  XCircle,
  Database,
  Cpu,
  BookOpen,
  GitBranch,
  Layers,
  Activity,
  BarChart3,
  ArrowRight,
  Zap,
  Info,
  Settings,
  Calendar,
  User,
  FileCode,
  Share2,
  Copy,
  Trash2,
  AlertTriangle,
  TrendingUp,
  Target,
  Gauge,
  Brain,
  Workflow,
  ListChecks,
  Code,
  Box,
  ServerCog,
  FileJson,
  History,
  ChevronRight,
  ChevronDown,
  Play,
  Pause,
  RotateCcw,
  ExternalLink,
  LinkIcon,
  Archive,
  Shield,
  Lock,
} from 'lucide-react';
import { toast } from 'sonner';
import {
  LineChart,
  Line,
  BarChart,
  Bar,
  XAxis,
  YAxis,
  CartesianGrid,
  Tooltip as RechartsTooltip,
  Legend,
  ResponsiveContainer,
  PieChart,
  Pie,
  Cell,
} from 'recharts';

interface DecisionLogPageProps {
  activePath?: string;
}

// 决策状态
type DecisionStatus = 'success' | 'failed' | 'partial' | 'cancelled';

// 决策级别
type DecisionLevel = 'critical' | 'important' | 'normal' | 'suggestion';

// 日志类型
type LogType = 'decision' | 'model' | 'rule' | 'fusion' | 'system';

// 执行类型
type ExecutionType = 'manual' | 'auto';

// 决策日志
interface DecisionLog {
  id: string;
  timestamp: string;
  status: DecisionStatus;
  level: DecisionLevel;
  type: string;
  scenario: string;
  summary: string;
  executionTime: number;
  executionType: ExecutionType; // 执行类型：manual-手动执行, auto-自动执行

  // 触发信息
  trigger: {
    source: string;
    event: string;
    userId: string;
    userName: string;
    conditionsMet?: string; // 自动执行时的触发条件
  };

  // 输入数据
  inputData: {
    [key: string]: any;
  };

  // 模型服务
  modelService: {
    id: string;
    name: string;
    version: string;
    provider: string;
    callTime: number;
    response: any;
  }[];

  // 规则匹配
  rulesMatched: {
    ruleId: string;
    ruleName: string;
    category: string;
    priority: number;
    matched: boolean;
    confidence: number;
    conditions: string[];
    actions: string[];
  }[];

  // 融合计算
  fusionProcess: {
    step: string;
    description: string;
    input: any;
    output: any;
    duration: number;
  }[];

  // 中间结果
  intermediateResults: {
    stage: string;
    data: any;
    timestamp: string;
  }[];

  // 最终决策
  finalDecision: {
    recommendation: string;
    confidence: number;
    reasoning: string;
    actionItems: string[];
    estimatedImpact: string;
  };

  // 执行情况
  execution: {
    status: DecisionStatus;
    appliedAt?: string;
    appliedBy?: string;
    result?: string;
    feedback?: string;
  };
}

// 审计追踪
interface AuditTrail {
  id: string;
  decisionId: string;
  action: string;
  timestamp: string;
  user: string;
  details: string;
  ipAddress: string;
}

export default function DecisionLogPage({ activePath }: DecisionLogPageProps) {
  const [activeTab, setActiveTab] = useState('logs');
  const [showDetailDialog, setShowDetailDialog] = useState(false);
  const [showAuditDialog, setShowAuditDialog] = useState(false);
  const [selectedLog, setSelectedLog] = useState<DecisionLog | null>(null);
  const [expandedSections, setExpandedSections] = useState<Set<string>>(new Set(['input', 'model', 'rules']));

  // 筛选条件
  const [filters, setFilters] = useState({
    status: 'all',
    level: 'all',
    type: 'all',
    executionType: 'all' as 'all' | 'manual' | 'auto', // 执行类型筛选
    dateRange: '7days',
    searchText: '',
  });

  // 模拟决策日志数据
  const [decisionLogs] = useState<DecisionLog[]>([
    {
      id: 'log_001',
      timestamp: '2024-10-23 14:30:25',
      status: 'success',
      level: 'important',
      type: '灌溉决策',
      scenario: '开花期缺水灌溉',
      summary: '基于土壤湿度和天气预报生成灌溉建议',
      executionTime: 2.3,
      executionType: 'auto', // 自动执行
      trigger: {
        source: '监测系统',
        event: '土壤湿度低于阈值',
        userId: 'user_001',
        userName: '张三',
        conditionsMet: '土壤湿度28%<30%',
      },
      inputData: {
        cropType: '番茄',
        variety: '金粉808',
        growthStage: '开花期',
        fieldId: 'field_001',
        fieldName: '1号大棚',
        fieldArea: 2.5,
        soilMoisture: 35,
        soilTemperature: 18,
        airTemperature: 28,
        humidity: 65,
        rainfall: 0,
        forecast: '未来3天晴天',
        lastIrrigation: '2024-10-20 18:00',
        lastIrrigationAmount: 100,
      },
      modelService: [
        {
          id: 'model_001',
          name: '作物需水预测模型',
          version: 'v2.1.3',
          provider: 'AgriAI',
          callTime: 0.8,
          response: {
            predictedWaterDemand: 120,
            confidence: 0.92,
            factors: {
              growth: 0.85,
              weather: 0.78,
              soil: 0.88,
            },
          },
        },
        {
          id: 'model_002',
          name: '灌溉时机优化模型',
          version: 'v1.5.0',
          provider: 'AgriAI',
          callTime: 0.5,
          response: {
            optimalTime: '17:00-18:00',
            reason: '避开高温时段，减少蒸发',
            temperature: 26,
          },
        },
      ],
      rulesMatched: [
        {
          ruleId: 'rule_001',
          ruleName: '开花期灌溉规则',
          category: '生长期管理',
          priority: 9,
          matched: true,
          confidence: 0.95,
          conditions: [
            '生长阶段 = 开花期',
            '土壤湿度 < 40%',
            '距上次灌溉 > 2天',
          ],
          actions: [
            '建议立即安排灌溉',
            '灌溉量 = 预测需水量 × 1.1',
            '选择傍晚时段灌溉',
          ],
        },
        {
          ruleId: 'rule_002',
          ruleName: '干旱预警规则',
          category: '风险管理',
          priority: 8,
          matched: true,
          confidence: 0.88,
          conditions: [
            '土壤湿度 < 30%',
            '连续3天无降雨',
            '温度 > 25℃',
          ],
          actions: [
            '发布干旱预警',
            '增加灌溉频率',
            '监控作物状态',
          ],
        },
      ],
      fusionProcess: [
        {
          step: '数据预处理',
          description: '标准化输入数据',
          input: { rawMoisture: 35, rawTemp: 28 },
          output: { normalizedMoisture: 0.35, normalizedTemp: 0.72 },
          duration: 0.1,
        },
        {
          step: '模型推理',
          description: '调用预测模型',
          input: { moisture: 0.35, temp: 0.72, stage: 'flowering' },
          output: { waterDemand: 120, confidence: 0.92 },
          duration: 1.3,
        },
        {
          step: '规则匹配',
          description: '匹配业务规则',
          input: { stage: 'flowering', moisture: 35 },
          output: { matchedRules: ['rule_001', 'rule_002'] },
          duration: 0.3,
        },
        {
          step: '融合计算',
          description: '加权融合结果',
          input: { modelOutput: 120, rules: ['rule_001', 'rule_002'] },
          output: { finalRecommendation: '灌溉120升' },
          duration: 0.2,
        },
      ],
      intermediateResults: [
        {
          stage: '模型输出',
          data: { waterDemand: 120, confidence: 0.92 },
          timestamp: '14:30:25.1',
        },
        {
          stage: '规则匹配',
          data: { matchedRules: 2, confidence: 0.9 },
          timestamp: '14:30:25.4',
        },
      ],
      finalDecision: {
        recommendation: '建议在17:00-18:00灌溉120升水',
        confidence: 0.92,
        reasoning: '基于土壤湿度监测和作物需水模型，结合天气预测',
        actionItems: [
          '检查灌溉设备状态',
          '准备120升灌溉用水',
          '在推荐时段执行灌溉',
          '记录灌溉效果',
        ],
        estimatedImpact: '预计提升土壤湿度至65%，满足作物需水',
      },
      execution: {
        status: 'success',
        appliedAt: '2024-10-23 17:30:00',
        appliedBy: '系统自动执行',
        result: '灌溉完成，土壤湿度提升至68%',
        feedback: '执行效果良好',
      },
    },
    {
      id: 'log_002',
      timestamp: '2024-10-23 12:15:30',
      status: 'failed',
      level: 'critical',
      type: '病虫害防治',
      scenario: '番茄晚疫病预警',
      summary: '检测到病害风险，建议采取防治措施',
      executionTime: 3.1,
      executionType: 'manual', // 手动执行
      trigger: {
        source: '用户操作',
        event: '手动触发病害检测',
        userId: 'user_002',
        userName: '李四',
      },
      inputData: {
        cropType: '番茄',
        fieldId: 'field_002',
        diseaseRisk: 0.78,
        weatherCondition: '高温高湿',
        symptoms: ['叶片黄化', '茎部腐烂'],
      },
      modelService: [
        {
          id: 'model_003',
          name: '病害预测模型',
          version: 'v1.8.0',
          provider: 'PlantAI',
          callTime: 1.2,
          response: {
            diseaseRisk: 0.78,
            predictedDisease: '晚疫病',
            confidence: 0.85,
          },
        },
      ],
      rulesMatched: [
        {
          ruleId: 'rule_003',
          ruleName: '病虫害防治规则',
          category: '植保管理',
          priority: 10,
          matched: true,
          confidence: 0.9,
          conditions: [
            '病害风险 > 0.7',
            '高温高湿环境',
            '出现症状',
          ],
          actions: [
            '立即采取防治措施',
            '使用推荐农药',
            '加强田间管理',
          ],
        },
      ],
      fusionProcess: [],
      intermediateResults: [],
      finalDecision: {
        recommendation: '立即使用甲霜灵防治晚疫病',
        confidence: 0.85,
        reasoning: '检测到高风险，需要立即干预',
        actionItems: [
          '准备防治药剂',
          '选择合适时机喷药',
          '密切观察效果',
        ],
        estimatedImpact: '可有效控制病害蔓延',
      },
      execution: {
        status: 'failed',
        result: '用户取消执行',
        feedback: '药剂不足，需要补充',
      },
    },
    {
      id: 'log_003',
      timestamp: '2024-10-23 09:45:12',
      status: 'partial',
      level: 'normal',
      type: '施肥决策',
      scenario: '苗期追肥',
      summary: '根据土壤养分分析制定追肥方案',
      executionTime: 1.8,
      executionType: 'auto',
      trigger: {
        source: '定时监测',
        event: '定期土壤检测',
        userId: 'system_001',
        userName: '系统监测',
        conditionsMet: '检测周期到达',
      },
      inputData: {
        cropType: '黄瓜',
        growthStage: '苗期',
        soilNutrients: {
          nitrogen: 45,
          phosphorus: 28,
          potassium: 120,
        },
        fieldArea: 1.8,
      },
      modelService: [
        {
          id: 'model_004',
          name: '养分需求模型',
          version: 'v2.0.1',
          provider: 'FertilizerAI',
          callTime: 0.6,
          response: {
            recommendedNPK: [15, 10, 20],
            totalAmount: 45,
            confidence: 0.88,
          },
        },
      ],
      rulesMatched: [
        {
          ruleId: 'rule_004',
          ruleName: '苗期施肥规则',
          category: '营养管理',
          priority: 7,
          matched: true,
          confidence: 0.82,
          conditions: [
            '生长阶段 = 苗期',
            '氮含量 < 50mg/kg',
            '磷含量 < 30mg/kg',
          ],
          actions: [
            '补充氮磷钾肥',
            '控制施肥量',
            '分次施用',
          ],
        },
      ],
      fusionProcess: [],
      intermediateResults: [],
      finalDecision: {
        recommendation: '追施NPK复合肥45kg/公顷',
        confidence: 0.88,
        reasoning: '土壤养分不足，需要补充',
        actionItems: [
          '采购复合肥',
          '分2次施用',
          '监测效果',
        ],
        estimatedImpact: '提升土壤养分，促进苗期生长',
      },
      execution: {
        status: 'partial',
        appliedAt: '2024-10-23 10:00:00',
        result: '部分完成，第一次施肥已完成',
        feedback: '肥料库存不足，需要补充',
      },
    },
  ]);

  // 统计数据
  const stats = {
    totalLogs: decisionLogs.length,
    successRate: Math.round((decisionLogs.filter(log => log.status === 'success').length / decisionLogs.length) * 100),
    avgExecutionTime: (decisionLogs.reduce((sum, log) => sum + log.executionTime, 0) / decisionLogs.length).toFixed(1),
  };

  // 模拟审计数据
  const auditTrails: AuditTrail[] = [
    {
      id: 'audit_001',
      decisionId: 'log_001',
      action: '创建决策',
      timestamp: '2024-10-23 14:30:25',
      user: '系统',
      details: '自动生成灌溉决策',
      ipAddress: '192.168.1.100',
    },
    {
      id: 'audit_002',
      decisionId: 'log_001',
      action: '执行决策',
      timestamp: '2024-10-23 17:30:00',
      user: '系统',
      details: '自动执行灌溉操作',
      ipAddress: '192.168.1.100',
    },
    {
      id: 'audit_003',
      decisionId: 'log_002',
      action: '用户查看',
      timestamp: '2024-10-23 12:20:00',
      user: '李四',
      details: '查看病害防治决策详情',
      ipAddress: '192.168.1.101',
    },
    {
      id: 'audit_004',
      decisionId: 'log_002',
      action: '取消执行',
      timestamp: '2024-10-23 12:25:00',
      user: '李四',
      details: '用户取消病害防治执行',
      ipAddress: '192.168.1.101',
    },
  ];

  const getStatusBadge = (status: DecisionStatus) => {
    const config = {
      success: {
        label: '成功',
        className: 'bg-success-muted text-success-muted-foreground border-success',
        icon: CheckCircle,
      },
      failed: {
        label: '失败',
        className: 'bg-error-muted text-error-muted-foreground border-error',
        icon: XCircle,
      },
      partial: {
        label: '部分成功',
        className: 'bg-warning-muted text-warning-muted-foreground border-warning',
        icon: AlertTriangle,
      },
      cancelled: {
        label: '已取消',
        className: 'bg-muted text-muted-foreground border-border',
        icon: XCircle,
      },
    };

    const { label, className, icon: Icon } = config[status];
    return (
      <Badge variant="outline" className={className}>
        <Icon className="w-3 h-3 mr-1" />
        {label}
      </Badge>
    );
  };

  const getLevelBadge = (level: DecisionLevel) => {
    const config = {
      critical: { label: '紧急', className: 'bg-error-muted text-error-muted-foreground border-error' },
      important: { label: '重要', className: 'bg-warning-muted text-warning-muted-foreground border-warning' },
      normal: { label: '普通', className: 'bg-info-muted text-info-muted-foreground border-info' },
      suggestion: { label: '建议', className: 'bg-muted text-muted-foreground border-border' },
    };
    const { label, className } = config[level];
    return <Badge variant="outline" className={className}>{label}</Badge>;
  };

  // 筛选日志
  const filteredLogs = decisionLogs.filter(log => {
    if (filters.status !== 'all' && log.status !== filters.status) return false;
    if (filters.level !== 'all' && log.level !== filters.level) return false;
    if (filters.type !== 'all' && log.type !== filters.type) return false;
    if (filters.executionType !== 'all' && log.executionType !== filters.executionType) return false;
    if (filters.searchText && !log.summary.toLowerCase().includes(filters.searchText.toLowerCase())) return false;
    return true;
  });

  const handleViewDetail = (log: DecisionLog) => {
    setSelectedLog(log);
    setShowDetailDialog(true);
  };

  const handleViewAudit = (log: DecisionLog) => {
    setSelectedLog(log);
    setShowAuditDialog(true);
  };

  const toggleSection = (section: string) => {
    const newExpanded = new Set(expandedSections);
    if (newExpanded.has(section)) {
      newExpanded.delete(section);
    } else {
      newExpanded.add(section);
    }
    setExpandedSections(newExpanded);
  };

  
  const handleRefresh = () => {
    toast.success('日志已刷新');
  };

  // 图表数据
  const statusChartData = [
    { name: '成功', value: decisionLogs.filter(log => log.status === 'success').length, color: '#10b981' },
    { name: '失败', value: decisionLogs.filter(log => log.status === 'failed').length, color: '#ef4444' },
    { name: '部分成功', value: decisionLogs.filter(log => log.status === 'partial').length, color: '#f59e0b' },
    { name: '已取消', value: decisionLogs.filter(log => log.status === 'cancelled').length, color: '#6b7280' },
  ];

  const typeChartData = [
    { name: '灌溉决策', value: decisionLogs.filter(log => log.type === '灌溉决策').length },
    { name: '病虫害防治', value: decisionLogs.filter(log => log.type === '病虫害防治').length },
    { name: '施肥决策', value: decisionLogs.filter(log => log.type === '施肥决策').length },
    { name: '其他', value: decisionLogs.filter(log => !['灌溉决策', '病虫害防治', '施肥决策'].includes(log.type)).length },
  ];

  return (
    <div className="space-y-6">
      {/* 页面标题 */}
      <Card className="p-6 bg-gradient-to-r from-info-muted to-accent-muted border-info">
        <div className="flex items-start gap-3">
          <FileText className="w-6 h-6 text-info 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">
                <Database className="w-3 h-3 mr-1" />
                完整追溯
              </Badge>
              <Badge variant="outline" className="bg-white">
                <Shield className="w-3 h-3 mr-1" />
                审计合规
              </Badge>
              <Badge variant="outline" className="bg-white">
                <Search className="w-3 h-3 mr-1" />
                结构化查询
              </Badge>
              <Badge variant="outline" className="bg-white">
                <History className="w-3 h-3 mr-1" />
                历史回溯
              </Badge>
            </div>
          </div>
        </div>
      </Card>

      {/* 决策日志 */}
      <div className="space-y-6">
          {/* 统计卡片 */}
          <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>
                <FileText className="w-5 h-5 text-blue-500" />
              </div>
              <div className="text-3xl font-bold mb-1">{stats.totalLogs}</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">{stats.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-orange-500" />
              </div>
              <div className="text-3xl font-bold mb-1">{stats.avgExecutionTime}s</div>
              <div className="text-xs text-muted-foreground">响应迅速</div>
            </Card>
          </div>

          {/* 筛选条件 */}
          <Card className="p-6">
            <div className="flex items-center gap-4 mb-4">
              <h3>筛选条件</h3>
            </div>

            <div className="grid grid-cols-5 gap-4">
              <div>
                <Label>执行类型</Label>
                <Select value={filters.executionType} onValueChange={(value) => setFilters({ ...filters, executionType: value as any })}>
                  <SelectTrigger>
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="all">全部</SelectItem>
                    <SelectItem value="manual">👤 手动执行</SelectItem>
                    <SelectItem value="auto">⚡ 自动执行</SelectItem>
                  </SelectContent>
                </Select>
              </div>

              <div>
                <Label>状态</Label>
                <Select value={filters.status} onValueChange={(value) => setFilters({ ...filters, status: value })}>
                  <SelectTrigger>
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="all">全部</SelectItem>
                    <SelectItem value="success">成功</SelectItem>
                    <SelectItem value="failed">失败</SelectItem>
                    <SelectItem value="partial">部分成功</SelectItem>
                    <SelectItem value="cancelled">已取消</SelectItem>
                  </SelectContent>
                </Select>
              </div>

              <div>
                <Label>类型</Label>
                <Select value={filters.type} onValueChange={(value) => setFilters({ ...filters, type: value })}>
                  <SelectTrigger>
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="all">全部</SelectItem>
                    <SelectItem value="灌溉决策">灌溉决策</SelectItem>
                    <SelectItem value="病虫害防治">病虫害防治</SelectItem>
                    <SelectItem value="施肥决策">施肥决策</SelectItem>
                    <SelectItem value="综合决策">综合决策</SelectItem>
                  </SelectContent>
                </Select>
              </div>

              <div>
                <Label>时间范围</Label>
                <Select value={filters.dateRange} onValueChange={(value) => setFilters({ ...filters, dateRange: value })}>
                  <SelectTrigger>
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="today">今天</SelectItem>
                    <SelectItem value="7days">最近7天</SelectItem>
                    <SelectItem value="30days">最近30天</SelectItem>
                    <SelectItem value="all">全部</SelectItem>
                  </SelectContent>
                </Select>
              </div>

              <div>
                <Label>搜索</Label>
                <div className="relative">
                  <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground" />
                  <Input
                    placeholder="搜索日志..."
                    value={filters.searchText}
                    onChange={(e) => setFilters({ ...filters, searchText: e.target.value })}
                    className="pl-9"
                  />
                </div>
              </div>
            </div>
          </Card>

          {/* 日志列表 */}
          <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" onClick={handleRefresh}>
                  <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>
                  <TableHead>操作</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {filteredLogs.map((log) => (
                  <TableRow key={log.id}>
                    <TableCell>
                      <code className="text-xs bg-muted px-2 py-1 rounded">{log.id}</code>
                    </TableCell>
                    <TableCell>
                      <div className="text-sm">{log.timestamp}</div>
                    </TableCell>
                    <TableCell>
                      {log.executionType === 'auto' ? (
                        <Badge variant="outline" className="bg-accent/20 text-accent border-accent/40">
                          <Zap className="w-3 h-3 mr-1" />
                          自动执行
                        </Badge>
                      ) : (
                        <Badge variant="outline" className="bg-blue-50 text-blue-700 border-blue-300">
                          <User className="w-3 h-3 mr-1" />
                          手动执行
                        </Badge>
                      )}
                      {log.executionType === 'auto' && log.trigger.conditionsMet && (
                        <div className="text-xs text-muted-foreground mt-1">
                          {log.trigger.conditionsMet}
                        </div>
                      )}
                    </TableCell>
                    <TableCell>
                      <Badge variant="outline">{log.type}</Badge>
                    </TableCell>
                    <TableCell>
                      <div className="max-w-xs">
                        <div className="font-medium text-sm">{log.scenario}</div>
                        <div className="text-xs text-muted-foreground truncate">{log.summary}</div>
                      </div>
                    </TableCell>
                    <TableCell>{getStatusBadge(log.status)}</TableCell>
                    <TableCell>
                      <div className="text-sm">{log.executionTime}s</div>
                    </TableCell>
                    <TableCell>
                      <div className="text-sm">{log.trigger.userName}</div>
                      <div className="text-xs text-muted-foreground">{log.trigger.source}</div>
                    </TableCell>
                    <TableCell>
                      <div className="flex gap-2">
                        <Button size="sm" variant="outline" onClick={() => handleViewDetail(log)}>
                          <Eye className="w-4 h-4" />
                        </Button>
                        <Button size="sm" variant="outline" onClick={() => handleViewAudit(log)}>
                          <Shield className="w-4 h-4" />
                        </Button>
                      </div>
                    </TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>
          </Card>
        </div>

      {/* 详情对话框 */}
      <Dialog open={showDetailDialog} onOpenChange={setShowDetailDialog}>
        <DialogContent className="max-w-6xl max-h-[90vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle>决策日志详情</DialogTitle>
            <DialogDescription>
              查看完整的决策生成过程和所有中间数据
            </DialogDescription>
          </DialogHeader>

          {selectedLog && (
            <div className="space-y-6">
              {/* 基本信息 */}
              <div>
                <div className="flex items-center justify-between mb-3">
                  <h4>基本信息</h4>
                  <div className="flex items-center gap-2">
                    {getStatusBadge(selectedLog.status)}
                    {getLevelBadge(selectedLog.level)}
                  </div>
                </div>
                <div className="grid grid-cols-4 gap-4 text-sm">
                  <div>
                    <div className="text-xs text-muted-foreground mb-1">日志ID</div>
                    <code className="text-xs bg-muted px-2 py-1 rounded">{selectedLog.id}</code>
                  </div>
                  <div>
                    <div className="text-xs text-muted-foreground mb-1">生成时间</div>
                    <div>{selectedLog.timestamp}</div>
                  </div>
                  <div>
                    <div className="text-xs text-muted-foreground mb-1">执行耗时</div>
                    <div>{selectedLog.executionTime}秒</div>
                  </div>
                  <div>
                    <div className="text-xs text-muted-foreground mb-1">决策类型</div>
                    <Badge variant="outline">{selectedLog.type}</Badge>
                  </div>
                </div>
              </div>

              <Separator />

              {/* 触发信息 */}
              <div>
                <button
                  onClick={() => toggleSection('trigger')}
                  className="flex items-center gap-2 mb-3 hover:text-info"
                >
                  {expandedSections.has('trigger') ? (
                    <ChevronDown className="w-4 h-4" />
                  ) : (
                    <ChevronRight className="w-4 h-4" />
                  )}
                  <h4>触发信息</h4>
                </button>
                {expandedSections.has('trigger') && (
                  <div className="p-4 bg-muted rounded-lg space-y-2">
                    <div className="grid grid-cols-2 gap-4 text-sm">
                      <div>
                        <span className="text-muted-foreground">触发源：</span>
                        <span className="ml-2 font-medium">{selectedLog.trigger.source}</span>
                      </div>
                      <div>
                        <span className="text-muted-foreground">触发事件：</span>
                        <span className="ml-2 font-medium">{selectedLog.trigger.event}</span>
                      </div>
                      <div>
                        <span className="text-muted-foreground">用户：</span>
                        <span className="ml-2 font-medium">{selectedLog.trigger.userName}</span>
                      </div>
                      <div>
                        <span className="text-muted-foreground">用户ID：</span>
                        <code className="ml-2 text-xs bg-white px-2 py-1 rounded">{selectedLog.trigger.userId}</code>
                      </div>
                    </div>
                  </div>
                )}
              </div>

              <Separator />

              {/* 输入数据 */}
              <div>
                <button
                  onClick={() => toggleSection('input')}
                  className="flex items-center gap-2 mb-3 hover:text-info"
                >
                  {expandedSections.has('input') ? (
                    <ChevronDown className="w-4 h-4" />
                  ) : (
                    <ChevronRight className="w-4 h-4" />
                  )}
                  <h4>输入数据明细</h4>
                  <Badge variant="outline" className="text-xs">
                    {Object.keys(selectedLog.inputData).length} 个参数
                  </Badge>
                </button>
                {expandedSections.has('input') && (
                  <div className="p-4 bg-muted rounded-lg">
                    <div className="grid grid-cols-3 gap-3 text-sm">
                      {Object.entries(selectedLog.inputData).map(([key, value]) => (
                        <div key={key} className="p-3 bg-white rounded border">
                          <div className="text-xs text-muted-foreground mb-1">{key}</div>
                          <div className="font-medium">{String(value)}</div>
                        </div>
                      ))}
                    </div>
                  </div>
                )}
              </div>

              <Separator />

              {/* 模型服务调用 */}
              <div>
                <button
                  onClick={() => toggleSection('model')}
                  className="flex items-center gap-2 mb-3 hover:text-info"
                >
                  {expandedSections.has('model') ? (
                    <ChevronDown className="w-4 h-4" />
                  ) : (
                    <ChevronRight className="w-4 h-4" />
                  )}
                  <h4>模型服务调用</h4>
                  <Badge variant="outline" className="text-xs">
                    {selectedLog.modelService.length} 个模型
                  </Badge>
                </button>
                {expandedSections.has('model') && (
                  <div className="space-y-3">
                    {selectedLog.modelService.map((model, idx) => (
                      <div key={idx} className="p-4 bg-blue-50 border border-blue-200 rounded-lg">
                        <div className="flex items-start justify-between mb-3">
                          <div>
                            <div className="font-medium mb-1">{model.name}</div>
                            <div className="flex items-center gap-2 text-sm text-muted-foreground">
                              <Badge variant="outline" className="text-xs">v{model.version}</Badge>
                              <span>·</span>
                              <span>{model.provider}</span>
                              <span>·</span>
                              <span>耗时: {model.callTime}s</span>
                            </div>
                          </div>
                          <code className="text-xs bg-white px-2 py-1 rounded">{model.id}</code>
                        </div>
                        <div className="p-3 bg-white rounded">
                          <div className="text-xs text-muted-foreground mb-2">响应数据：</div>
                          <pre className="text-xs overflow-x-auto">
                            {JSON.stringify(model.response, null, 2)}
                          </pre>
                        </div>
                      </div>
                    ))}
                  </div>
                )}
              </div>

              {/* 执行情况 */}
              {selectedLog.execution.appliedAt && (
                <>
                  <Separator />
                  <div>
                    <h4 className="mb-3">执行情况</h4>
                    <div className="p-4 bg-green-50 border border-green-200 rounded-lg">
                      <div className="grid grid-cols-2 gap-4 text-sm mb-3">
                        <div>
                          <span className="text-muted-foreground">执行时间：</span>
                          <span className="ml-2 font-medium">{selectedLog.execution.appliedAt}</span>
                        </div>
                        <div>
                          <span className="text-muted-foreground">执行人：</span>
                          <span className="ml-2 font-medium">{selectedLog.execution.appliedBy}</span>
                        </div>
                      </div>
                      {selectedLog.execution.result && (
                        <div className="p-3 bg-white rounded mb-2">
                          <div className="text-xs text-muted-foreground mb-1">执行结果：</div>
                          <div className="text-sm">{selectedLog.execution.result}</div>
                        </div>
                      )}
                      {selectedLog.execution.feedback && (
                        <div className="p-3 bg-white rounded">
                          <div className="text-xs text-muted-foreground mb-1">执行反馈：</div>
                          <div className="text-sm">{selectedLog.execution.feedback}</div>
                        </div>
                      )}
                    </div>
                  </div>
                </>
              )}
            </div>
          )}

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

      {/* 审计对话框 */}
      <Dialog open={showAuditDialog} onOpenChange={setShowAuditDialog}>
        <DialogContent className="max-w-4xl">
          <DialogHeader>
            <DialogTitle>审计追踪</DialogTitle>
            <DialogDescription>
              查看该决策的所有操作记录
            </DialogDescription>
          </DialogHeader>

          <div className="space-y-4">
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead>时间</TableHead>
                  <TableHead>操作</TableHead>
                  <TableHead>用户</TableHead>
                  <TableHead>详情</TableHead>
                  <TableHead>IP地址</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {auditTrails
                  .filter(trail => trail.decisionId === selectedLog?.id)
                  .map((trail) => (
                    <TableRow key={trail.id}>
                      <TableCell className="text-sm">{trail.timestamp}</TableCell>
                      <TableCell>{trail.action}</TableCell>
                      <TableCell>{trail.user}</TableCell>
                      <TableCell className="text-sm">{trail.details}</TableCell>
                      <TableCell className="text-sm">{trail.ipAddress}</TableCell>
                    </TableRow>
                  ))}
              </TableBody>
            </Table>
          </div>

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