import { useState } from 'react';
import { Card } from '../ui/card';
import { Button } from '../ui/button';
import { Badge } from '../ui/badge';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '../ui/select';
import { Input } from '../ui/input';
import { Label } from '../ui/label';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription, DialogFooter } from '../ui/dialog';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '../ui/table';
import {
  FileText,
  Download,
  Eye,
  Clock,
  CheckCircle,
  XCircle,
  AlertCircle,
  MapPin,
  Database,
  Cpu,
  GitBranch,
  Zap,
  Target,
  BarChart3,
  Activity,
  Info,
  PlayCircle,
  FileCode,
  Timer,
  Code,
} from 'lucide-react';
import { toast } from 'sonner@2.0.3';

interface AIAuditLogProps {
  activePath?: string;
}

// 执行状态
type ExecutionStatus = 'success' | 'failed' | 'partial' | 'running';

// 步骤状态
type StepStatus = 'success' | 'failed' | 'skipped' | 'running';

// 决策类型
type DecisionType = '灌溉决策' | '施肥决策' | '病虫害预警' | '产量预测' | '生长监测';

// 审计日志
interface AuditLog {
  id: string;
  traceId: string;
  decisionNo: string;
  decisionType: DecisionType;
  fieldName: string;
  fieldArea: number;
  cropType: string;
  
  // 执行时间
  startTime: string;
  endTime: string;
  duration: number; // 毫秒
  
  // 状态
  status: ExecutionStatus;
  
  // 执行步骤
  steps: ExecutionStep[];
  
  // 统计信息
  totalSteps: number;
  successSteps: number;
  failedSteps: number;
  
  // 性能指标
  performance: {
    dataInputTime: number;
    modelCalcTime: number;
    ruleMatchTime: number;
    decisionGenTime: number;
    actionExecTime: number;
  };
  
  // 用户信息
  userId: string;
  userName: string;
  
  // 备注
  remark?: string;
}

// 执行步骤
interface ExecutionStep {
  id: string;
  stepNo: number;
  stepName: string;
  stepType: 'data-input' | 'model-calc' | 'rule-match' | 'decision-gen' | 'action-exec';
  status: StepStatus;
  startTime: string;
  endTime: string;
  duration: number;
  
  // 输入输出
  input?: any;
  output?: any;
  
  // 详细信息
  details?: {
    modelId?: string;
    modelName?: string;
    modelVersion?: string;
    ruleId?: string;
    ruleName?: string;
    confidence?: number;
    parameters?: Record<string, any>;
  };
  
  // 错误信息
  error?: {
    code: string;
    message: string;
    stack?: string;
  };
}

export function AIAuditLog({ activePath }: AIAuditLogProps) {
  const [selectedLog, setSelectedLog] = useState<AuditLog | null>(null);
  const [showLogDetail, setShowLogDetail] = useState(false);
  const [selectedStep, setSelectedStep] = useState<ExecutionStep | null>(null);
  const [showStepDetail, setShowStepDetail] = useState(false);
  
  // 筛选条件
  const [filters, setFilters] = useState({
    status: 'all',
    fieldName: '',
    decisionNo: '',
    startDate: '',
    endDate: '',
  });

  // 审计日志数据
  const [auditLogs] = useState<AuditLog[]>([
    {
      id: 'log_001',
      traceId: 'trace_20241023_001',
      decisionNo: 'DEC-20241023-001',
      decisionType: '灌溉决策',
      fieldName: '1号田',
      fieldArea: 5.2,
      cropType: '番茄',
      startTime: '2024-10-23 14:30:00',
      endTime: '2024-10-23 14:30:05',
      duration: 5280,
      status: 'success',
      totalSteps: 5,
      successSteps: 5,
      failedSteps: 0,
      performance: {
        dataInputTime: 320,
        modelCalcTime: 1850,
        ruleMatchTime: 980,
        decisionGenTime: 1420,
        actionExecTime: 710,
      },
      userId: 'user_001',
      userName: '张三',
      steps: [
        {
          id: 'step_001_1',
          stepNo: 1,
          stepName: '数据输入与验证',
          stepType: 'data-input',
          status: 'success',
          startTime: '2024-10-23 14:30:00.000',
          endTime: '2024-10-23 14:30:00.320',
          duration: 320,
          input: {
            fieldId: 'field_001',
            fieldName: '1号田',
            cropType: '番茄',
            growthStage: '开花期',
            sensors: {
              soilMoisture: 35,
              temperature: 26.5,
              humidity: 65,
            },
          },
          output: {
            validation: 'passed',
            dataQuality: 'high',
            missingFields: [],
          },
          details: {
            parameters: {
              validationRules: ['soil_moisture_range', 'temperature_range', 'humidity_range'],
              dataSource: 'IoT传感器',
              dataTimestamp: '2024-10-23 14:29:55',
            },
          },
        },
        {
          id: 'step_001_2',
          stepNo: 2,
          stepName: '模型计算',
          stepType: 'model-calc',
          status: 'success',
          startTime: '2024-10-23 14:30:00.320',
          endTime: '2024-10-23 14:30:02.170',
          duration: 1850,
          input: {
            soilMoisture: 35,
            temperature: 26.5,
            humidity: 65,
            cropType: '番茄',
            growthStage: '开花期',
          },
          output: {
            needWater: true,
            recommendedAmount: 1200,
            irrigationTime: '傍晚17:00-18:00',
            confidence: 0.92,
          },
          details: {
            modelId: 'model_001',
            modelName: '作物需水预测模型',
            modelVersion: 'v2.1.0',
            confidence: 0.92,
            parameters: {
              modelType: 'deep_learning',
              features: ['soil_moisture', 'temperature', 'humidity', 'crop_stage'],
              algorithm: 'LSTM',
            },
          },
        },
        {
          id: 'step_001_3',
          stepNo: 3,
          stepName: '规则匹配',
          stepType: 'rule-match',
          status: 'success',
          startTime: '2024-10-23 14:30:02.170',
          endTime: '2024-10-23 14:30:03.150',
          duration: 980,
          input: {
            modelOutput: {
              needWater: true,
              recommendedAmount: 1200,
            },
            currentConditions: {
              soilMoisture: 35,
              weatherForecast: '未来3天无降雨',
            },
          },
          output: {
            matchedRules: [
              {
                ruleId: 'rule_001',
                ruleName: '番茄开花期灌溉规则',
                priority: 'high',
                action: 'irrigate',
              },
            ],
            conflictResolution: 'none',
          },
          details: {
            ruleId: 'rule_001',
            ruleName: '番茄开花期灌溉规则',
            parameters: {
              moistureThreshold: 40,
              timeWindow: '17:00-18:00',
              minInterval: 48,
            },
          },
        },
        {
          id: 'step_001_4',
          stepNo: 4,
          stepName: '决策生成',
          stepType: 'decision-gen',
          status: 'success',
          startTime: '2024-10-23 14:30:03.150',
          endTime: '2024-10-23 14:30:04.570',
          duration: 1420,
          input: {
            modelRecommendation: {
              needWater: true,
              amount: 1200,
              time: '傍晚17:00-18:00',
            },
            ruleConstraints: {
              moistureThreshold: 40,
              timeWindow: '17:00-18:00',
            },
          },
          output: {
            decision: {
              action: '启动灌溉',
              amount: 1200,
              time: '今日17:00',
              priority: 'high',
              reason: '土壤湿度35%低于40%阈值，开花期需水关键期',
            },
            alternatives: [
              {
                action: '延迟至明日清晨',
                reason: '如温度低于25℃可延迟',
              },
            ],
          },
          details: {
            parameters: {
              decisionStrategy: 'model_rule_fusion',
              modelWeight: 0.6,
              ruleWeight: 0.4,
              confidenceThreshold: 0.85,
            },
          },
        },
        {
          id: 'step_001_5',
          stepNo: 5,
          stepName: '执行动作',
          stepType: 'action-exec',
          status: 'success',
          startTime: '2024-10-23 14:30:04.570',
          endTime: '2024-10-23 14:30:05.280',
          duration: 710,
          input: {
            decision: {
              action: '启动灌溉',
              amount: 1200,
              time: '今日17:00',
            },
          },
          output: {
            executionResult: 'scheduled',
            taskId: 'task_001',
            scheduledTime: '2024-10-23 17:00:00',
            deviceStatus: 'ready',
          },
          details: {
            parameters: {
              executionMode: 'scheduled',
              deviceId: 'irrigation_001',
              notificationSent: true,
              notificationChannels: ['app', 'sms'],
            },
          },
        },
      ],
    },
    {
      id: 'log_002',
      traceId: 'trace_20241023_002',
      decisionNo: 'DEC-20241023-002',
      decisionType: '病虫害预警',
      fieldName: '2号大棚',
      fieldArea: 2.5,
      cropType: '黄瓜',
      startTime: '2024-10-23 15:15:00',
      endTime: '2024-10-23 15:15:08',
      duration: 8350,
      status: 'success',
      totalSteps: 5,
      successSteps: 5,
      failedSteps: 0,
      performance: {
        dataInputTime: 450,
        modelCalcTime: 3200,
        ruleMatchTime: 1100,
        decisionGenTime: 2800,
        actionExecTime: 800,
      },
      userId: 'user_002',
      userName: '李四',
      steps: [
        {
          id: 'step_002_1',
          stepNo: 1,
          stepName: '数据输入与验证',
          stepType: 'data-input',
          status: 'success',
          startTime: '2024-10-23 15:15:00.000',
          endTime: '2024-10-23 15:15:00.450',
          duration: 450,
          input: {
            fieldId: 'field_002',
            fieldName: '2号大棚',
            cropType: '黄瓜',
            images: ['image_001.jpg', 'image_002.jpg'],
            environmentData: {
              temperature: 26.8,
              humidity: 72,
              lightIntensity: 8500,
            },
          },
          output: {
            validation: 'passed',
            imageQuality: 'high',
            imageCount: 2,
          },
          details: {
            parameters: {
              imageResolution: '1920x1080',
              imageFormat: 'JPEG',
              dataSource: '病虫害监测摄像头',
            },
          },
        },
        {
          id: 'step_002_2',
          stepNo: 2,
          stepName: '模型计算',
          stepType: 'model-calc',
          status: 'success',
          startTime: '2024-10-23 15:15:00.450',
          endTime: '2024-10-23 15:15:03.650',
          duration: 3200,
          input: {
            images: ['image_001.jpg', 'image_002.jpg'],
            cropType: '黄瓜',
            environmentData: {
              temperature: 26.8,
              humidity: 72,
            },
          },
          output: {
            diseaseDetected: true,
            diseaseType: '霜霉病',
            severity: 'medium',
            affectedArea: 15,
            confidence: 0.94,
          },
          details: {
            modelId: 'model_002',
            modelName: '病虫害识别模型',
            modelVersion: 'v1.8.0',
            confidence: 0.94,
            parameters: {
              modelType: 'CNN',
              features: ['leaf_color', 'spot_pattern', 'area_ratio'],
              algorithm: 'ResNet50',
            },
          },
        },
        {
          id: 'step_002_3',
          stepNo: 3,
          stepName: '规则匹配',
          stepType: 'rule-match',
          status: 'success',
          startTime: '2024-10-23 15:15:03.650',
          endTime: '2024-10-23 15:15:04.750',
          duration: 1100,
          input: {
            diseaseType: '霜霉病',
            severity: 'medium',
            environmentData: {
              temperature: 26.8,
              humidity: 72,
            },
          },
          output: {
            matchedRules: [
              {
                ruleId: 'rule_002',
                ruleName: '黄瓜霜霉病预警规则',
                priority: 'critical',
                action: 'immediate_treatment',
              },
            ],
            riskLevel: 'high',
          },
          details: {
            ruleId: 'rule_002',
            ruleName: '黄瓜霜霉病预警规则',
            parameters: {
              humidityThreshold: 70,
              temperatureRange: [18, 30],
              treatmentWindow: 72,
            },
          },
        },
        {
          id: 'step_002_4',
          stepNo: 4,
          stepName: '决策生成',
          stepType: 'decision-gen',
          status: 'success',
          startTime: '2024-10-23 15:15:04.750',
          endTime: '2024-10-23 15:15:07.550',
          duration: 2800,
          input: {
            diseaseInfo: {
              type: '霜霉病',
              severity: 'medium',
              affectedArea: 15,
            },
            ruleAction: 'immediate_treatment',
          },
          output: {
            decision: {
              action: '紧急预警！72小时内处理',
              treatment: '喷施百菌清或甲霜灵',
              dosage: '800倍稀释液',
              frequency: '每7天一次，连续2-3次',
              preventiveMeasures: [
                '加强通风',
                '降低湿度至60%以下',
                '提高温度至28℃',
                '隔离病株',
              ],
            },
            priority: 'critical',
          },
          details: {
            parameters: {
              decisionStrategy: 'expert_system',
              knowledgeBase: 'disease_treatment_kb',
              treatmentProtocol: 'protocol_霜霉病_001',
            },
          },
        },
        {
          id: 'step_002_5',
          stepNo: 5,
          stepName: '执行动作',
          stepType: 'action-exec',
          status: 'success',
          startTime: '2024-10-23 15:15:07.550',
          endTime: '2024-10-23 15:15:08.350',
          duration: 800,
          input: {
            decision: {
              action: '紧急预警',
              priority: 'critical',
            },
          },
          output: {
            notificationSent: true,
            notificationChannels: ['app', 'sms', 'phone'],
            taskCreated: true,
            taskId: 'task_002',
          },
          details: {
            parameters: {
              recipients: ['农场主', '技术员', '值班人员'],
              escalationLevel: 'high',
              taskDeadline: '2024-10-26 15:15:00',
            },
          },
        },
      ],
    },
    {
      id: 'log_003',
      traceId: 'trace_20241023_003',
      decisionNo: 'DEC-20241023-003',
      decisionType: '施肥决策',
      fieldName: '5号田',
      fieldArea: 20.0,
      cropType: '玉米',
      startTime: '2024-10-23 16:20:00',
      endTime: '2024-10-23 16:20:12',
      duration: 12500,
      status: 'partial',
      totalSteps: 5,
      successSteps: 4,
      failedSteps: 1,
      performance: {
        dataInputTime: 520,
        modelCalcTime: 4200,
        ruleMatchTime: 1800,
        decisionGenTime: 3500,
        actionExecTime: 0,
      },
      userId: 'user_001',
      userName: '张三',
      steps: [
        {
          id: 'step_003_1',
          stepNo: 1,
          stepName: '数据输入与验证',
          stepType: 'data-input',
          status: 'success',
          startTime: '2024-10-23 16:20:00.000',
          endTime: '2024-10-23 16:20:00.520',
          duration: 520,
          input: {
            fieldId: 'field_005',
            fieldName: '5号田',
            cropType: '玉米',
            growthStage: '拔节期',
            soilTest: {
              nitrogen: 45,
              phosphorus: 28,
              potassium: 180,
              pH: 6.5,
            },
          },
          output: {
            validation: 'passed',
            dataQuality: 'high',
          },
        },
        {
          id: 'step_003_2',
          stepNo: 2,
          stepName: '模型计算',
          stepType: 'model-calc',
          status: 'success',
          startTime: '2024-10-23 16:20:00.520',
          endTime: '2024-10-23 16:20:04.720',
          duration: 4200,
          input: {
            soilNutrients: {
              nitrogen: 45,
              phosphorus: 28,
              potassium: 180,
            },
            cropType: '玉米',
            growthStage: '拔节期',
            targetYield: 650,
          },
          output: {
            needFertilizer: true,
            recommendations: {
              urea: 15,
              potash: 5,
            },
            expectedYieldIncrease: 15,
            confidence: 0.90,
          },
          details: {
            modelId: 'model_004',
            modelName: '施肥决策模型',
            modelVersion: 'v2.3.0',
            confidence: 0.90,
          },
        },
        {
          id: 'step_003_3',
          stepNo: 3,
          stepName: '规则匹配',
          stepType: 'rule-match',
          status: 'success',
          startTime: '2024-10-23 16:20:04.720',
          endTime: '2024-10-23 16:20:06.520',
          duration: 1800,
          input: {
            modelOutput: {
              urea: 15,
              potash: 5,
            },
            soilConditions: {
              nitrogen: 45,
              pH: 6.5,
            },
          },
          output: {
            matchedRules: [
              {
                ruleId: 'rule_003',
                ruleName: '玉米拔节期施肥规则',
                adjustments: {
                  urea: 12,
                  potash: 5,
                },
              },
            ],
          },
        },
        {
          id: 'step_003_4',
          stepNo: 4,
          stepName: '决策生成',
          stepType: 'decision-gen',
          status: 'success',
          startTime: '2024-10-23 16:20:06.520',
          endTime: '2024-10-23 16:20:10.020',
          duration: 3500,
          input: {
            modelRecommendation: {
              urea: 15,
              potash: 5,
            },
            ruleAdjustment: {
              urea: 12,
              potash: 5,
            },
          },
          output: {
            decision: {
              action: '追肥',
              fertilizers: [
                { name: '尿素', amount: 12, unit: 'kg/亩' },
                { name: '钾肥', amount: 5, unit: 'kg/亩' },
              ],
              method: '沟施+浇水',
              timing: '本周内完成',
              expectedIncrease: '产量提升15%',
              costBenefit: '投入产出比1:3.5',
            },
          },
        },
        {
          id: 'step_003_5',
          stepNo: 5,
          stepName: '执行动作',
          stepType: 'action-exec',
          status: 'failed',
          startTime: '2024-10-23 16:20:10.020',
          endTime: '2024-10-23 16:20:12.500',
          duration: 2480,
          input: {
            decision: {
              action: '追肥',
            },
          },
          error: {
            code: 'DEVICE_OFFLINE',
            message: '施肥设备离线，无法执行自动施肥',
            stack: 'DeviceConnectionError: Device irrigation_005 is offline',
          },
        },
      ],
      remark: '设备离线导致自动执行失败，已转人工处理',
    },
  ]);

  // 统计数据
  const stats = {
    totalLogs: auditLogs.length,
    successRate: ((auditLogs.filter(l => l.status === 'success').length / auditLogs.length) * 100).toFixed(1),
    avgDuration: Math.round(auditLogs.reduce((sum, l) => sum + l.duration, 0) / auditLogs.length),
    todayLogs: auditLogs.filter(l => l.startTime.startsWith('2024-10-23')).length,
  };

  const getStatusBadge = (status: ExecutionStatus) => {
    const config = {
      success: { label: '成功', icon: CheckCircle, className: 'bg-success-muted text-success-muted-foreground' },
      failed: { label: '失败', icon: XCircle, className: 'bg-error-muted text-error-muted-foreground' },
      partial: { label: '部分成功', icon: AlertCircle, className: 'bg-warning-muted text-warning-muted-foreground' },
      running: { label: '执行中', icon: Activity, className: 'bg-info-muted text-info-muted-foreground' },
    };
    const { label, icon: Icon, className } = config[status];
    return (
      <Badge variant="outline" className={className}>
        <Icon className="w-3 h-3 mr-1" />
        {label}
      </Badge>
    );
  };

  const getStepStatusBadge = (status: StepStatus) => {
    const config = {
      success: { label: '成功', className: 'bg-success-muted text-success-muted-foreground' },
      failed: { label: '失败', className: 'bg-error-muted text-error-muted-foreground' },
      skipped: { label: '跳过', className: 'bg-muted text-muted-foreground' },
      running: { label: '执行中', className: 'bg-info-muted text-info-muted-foreground' },
    };
    const { label, className } = config[status];
    return <Badge className={className}>{label}</Badge>;
  };

  const getStepIcon = (stepType: ExecutionStep['stepType']) => {
    const icons = {
      'data-input': Database,
      'model-calc': Cpu,
      'rule-match': GitBranch,
      'decision-gen': Zap,
      'action-exec': PlayCircle,
    };
    return icons[stepType];
  };

  const getStepTypeName = (stepType: ExecutionStep['stepType']) => {
    const names = {
      'data-input': '数据输入',
      'model-calc': '模型计算',
      'rule-match': '规则匹配',
      'decision-gen': '决策生成',
      'action-exec': '执行动作',
    };
    return names[stepType];
  };

  const handleViewLog = (log: AuditLog) => {
    setSelectedLog(log);
    setShowLogDetail(true);
  };

  const handleViewStep = (step: ExecutionStep) => {
    setSelectedStep(step);
    setShowStepDetail(true);
  };

  const handleExport = () => {
    toast.success('审计日志已导出');
  };

  const handleGenerateReport = () => {
    toast.success('审计报告生成中...');
  };

  // 筛选日志
  const filteredLogs = auditLogs.filter(log => {
    if (filters.status !== 'all' && log.status !== filters.status) return false;
    if (filters.fieldName && !log.fieldName.toLowerCase().includes(filters.fieldName.toLowerCase())) return false;
    if (filters.decisionNo && !log.decisionNo.toLowerCase().includes(filters.decisionNo.toLowerCase())) return false;
    if (filters.startDate && log.startTime < filters.startDate) return false;
    if (filters.endDate && log.startTime > filters.endDate) return false;
    return true;
  });

  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">
                <Activity className="w-3 h-3 mr-1" />
                完整链路
              </Badge>
              <Badge variant="outline" className="bg-white">
                <Clock 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">
                <BarChart3 className="w-3 h-3 mr-1" />
                性能优化
              </Badge>
            </div>
          </div>
        </div>
      </Card>

      {/* 统计卡片 */}
      <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>
            <FileText className="w-5 h-5 text-info" />
          </div>
          <div className="text-3xl font-bold mb-1">{stats.totalLogs}</div>
          <div className="text-xs text-muted-foreground">
            今日: {stats.todayLogs}条
          </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-success" />
          </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>
            <Timer className="w-5 h-5 text-accent-foreground" />
          </div>
          <div className="text-3xl font-bold mb-1">{stats.avgDuration}</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>
            <AlertCircle className="w-5 h-5 text-warning" />
          </div>
          <div className="text-3xl font-bold mb-1">
            {auditLogs.filter(l => l.status === 'failed' || l.status === 'partial').length}
          </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" onClick={handleExport}>
              <Download className="w-4 h-4 mr-2" />
              导出
            </Button>
            <Button variant="outline" size="sm" onClick={handleGenerateReport}>
              <FileCode className="w-4 h-4 mr-2" />
              生成报告
            </Button>
          </div>
        </div>

        {/* 查询条件 */}
        <div className="grid grid-cols-3 gap-4 mb-4">
          <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="partial">部分成功</SelectItem>
                <SelectItem value="failed">失败</SelectItem>
              </SelectContent>
            </Select>
          </div>

          <div>
            <Label>地块名称</Label>
            <Input
              placeholder="搜索地块..."
              value={filters.fieldName}
              onChange={(e) => setFilters({ ...filters, fieldName: e.target.value })}
            />
          </div>

          <div>
            <Label>决策编号</Label>
            <Input
              placeholder="搜索决策编号..."
              value={filters.decisionNo}
              onChange={(e) => setFilters({ ...filters, decisionNo: e.target.value })}
            />
          </div>

          <div>
            <Label>开始时间</Label>
            <Input
              type="datetime-local"
              value={filters.startDate}
              onChange={(e) => setFilters({ ...filters, startDate: e.target.value })}
            />
          </div>

          <div>
            <Label>结束时间</Label>
            <Input
              type="datetime-local"
              value={filters.endDate}
              onChange={(e) => setFilters({ ...filters, endDate: e.target.value })}
            />
          </div>
        </div>

        {/* 日志列表 */}
        <div className="border rounded-lg overflow-hidden">
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead>追踪ID</TableHead>
                <TableHead>决策编号</TableHead>
                <TableHead>地块信息</TableHead>
                <TableHead>执行时间</TableHead>
                <TableHead>耗时</TableHead>
                <TableHead>状态</TableHead>
                <TableHead>操作</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {filteredLogs.map((log) => (
                <TableRow key={log.id}>
                  <TableCell className="font-mono text-xs">{log.traceId}</TableCell>
                  <TableCell className="font-medium">{log.decisionNo}</TableCell>
                  <TableCell>
                    <div className="flex items-center gap-1">
                      <MapPin className="w-3 h-3 text-muted-foreground" />
                      <span>{log.fieldName}</span>
                      <span className="text-xs text-muted-foreground">({log.fieldArea}亩)</span>
                    </div>
                  </TableCell>
                  <TableCell className="text-sm">{log.startTime}</TableCell>
                  <TableCell>
                    <div className="flex items-center gap-1">
                      <Clock className="w-3 h-3 text-muted-foreground" />
                      <span>{log.duration}ms</span>
                    </div>
                  </TableCell>
                  <TableCell>{getStatusBadge(log.status)}</TableCell>
                  <TableCell>
                    <Button size="sm" variant="outline" onClick={() => handleViewLog(log)}>
                      <Eye className="w-3 h-3 mr-1" />
                      详情
                    </Button>
                  </TableCell>
                </TableRow>
              ))}
            </TableBody>
          </Table>
        </div>
      </Card>

      {/* 日志详情对话框 */}
      <Dialog open={showLogDetail} onOpenChange={setShowLogDetail}>
        <DialogContent className="max-w-6xl max-h-[90vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle>审计日志详情</DialogTitle>
            <DialogDescription>
              查看决策执行的完整流水记录
            </DialogDescription>
          </DialogHeader>

          {selectedLog && (
            <div className="space-y-6">
              {/* 基本信息 */}
              <div>
                <h4 className="mb-3">基本信息</h4>
                <div className="grid grid-cols-3 gap-4">
                  <div className="p-3 bg-muted rounded">
                    <div className="text-xs text-muted-foreground mb-1">追踪ID</div>
                    <div className="font-mono text-sm">{selectedLog.traceId}</div>
                  </div>
                  <div className="p-3 bg-muted rounded">
                    <div className="text-xs text-muted-foreground mb-1">决策编号</div>
                    <div className="font-medium">{selectedLog.decisionNo}</div>
                  </div>
                  <div className="p-3 bg-muted rounded">
                    <div className="text-xs text-muted-foreground mb-1">决策类型</div>
                    <div className="font-medium">{selectedLog.decisionType}</div>
                  </div>
                  <div className="p-3 bg-muted rounded">
                    <div className="text-xs text-muted-foreground mb-1">地块信息</div>
                    <div className="font-medium">{selectedLog.fieldName} ({selectedLog.fieldArea}亩)</div>
                  </div>
                  <div className="p-3 bg-muted rounded">
                    <div className="text-xs text-muted-foreground mb-1">作物类型</div>
                    <div className="font-medium">{selectedLog.cropType}</div>
                  </div>
                  <div className="p-3 bg-muted rounded">
                    <div className="text-xs text-muted-foreground mb-1">执行用户</div>
                    <div className="font-medium">{selectedLog.userName}</div>
                  </div>
                </div>
              </div>

              {/* 执行统计 */}
              <div>
                <h4 className="mb-3">执行统计</h4>
                <div className="grid grid-cols-4 gap-4">
                  <div className="p-4 bg-info/10 rounded-lg text-center">
                    <div className="text-xs text-muted-foreground mb-1">开始时间</div>
                    <div className="text-sm font-medium">{selectedLog.startTime}</div>
                  </div>
                  <div className="p-4 bg-success/10 rounded-lg text-center">
                    <div className="text-xs text-muted-foreground mb-1">结束时间</div>
                    <div className="text-sm font-medium">{selectedLog.endTime}</div>
                  </div>
                  <div className="p-4 bg-accent/20 rounded-lg text-center">
                    <div className="text-xs text-muted-foreground mb-1">总耗时</div>
                    <div className="text-sm font-medium">{selectedLog.duration}ms</div>
                  </div>
                  <div className="p-4 bg-warning/10 rounded-lg text-center">
                    <div className="text-xs text-muted-foreground mb-1">执行状态</div>
                    <div>{getStatusBadge(selectedLog.status)}</div>
                  </div>
                </div>
              </div>

              {/* 执行步骤 */}
              <div>
                <h4 className="mb-3">执行步骤 ({selectedLog.successSteps}/{selectedLog.totalSteps})</h4>
                <div className="space-y-3">
                  {selectedLog.steps.map((step) => {
                    const StepIcon = getStepIcon(step.stepType);
                    return (
                      <div key={step.id} className="p-4 border rounded-lg">
                        <div className="flex items-start gap-3">
                          <div className={`w-10 h-10 rounded-full flex items-center justify-center flex-shrink-0 ${
                            step.status === 'success' ? 'bg-success-muted text-success' :
                            step.status === 'failed' ? 'bg-error-muted text-error' :
                            'bg-muted text-muted-foreground'
                          }`}>
                            <StepIcon className="w-5 h-5" />
                          </div>
                          
                          <div className="flex-1">
                            <div className="flex items-center justify-between mb-2">
                              <div>
                                <div className="flex items-center gap-2">
                                  <span className="font-medium">步骤{step.stepNo}：{step.stepName}</span>
                                  {getStepStatusBadge(step.status)}
                                </div>
                                <p className="text-sm text-muted-foreground mt-1">
                                  {getStepTypeName(step.stepType)}
                                </p>
                              </div>
                              <div className="text-sm text-muted-foreground">
                                {step.duration}ms
                              </div>
                            </div>

                            {step.details && (
                              <div className="p-3 bg-muted rounded-lg mb-2">
                                <div className="text-xs font-medium mb-2">步骤详情：</div>
                                {step.details.modelName && (
                                  <div className="text-xs mb-1">
                                    模型: {step.details.modelName} {step.details.modelVersion}
                                  </div>
                                )}
                                {step.details.ruleName && (
                                  <div className="text-xs mb-1">
                                    规则: {step.details.ruleName}
                                  </div>
                                )}
                                {step.details.confidence && (
                                  <div className="text-xs mb-1">
                                    置信度: {(step.details.confidence * 100).toFixed(1)}%
                                  </div>
                                )}
                              </div>
                            )}

                            {step.error && (
                              <div className="p-3 bg-destructive/10 border border-destructive/30 rounded-lg">
                                <div className="flex items-start gap-2">
                                  <XCircle className="w-4 h-4 text-destructive flex-shrink-0 mt-0.5" />
                                  <div>
                                    <div className="text-sm font-medium text-destructive mb-1">
                                      错误: {step.error.code}
                                    </div>
                                    <div className="text-xs text-destructive">{step.error.message}</div>
                                  </div>
                                </div>
                              </div>
                            )}

                            <Button
                              size="sm"
                              variant="outline"
                              onClick={() => handleViewStep(step)}
                              className="mt-2"
                            >
                              <Code className="w-3 h-3 mr-1" />
                              查看输入输出
                            </Button>
                          </div>
                        </div>
                      </div>
                    );
                  })}
                </div>
              </div>
            </div>
          )}

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

      {/* 步骤详情对话框 */}
      <Dialog open={showStepDetail} onOpenChange={setShowStepDetail}>
        <DialogContent className="max-w-4xl max-h-[90vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle>步骤详情</DialogTitle>
            <DialogDescription>
              查看步骤的输入输出数据
            </DialogDescription>
          </DialogHeader>

          {selectedStep && (
            <div className="space-y-4">
              <div>
                <h4 className="mb-2">步骤信息</h4>
                <div className="p-3 bg-muted rounded">
                  <div className="grid grid-cols-2 gap-3 text-sm">
                    <div>步骤名称: {selectedStep.stepName}</div>
                    <div>执行时间: {selectedStep.startTime}</div>
                    <div>执行状态: {getStepStatusBadge(selectedStep.status)}</div>
                    <div>耗时: {selectedStep.duration}ms</div>
                  </div>
                </div>
              </div>

              {selectedStep.input && (
                <div>
                  <h4 className="mb-2">输入数据</h4>
                  <div className="p-4 bg-info/10 border border-info/30 rounded-lg">
                    <pre className="text-sm overflow-x-auto">
                      {JSON.stringify(selectedStep.input, null, 2)}
                    </pre>
                  </div>
                </div>
              )}

              {selectedStep.output && (
                <div>
                  <h4 className="mb-2">输出数据</h4>
                  <div className="p-4 bg-success/10 border border-success/30 rounded-lg">
                    <pre className="text-sm overflow-x-auto">
                      {JSON.stringify(selectedStep.output, null, 2)}
                    </pre>
                  </div>
                </div>
              )}

              {selectedStep.error && (
                <div>
                  <h4 className="mb-2">错误信息</h4>
                  <div className="p-4 bg-destructive/10 border border-destructive/30 rounded-lg">
                    <div className="text-sm">
                      <div className="mb-2">
                        <strong>错误代码:</strong> {selectedStep.error.code}
                      </div>
                      <div className="mb-2">
                        <strong>错误消息:</strong> {selectedStep.error.message}
                      </div>
                      {selectedStep.error.stack && (
                        <div>
                          <strong>堆栈跟踪:</strong>
                          <pre className="mt-1 text-xs overflow-x-auto">
                            {selectedStep.error.stack}
                          </pre>
                        </div>
                      )}
                    </div>
                  </div>
                </div>
              )}
            </div>
          )}

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