import { useState, useEffect } from 'react';
import { Card } from '../ui/card';
import { Button } from '../ui/button';
import { Badge } from '../ui/badge';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '../ui/tabs';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '../ui/select';
import { Input } from '../ui/input';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription, DialogFooter } from '../ui/dialog';
import { Label } from '../ui/label';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '../ui/table';
import { Progress } from '../ui/progress';
import { Switch } from '../ui/switch';
import { Textarea } from '../ui/textarea';
import {
  Calendar,
  Clock,
  Play,
  Pause,
  StopCircle,
  RefreshCw,
  AlertCircle,
  CheckCircle,
  XCircle,
  Timer,
  Zap,
  Activity,
  BarChart3,
  Settings,
  Eye,
  PlayCircle,
  PauseCircle,
  RotateCcw,
  Trash2,
  Filter,
  Search,
  Download,
  AlertTriangle,
  TrendingUp,
  Users,
  Layers,
  Database,
  Cpu,
  Server,
  Bell,
  ChevronRight,
  FileText,
  GitBranch,
  ListChecks,
  Workflow,
  CircleDot,
} from 'lucide-react';
import { toast } from 'sonner@2.0.3';
import {
  LineChart,
  Line,
  BarChart,
  Bar,
  XAxis,
  YAxis,
  CartesianGrid,
  Tooltip as RechartsTooltip,
  Legend,
  ResponsiveContainer,
  PieChart,
  Pie,
  Cell,
} from 'recharts';

interface AISchedulingManagementProps {
  activePath?: string;
}

// 调度任务状态
type TaskStatus = 'waiting' | 'running' | 'completed' | 'failed' | 'cancelled' | 'paused' | 'retrying';

// 触发类型
type TriggerType = 'cron' | 'interval' | 'event' | 'threshold' | 'manual' | 'dependency';

// 任务优先级
type Priority = 'critical' | 'high' | 'medium' | 'low';

// 重试策略
type RetryStrategy = 'immediate' | 'exponential' | 'fixed' | 'none';

// 调度任务
interface ScheduleTask {
  id: string;
  taskNo: string;
  name: string;
  applicationId: string;
  applicationName: string;
  triggerType: TriggerType;
  triggerConfig: any;
  priority: Priority;
  status: TaskStatus;
  scheduledTime: string;
  actualStartTime?: string;
  actualEndTime?: string;
  executionTime?: number;
  retryCount: number;
  maxRetry: number;
  retryStrategy: RetryStrategy;
  errorMessage?: string;
  result?: any;
  createdBy: string;
  createdAt: string;
  updatedAt: string;
}

// 调度规则
interface ScheduleRule {
  id: string;
  name: string;
  description: string;
  applicationId: string;
  applicationName: string;
  triggerType: TriggerType;
  triggerConfig: any;
  priority: Priority;
  enabled: boolean;
  maxRetry: number;
  retryStrategy: RetryStrategy;
  timeout: number;
  concurrent: boolean;
  maxConcurrent?: number;
  validFrom?: string;
  validTo?: string;
  createdAt: string;
  updatedAt: string;
  lastTriggeredAt?: string;
  nextTriggerAt?: string;
  totalRuns: number;
  successRuns: number;
  failedRuns: number;
}

// 任务队列统计
interface QueueStats {
  waiting: number;
  running: number;
  completed: number;
  failed: number;
  cancelled: number;
  paused: number;
  total: number;
}

// 执行日志
interface ExecutionLog {
  id: string;
  taskId: string;
  taskNo: string;
  applicationName: string;
  startTime: string;
  endTime?: string;
  status: TaskStatus;
  executionTime?: number;
  inputData?: any;
  outputData?: any;
  errorMessage?: string;
  retryCount: number;
  cpuUsage?: number;
  memoryUsage?: number;
}

export function AISchedulingManagement({ activePath }: AISchedulingManagementProps) {
  const [activeTab, setActiveTab] = useState('overview');
  const [showRuleDialog, setShowRuleDialog] = useState(false);
  const [showTaskDialog, setShowTaskDialog] = useState(false);
  const [showLogDialog, setShowLogDialog] = useState(false);
  const [showCreateTaskDialog, setShowCreateTaskDialog] = useState(false);
  const [showTaskDetailDialog, setShowTaskDetailDialog] = useState(false);
  const [selectedRule, setSelectedRule] = useState<ScheduleRule | null>(null);
  const [selectedTask, setSelectedTask] = useState<ScheduleTask | null>(null);
  const [editingRule, setEditingRule] = useState<Partial<ScheduleRule>>({});
  
  // 新增任务表单数据
  const [newTaskData, setNewTaskData] = useState({
    name: '',
    applicationId: '',
    inputDataSources: {} as Record<string, string>,
    priority: 'medium' as Priority,
    timeStrategy: 'cron' as 'cron' | 'interval' | 'daily',
    cronExpression: '',
    intervalMinutes: 60,
    dailyTime: '08:00',
  });

  // 可用应用列表
  const [availableApplications] = useState([
    {
      id: 'app-1',
      name: '智能灌溉策略生成',
      inputFields: ['土壤湿度', '温度', '降水预报', '作物类型', '生长阶段'],
    },
    {
      id: 'app-2',
      name: '病虫害智能预警',
      inputFields: ['作物图像', '温湿度', '历史病害记录'],
    },
    {
      id: 'app-3',
      name: '精准施肥推荐',
      inputFields: ['N含量', 'P含量', 'K含量', '作物品种', 'pH值'],
    },
    {
      id: 'app-4',
      name: '作物产量预测',
      inputFields: ['生长天数', '气象数据', '土壤类型', '施肥记录', '灌溉记录'],
    },
  ]);

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

  // 队列统计
  const [queueStats] = useState<QueueStats>({
    waiting: 15,
    running: 8,
    completed: 1247,
    failed: 23,
    cancelled: 5,
    paused: 3,
    total: 1301,
  });

  // 调度规则
  const [scheduleRules, setScheduleRules] = useState<ScheduleRule[]>([
    {
      id: 'rule-1',
      name: '智能灌溉定时调度',
      description: '每天早晚两次检测土壤湿度并生成灌溉方案',
      applicationId: 'app-1',
      applicationName: '智能灌溉策略生成',
      triggerType: 'cron',
      triggerConfig: { cron: '0 6,18 * * *' },
      priority: 'high',
      enabled: true,
      maxRetry: 3,
      retryStrategy: 'exponential',
      timeout: 300,
      concurrent: false,
      validFrom: '2024-01-01',
      createdAt: '2024-08-15 10:00:00',
      updatedAt: '2024-10-15 15:30:00',
      lastTriggeredAt: '2024-10-23 18:00:00',
      nextTriggerAt: '2024-10-24 06:00:00',
      totalRuns: 246,
      successRuns: 244,
      failedRuns: 2,
    },
    {
      id: 'rule-2',
      name: '病虫害实时监测',
      description: '当新的作物图像采集完成时触发病虫害识别',
      applicationId: 'app-2',
      applicationName: '病虫害智能预警',
      triggerType: 'event',
      triggerConfig: { event: 'image_captured' },
      priority: 'critical',
      enabled: true,
      maxRetry: 2,
      retryStrategy: 'immediate',
      timeout: 120,
      concurrent: true,
      maxConcurrent: 5,
      createdAt: '2024-09-01 09:00:00',
      updatedAt: '2024-10-20 11:20:00',
      lastTriggeredAt: '2024-10-23 14:30:00',
      totalRuns: 562,
      successRuns: 556,
      failedRuns: 6,
    },
    {
      id: 'rule-3',
      name: '施肥周期推荐',
      description: '每周一生成本周施肥计划',
      applicationId: 'app-3',
      applicationName: '精准施肥推荐',
      triggerType: 'cron',
      triggerConfig: { cron: '0 8 * * 1' },
      priority: 'medium',
      enabled: true,
      maxRetry: 3,
      retryStrategy: 'fixed',
      timeout: 180,
      concurrent: false,
      createdAt: '2024-07-20 14:00:00',
      updatedAt: '2024-10-15 16:00:00',
      lastTriggeredAt: '2024-10-21 08:00:00',
      nextTriggerAt: '2024-10-28 08:00:00',
      totalRuns: 15,
      successRuns: 15,
      failedRuns: 0,
    },
    {
      id: 'rule-4',
      name: '产量预测更新',
      description: '每3小时更新一次产量预测模型',
      applicationId: 'app-4',
      applicationName: '作物产量预测',
      triggerType: 'interval',
      triggerConfig: { interval: 180 }, // 分钟
      priority: 'medium',
      enabled: true,
      maxRetry: 2,
      retryStrategy: 'exponential',
      timeout: 240,
      concurrent: false,
      createdAt: '2024-09-10 10:00:00',
      updatedAt: '2024-10-22 09:00:00',
      lastTriggeredAt: '2024-10-23 12:00:00',
      nextTriggerAt: '2024-10-23 15:00:00',
      totalRuns: 248,
      successRuns: 246,
      failedRuns: 2,
    },
    {
      id: 'rule-5',
      name: '温度异常预警',
      description: '当温度超过35°C时触发预警',
      applicationId: 'app-5',
      applicationName: '气象灾害预警',
      triggerType: 'threshold',
      triggerConfig: { 
        metric: 'temperature',
        operator: '>',
        value: 35,
        duration: 10 // 持续10分钟
      },
      priority: 'critical',
      enabled: true,
      maxRetry: 1,
      retryStrategy: 'none',
      timeout: 60,
      concurrent: true,
      maxConcurrent: 3,
      createdAt: '2024-08-25 11:00:00',
      updatedAt: '2024-10-18 14:00:00',
      lastTriggeredAt: '2024-10-20 14:25:00',
      totalRuns: 18,
      successRuns: 18,
      failedRuns: 0,
    },
  ]);

  // 正在执行的任务
  const [runningTasks] = useState<ScheduleTask[]>([
    {
      id: 'task-1',
      taskNo: 'SCH-20241023-001',
      name: '智能灌溉策略生成',
      applicationId: 'app-1',
      applicationName: '智能灌溉策略生成',
      triggerType: 'cron',
      triggerConfig: { cron: '0 6,18 * * *' },
      priority: 'high',
      status: 'running',
      scheduledTime: '2024-10-23 18:00:00',
      actualStartTime: '2024-10-23 18:00:05',
      executionTime: 45,
      retryCount: 0,
      maxRetry: 3,
      retryStrategy: 'exponential',
      createdBy: 'System',
      createdAt: '2024-10-23 18:00:00',
      updatedAt: '2024-10-23 18:00:05',
    },
    {
      id: 'task-2',
      taskNo: 'SCH-20241023-002',
      name: '病虫害智能预警',
      applicationId: 'app-2',
      applicationName: '病虫害智能预警',
      triggerType: 'event',
      triggerConfig: { event: 'image_captured' },
      priority: 'critical',
      status: 'running',
      scheduledTime: '2024-10-23 14:30:15',
      actualStartTime: '2024-10-23 14:30:18',
      executionTime: 32,
      retryCount: 0,
      maxRetry: 2,
      retryStrategy: 'immediate',
      createdBy: 'Event Trigger',
      createdAt: '2024-10-23 14:30:15',
      updatedAt: '2024-10-23 14:30:18',
    },
  ]);

  // 待执行任务
  const [waitingTasks] = useState<ScheduleTask[]>([
    {
      id: 'task-3',
      taskNo: 'SCH-20241024-001',
      name: '智能灌溉策略生成',
      applicationId: 'app-1',
      applicationName: '智能灌溉策略生成',
      triggerType: 'cron',
      triggerConfig: { cron: '0 6,18 * * *' },
      priority: 'high',
      status: 'waiting',
      scheduledTime: '2024-10-24 06:00:00',
      retryCount: 0,
      maxRetry: 3,
      retryStrategy: 'exponential',
      createdBy: 'System',
      createdAt: '2024-10-23 18:00:00',
      updatedAt: '2024-10-23 18:00:00',
    },
    {
      id: 'task-4',
      taskNo: 'SCH-20241023-003',
      name: '产量预测更新',
      applicationId: 'app-4',
      applicationName: '作物产量预测',
      triggerType: 'interval',
      triggerConfig: { interval: 180 },
      priority: 'medium',
      status: 'waiting',
      scheduledTime: '2024-10-23 15:00:00',
      retryCount: 0,
      maxRetry: 2,
      retryStrategy: 'exponential',
      createdBy: 'System',
      createdAt: '2024-10-23 12:00:00',
      updatedAt: '2024-10-23 12:00:00',
    },
  ]);

  // 执行日志
  const [executionLogs] = useState<ExecutionLog[]>([
    {
      id: 'log-1',
      taskId: 'task-100',
      taskNo: 'SCH-20241023-100',
      applicationName: '智能灌溉策略生成',
      startTime: '2024-10-23 06:00:05',
      endTime: '2024-10-23 06:02:18',
      status: 'completed',
      executionTime: 133,
      retryCount: 0,
      cpuUsage: 45,
      memoryUsage: 512,
    },
    {
      id: 'log-2',
      taskId: 'task-101',
      taskNo: 'SCH-20241023-101',
      applicationName: '病虫害智能预警',
      startTime: '2024-10-23 10:15:20',
      endTime: '2024-10-23 10:16:55',
      status: 'completed',
      executionTime: 95,
      retryCount: 0,
      cpuUsage: 62,
      memoryUsage: 768,
    },
    {
      id: 'log-3',
      taskId: 'task-102',
      taskNo: 'SCH-20241023-102',
      applicationName: '产量预测更新',
      startTime: '2024-10-23 09:00:10',
      endTime: '2024-10-23 09:00:25',
      status: 'failed',
      executionTime: 15,
      errorMessage: '数据库连接超时',
      retryCount: 3,
      cpuUsage: 25,
      memoryUsage: 256,
    },
  ]);

  // 性能数据
  const performanceData = [
    { time: '00:00', tasks: 12, success: 12, failed: 0 },
    { time: '03:00', tasks: 8, success: 8, failed: 0 },
    { time: '06:00', tasks: 25, success: 24, failed: 1 },
    { time: '09:00', tasks: 18, success: 17, failed: 1 },
    { time: '12:00', tasks: 22, success: 22, failed: 0 },
    { time: '15:00', tasks: 15, success: 15, failed: 0 },
    { time: '18:00', tasks: 30, success: 29, failed: 1 },
    { time: '21:00', tasks: 10, success: 10, failed: 0 },
  ];

  const priorityDistribution = [
    { name: '紧急', value: queueStats.waiting * 0.1, color: '#ef4444' },
    { name: '高', value: queueStats.waiting * 0.3, color: '#f97316' },
    { name: '中', value: queueStats.waiting * 0.4, color: '#3b82f6' },
    { name: '低', value: queueStats.waiting * 0.2, color: '#6b7280' },
  ];

  const handleCreateRule = () => {
    setEditingRule({
      enabled: true,
      maxRetry: 3,
      retryStrategy: 'exponential',
      timeout: 300,
      concurrent: false,
      priority: 'medium',
    });
    setSelectedRule(null);
    setShowRuleDialog(true);
  };

  const handleEditRule = (rule: ScheduleRule) => {
    setSelectedRule(rule);
    setEditingRule(rule);
    setShowRuleDialog(true);
  };

  const handleSaveRule = () => {
    if (selectedRule) {
      // 更新规则
      setScheduleRules(scheduleRules.map(r => 
        r.id === selectedRule.id ? { ...selectedRule, ...editingRule } : r
      ));
      toast.success('调度规则已更新');
    } else {
      // 新增规则
      const newRule: ScheduleRule = {
        id: `rule-${Date.now()}`,
        ...editingRule as ScheduleRule,
        createdAt: new Date().toISOString(),
        updatedAt: new Date().toISOString(),
        totalRuns: 0,
        successRuns: 0,
        failedRuns: 0,
      };
      setScheduleRules([...scheduleRules, newRule]);
      toast.success('调度规则已创建');
    }
    setShowRuleDialog(false);
  };

  const handleToggleRule = (ruleId: string) => {
    setScheduleRules(scheduleRules.map(r => 
      r.id === ruleId ? { ...r, enabled: !r.enabled } : r
    ));
    const rule = scheduleRules.find(r => r.id === ruleId);
    toast.success(`调度规则已${rule?.enabled ? '禁用' : '启用'}`);
  };

  const handleDeleteRule = (ruleId: string) => {
    setScheduleRules(scheduleRules.filter(r => r.id !== ruleId));
    toast.success('调度规则已删除');
  };

  const handleManualTrigger = (ruleId: string) => {
    const rule = scheduleRules.find(r => r.id === ruleId);
    if (rule) {
      toast.success(`已手动触发: ${rule.name}`);
    }
  };

  const handlePauseTask = (taskId: string) => {
    toast.success('任务已暂停');
  };

  const handleResumeTask = (taskId: string) => {
    toast.success('任务已恢复');
  };

  const handleCancelTask = (taskId: string) => {
    toast.success('任务已取消');
  };

  const handleRetryTask = (taskId: string) => {
    toast.success('任务已重新启动');
  };

  // 打开新增调度任务对话框
  const handleOpenCreateTask = () => {
    setNewTaskData({
      name: '',
      applicationId: '',
      inputDataSources: {},
      priority: 'medium',
      timeStrategy: 'cron',
      cronExpression: '0 8 * * *',
      intervalMinutes: 60,
      dailyTime: '08:00',
    });
    setShowCreateTaskDialog(true);
  };

  // 保存新增调度任务
  const handleSaveTask = () => {
    if (!newTaskData.name) {
      toast.error('请输入任务名称');
      return;
    }
    if (!newTaskData.applicationId) {
      toast.error('请选择应用');
      return;
    }

    const selectedApp = availableApplications.find(app => app.id === newTaskData.applicationId);
    if (selectedApp) {
      // 验证所有入参都已配置数据源
      const missingFields = selectedApp.inputFields.filter(
        field => !newTaskData.inputDataSources[field]
      );
      if (missingFields.length > 0) {
        toast.error(`请为以下字段配置数据源：${missingFields.join('、')}`);
        return;
      }
    }

    // 生成触发配置
    let triggerType: TriggerType = 'cron';
    let triggerConfig: any = {};

    if (newTaskData.timeStrategy === 'cron') {
      triggerType = 'cron';
      triggerConfig = { cron: newTaskData.cronExpression };
    } else if (newTaskData.timeStrategy === 'interval') {
      triggerType = 'interval';
      triggerConfig = { interval: newTaskData.intervalMinutes };
    } else if (newTaskData.timeStrategy === 'daily') {
      triggerType = 'cron';
      const [hour, minute] = newTaskData.dailyTime.split(':');
      triggerConfig = { cron: `${minute} ${hour} * * *` };
    }

    const newRule: ScheduleRule = {
      id: `rule-${Date.now()}`,
      name: newTaskData.name,
      description: `任务数据源：${Object.entries(newTaskData.inputDataSources).map(([k, v]) => `${k}=${v}`).join(', ')}`,
      applicationId: newTaskData.applicationId,
      applicationName: selectedApp?.name || '',
      triggerType,
      triggerConfig,
      priority: newTaskData.priority,
      enabled: true,
      maxRetry: 3,
      retryStrategy: 'exponential',
      timeout: 300,
      concurrent: false,
      createdAt: new Date().toLocaleString('zh-CN'),
      updatedAt: new Date().toLocaleString('zh-CN'),
      totalRuns: 0,
      successRuns: 0,
      failedRuns: 0,
    };

    setScheduleRules([...scheduleRules, newRule]);
    setShowCreateTaskDialog(false);
    toast.success(`调度任务"${newTaskData.name}"创建成功！`);
  };

  // 手动触发任务
  const handleManualExecute = () => {
    if (!newTaskData.name) {
      toast.error('请输入任务名称');
      return;
    }
    if (!newTaskData.applicationId) {
      toast.error('请选择应用');
      return;
    }

    const selectedApp = availableApplications.find(app => app.id === newTaskData.applicationId);
    toast.success(`已手动触发任务："${newTaskData.name}"，应用：${selectedApp?.name}`);
  };

  // 查看任务详情
  const handleViewTaskDetail = (task: ScheduleTask) => {
    setSelectedTask(task);
    setShowTaskDetailDialog(true);
  };

  const getStatusBadge = (status: TaskStatus) => {
    const statusConfig = {
      waiting: { label: '等待中', variant: 'outline' as const, color: 'text-muted-foreground' },
      running: { label: '运行中', variant: 'default' as const, color: 'text-info' },
      completed: { label: '已完成', variant: 'secondary' as const, color: 'text-success' },
      failed: { label: '失败', variant: 'destructive' as const, color: 'text-error' },
      cancelled: { label: '已取消', variant: 'outline' as const, color: 'text-muted-foreground' },
      paused: { label: '已暂停', variant: 'outline' as const, color: 'text-warning' },
      retrying: { label: '重试中', variant: 'default' as const, color: 'text-warning' },
    };
    const config = statusConfig[status];
    return <Badge variant={config.variant}>{config.label}</Badge>;
  };

  const getPriorityBadge = (priority: Priority) => {
    const priorityConfig = {
      critical: { label: '紧急', className: 'bg-error-muted text-error-muted-foreground border-error' },
      high: { label: '高', className: 'bg-warning-muted text-warning-muted-foreground border-warning' },
      medium: { label: '中', className: 'bg-info-muted text-info-muted-foreground border-info' },
      low: { label: '低', className: 'bg-muted text-muted-foreground border-border' },
    };
    const config = priorityConfig[priority];
    return <Badge variant="outline" className={config.className}>{config.label}</Badge>;
  };

  const getTriggerTypeLabel = (type: TriggerType) => {
    const labels: Record<TriggerType, string> = {
      cron: 'Cron定时',
      interval: '周期间隔',
      event: '事件触发',
      threshold: '阈值触发',
      manual: '手动触发',
      dependency: '依赖触发',
    };
    return labels[type];
  };

  const getRetryStrategyLabel = (strategy: RetryStrategy) => {
    const labels: Record<RetryStrategy, string> = {
      immediate: '立即重试',
      exponential: '指数退避',
      fixed: '固定间隔',
      none: '不重试',
    };
    return labels[strategy];
  };

  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">
          <Workflow 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">
              企业级任务调度引擎，支持多种触发策略、任务队列管理、实时监控和异常重试，保障7×24小时无人值守稳定运行
            </p>
            <div className="flex flex-wrap gap-2">
              <Badge variant="outline" className="bg-white">
                <Zap className="w-3 h-3 mr-1" />
                智能调度
              </Badge>
              <Badge variant="outline" className="bg-white">
                <Activity className="w-3 h-3 mr-1" />
                实时监控
              </Badge>
              <Badge variant="outline" className="bg-white">
                <RotateCcw className="w-3 h-3 mr-1" />
                异常重试
              </Badge>
              <Badge variant="outline" className="bg-white">
                <Server className="w-3 h-3 mr-1" />
                7×24运行
              </Badge>
            </div>
          </div>
        </div>
      </Card>

      <Tabs value={activeTab} onValueChange={setActiveTab} className="space-y-4">
        <TabsList>
          <TabsTrigger value="overview">
            <BarChart3 className="w-4 h-4 mr-2" />
            调度概览
          </TabsTrigger>
          <TabsTrigger value="rules">
            <Settings className="w-4 h-4 mr-2" />
            调度规则
          </TabsTrigger>
          <TabsTrigger value="queue">
            <Layers className="w-4 h-4 mr-2" />
            任务队列
          </TabsTrigger>
          <TabsTrigger value="logs">
            <FileText className="w-4 h-4 mr-2" />
            执行日志
          </TabsTrigger>
        </TabsList>

        {/* 调度概览 */}
        <TabsContent value="overview" 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>
                <Clock className="w-5 h-5 text-muted-foreground" />
              </div>
              <div className="text-3xl font-bold mb-1">{queueStats.waiting}</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>
                <PlayCircle className="w-5 h-5 text-info" />
              </div>
              <div className="text-3xl font-bold mb-1 text-info">{queueStats.running}</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-success" />
              </div>
              <div className="text-3xl font-bold mb-1 text-success">{queueStats.completed}</div>
              <div className="text-xs text-muted-foreground">
                成功率 {((queueStats.completed / queueStats.total) * 100).toFixed(1)}%
              </div>
            </Card>

            <Card className="p-6">
              <div className="flex items-center justify-between mb-2">
                <div className="text-sm text-muted-foreground">失败</div>
                <XCircle className="w-5 h-5 text-red-500" />
              </div>
              <div className="text-3xl font-bold mb-1 text-red-600">{queueStats.failed}</div>
              <div className="text-xs text-muted-foreground">
                失败率 {((queueStats.failed / queueStats.total) * 100).toFixed(1)}%
              </div>
            </Card>
          </div>

          {/* 图表区域 */}
          <div className="grid grid-cols-2 gap-6">
            <Card className="p-6">
              <h3 className="mb-4">任务执行趋势</h3>
              <ResponsiveContainer width="100%" height={300}>
                <LineChart data={performanceData}>
                  <CartesianGrid strokeDasharray="3 3" />
                  <XAxis dataKey="time" />
                  <YAxis />
                  <RechartsTooltip />
                  <Legend />
                  <Line type="monotone" dataKey="tasks" stroke="#3b82f6" name="总任务数" />
                  <Line type="monotone" dataKey="success" stroke="#10b981" name="成功" />
                  <Line type="monotone" dataKey="failed" stroke="#ef4444" name="失败" />
                </LineChart>
              </ResponsiveContainer>
            </Card>

            <Card className="p-6">
              <h3 className="mb-4">优先级分布</h3>
              <ResponsiveContainer width="100%" height={300}>
                <PieChart>
                  <Pie
                    data={priorityDistribution}
                    cx="50%"
                    cy="50%"
                    labelLine={false}
                    label={({ name, percent }) => `${name} ${(percent * 100).toFixed(0)}%`}
                    outerRadius={100}
                    fill="#8884d8"
                    dataKey="value"
                  >
                    {priorityDistribution.map((entry, index) => (
                      <Cell key={`cell-${index}`} fill={entry.color} />
                    ))}
                  </Pie>
                  <RechartsTooltip />
                </PieChart>
              </ResponsiveContainer>
            </Card>
          </div>

          {/* 正在执行的任务 */}
          <Card className="p-6">
            <div className="flex items-center justify-between mb-4">
              <h3>正在执行的任务</h3>
              <Badge variant="outline">{runningTasks.length} 个任务</Badge>
            </div>
            <div className="space-y-3">
              {runningTasks.map((task) => (
                <Card key={task.id} className="p-4 bg-blue-50 border-blue-200">
                  <div className="flex items-start justify-between">
                    <div className="flex-1">
                      <div className="flex items-center gap-2 mb-2">
                        <Activity className="w-4 h-4 text-blue-600 animate-pulse" />
                        <span className="font-medium">{task.name}</span>
                        {getPriorityBadge(task.priority)}
                        <Badge variant="outline" className="text-xs">{task.taskNo}</Badge>
                      </div>
                      <div className="grid grid-cols-3 gap-4 text-sm text-muted-foreground mb-3">
                        <div>
                          <span className="text-xs">开始时间：</span>
                          {task.actualStartTime}
                        </div>
                        <div>
                          <span className="text-xs">已执行：</span>
                          {task.executionTime}秒
                        </div>
                        <div>
                          <span className="text-xs">触发方式：</span>
                          {getTriggerTypeLabel(task.triggerType)}
                        </div>
                      </div>
                      <Progress value={(task.executionTime || 0) % 100} className="h-2" />
                    </div>
                    <div className="flex gap-2 ml-4">
                      <Button size="sm" variant="outline" onClick={() => handleViewTaskDetail(task)}>
                        <Eye className="w-4 h-4" />
                      </Button>
                      <Button size="sm" variant="outline" onClick={() => handlePauseTask(task.id)}>
                        <Pause className="w-4 h-4" />
                      </Button>
                      <Button size="sm" variant="outline" onClick={() => handleCancelTask(task.id)}>
                        <StopCircle className="w-4 h-4" />
                      </Button>
                    </div>
                  </div>
                </Card>
              ))}
            </div>
          </Card>
        </TabsContent>

        {/* 调度规则 */}
        <TabsContent value="rules" className="space-y-4">
          <Card className="p-6">
            <div className="flex items-center justify-between mb-4">
              <h3>调度规则管理</h3>
              <div className="flex gap-2">
                <Button onClick={handleOpenCreateTask} className="bg-green-600 hover:bg-green-700">
                  <PlayCircle className="w-4 h-4 mr-2" />
                  新增调度任务
                </Button>
                <Button onClick={handleCreateRule} variant="outline">
                  <Zap className="w-4 h-4 mr-2" />
                  新建规则
                </Button>
              </div>
            </div>

            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead>规则名称</TableHead>
                  <TableHead>应用</TableHead>
                  <TableHead>触发类型</TableHead>
                  <TableHead>优先级</TableHead>
                  <TableHead>状态</TableHead>
                  <TableHead>成功率</TableHead>
                  <TableHead>下次执行</TableHead>
                  <TableHead>操作</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {scheduleRules.map((rule) => (
                  <TableRow key={rule.id}>
                    <TableCell>
                      <div className="font-medium">{rule.name}</div>
                      <div className="text-xs text-muted-foreground">{rule.description}</div>
                    </TableCell>
                    <TableCell>{rule.applicationName}</TableCell>
                    <TableCell>
                      <Badge variant="outline">{getTriggerTypeLabel(rule.triggerType)}</Badge>
                    </TableCell>
                    <TableCell>{getPriorityBadge(rule.priority)}</TableCell>
                    <TableCell>
                      <div className="flex items-center gap-2">
                        <Switch
                          checked={rule.enabled}
                          onCheckedChange={() => handleToggleRule(rule.id)}
                        />
                        <span className="text-sm">{rule.enabled ? '已启用' : '已禁用'}</span>
                      </div>
                    </TableCell>
                    <TableCell>
                      {rule.totalRuns > 0 ? (
                        <div>
                          <div className="font-medium">
                            {((rule.successRuns / rule.totalRuns) * 100).toFixed(1)}%
                          </div>
                          <div className="text-xs text-muted-foreground">
                            {rule.successRuns}/{rule.totalRuns}
                          </div>
                        </div>
                      ) : (
                        <span className="text-muted-foreground">-</span>
                      )}
                    </TableCell>
                    <TableCell>
                      {rule.nextTriggerAt ? (
                        <div className="text-sm">{rule.nextTriggerAt}</div>
                      ) : (
                        <span className="text-muted-foreground">-</span>
                      )}
                    </TableCell>
                    <TableCell>
                      <div className="flex gap-2">
                        <Button
                          size="sm"
                          variant="outline"
                          onClick={() => handleManualTrigger(rule.id)}
                        >
                          <Play className="w-4 h-4" />
                        </Button>
                        <Button
                          size="sm"
                          variant="outline"
                          onClick={() => handleEditRule(rule)}
                        >
                          <Settings className="w-4 h-4" />
                        </Button>
                        <Button
                          size="sm"
                          variant="outline"
                          onClick={() => handleDeleteRule(rule.id)}
                        >
                          <Trash2 className="w-4 h-4" />
                        </Button>
                      </div>
                    </TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>
          </Card>
        </TabsContent>

        {/* 任务队列 */}
        <TabsContent value="queue" className="space-y-4">
          <div className="grid grid-cols-2 gap-6">
            {/* 等待队列 */}
            <Card className="p-6">
              <div className="flex items-center justify-between mb-4">
                <h3>等待队列</h3>
                <Badge variant="outline">{waitingTasks.length} 个任务</Badge>
              </div>
              <div className="space-y-3">
                {waitingTasks.map((task) => (
                  <Card key={task.id} className="p-4 hover:shadow-md transition-shadow">
                    <div className="flex items-start justify-between">
                      <div className="flex-1">
                        <div className="flex items-center gap-2 mb-2">
                          <Clock className="w-4 h-4 text-gray-500" />
                          <span className="font-medium">{task.name}</span>
                          {getPriorityBadge(task.priority)}
                        </div>
                        <div className="text-xs text-muted-foreground mb-1">
                          任务编号: {task.taskNo}
                        </div>
                        <div className="text-xs text-muted-foreground">
                          计划执行: {task.scheduledTime}
                        </div>
                      </div>
                      <div className="flex gap-2">
                        <Button
                          size="sm"
                          variant="outline"
                          onClick={() => handleViewTaskDetail(task)}
                        >
                          <Eye className="w-4 h-4" />
                        </Button>
                        <Button
                          size="sm"
                          variant="outline"
                          onClick={() => handleCancelTask(task.id)}
                        >
                          <XCircle className="w-4 h-4" />
                        </Button>
                      </div>
                    </div>
                  </Card>
                ))}
              </div>
            </Card>

            {/* 失败任务 */}
            <Card className="p-6">
              <div className="flex items-center justify-between mb-4">
                <h3>失败任务</h3>
                <Badge variant="destructive">{queueStats.failed} 个任务</Badge>
              </div>
              <div className="space-y-3">
                {executionLogs
                  .filter((log) => log.status === 'failed')
                  .map((log) => (
                    <Card key={log.id} className="p-4 bg-red-50 border-red-200">
                      <div className="flex items-start justify-between">
                        <div className="flex-1">
                          <div className="flex items-center gap-2 mb-2">
                            <AlertCircle className="w-4 h-4 text-red-600" />
                            <span className="font-medium">{log.applicationName}</span>
                            <Badge variant="destructive" className="text-xs">
                              重试 {log.retryCount} 次
                            </Badge>
                          </div>
                          <div className="text-xs text-muted-foreground mb-1">
                            任务编号: {log.taskNo}
                          </div>
                          <div className="text-xs text-red-600 mb-2">
                            错误: {log.errorMessage}
                          </div>
                          <div className="text-xs text-muted-foreground">
                            失败时间: {log.endTime}
                          </div>
                        </div>
                        <Button
                          size="sm"
                          variant="outline"
                          onClick={() => handleRetryTask(log.taskId)}
                        >
                          <RotateCcw className="w-4 h-4" />
                        </Button>
                      </div>
                    </Card>
                  ))}
              </div>
            </Card>
          </div>
        </TabsContent>

        {/* 执行日志 */}
        <TabsContent value="logs" className="space-y-4">
          <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">
                  <Filter className="w-4 h-4 mr-2" />
                  筛选
                </Button>
                <Button variant="outline" size="sm">
                  <Download className="w-4 h-4 mr-2" />
                  导出
                </Button>
              </div>
            </div>

            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead>任务编号</TableHead>
                  <TableHead>应用名称</TableHead>
                  <TableHead>开始时间</TableHead>
                  <TableHead>结束时间</TableHead>
                  <TableHead>执行时长</TableHead>
                  <TableHead>状态</TableHead>
                  <TableHead>资源使用</TableHead>
                  <TableHead>操作</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {executionLogs.map((log) => (
                  <TableRow key={log.id}>
                    <TableCell>
                      <div className="font-mono text-sm">{log.taskNo}</div>
                    </TableCell>
                    <TableCell>{log.applicationName}</TableCell>
                    <TableCell>{log.startTime}</TableCell>
                    <TableCell>{log.endTime || '-'}</TableCell>
                    <TableCell>
                      {log.executionTime ? `${log.executionTime}秒` : '-'}
                    </TableCell>
                    <TableCell>{getStatusBadge(log.status)}</TableCell>
                    <TableCell>
                      {log.cpuUsage && log.memoryUsage ? (
                        <div className="text-xs">
                          <div>CPU: {log.cpuUsage}%</div>
                          <div>内存: {log.memoryUsage}MB</div>
                        </div>
                      ) : (
                        '-'
                      )}
                    </TableCell>
                    <TableCell>
                      <Button
                        size="sm"
                        variant="outline"
                        onClick={() => {
                          setSelectedTask(log as any);
                          setShowLogDialog(true);
                        }}
                      >
                        <Eye className="w-4 h-4" />
                      </Button>
                    </TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>
          </Card>
        </TabsContent>
      </Tabs>

      {/* 规则编辑对话框 */}
      <Dialog open={showRuleDialog} onOpenChange={setShowRuleDialog}>
        <DialogContent className="max-w-3xl">
          <DialogHeader>
            <DialogTitle>{selectedRule ? '编辑调度规则' : '新建调度规则'}</DialogTitle>
            <DialogDescription>
              配置任务的触发条件、执行策略和重试机制
            </DialogDescription>
          </DialogHeader>

          <div className="space-y-4">
            <div className="grid grid-cols-2 gap-4">
              <div>
                <Label>规则名称</Label>
                <Input
                  value={editingRule.name || ''}
                  onChange={(e) =>
                    setEditingRule({ ...editingRule, name: e.target.value })
                  }
                  placeholder="输入规则名称"
                />
              </div>
              <div>
                <Label>关联应用</Label>
                <Select
                  value={editingRule.applicationId || ''}
                  onValueChange={(value) =>
                    setEditingRule({ ...editingRule, applicationId: value })
                  }
                >
                  <SelectTrigger>
                    <SelectValue placeholder="选择应用" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="app-1">智能灌溉策略生成</SelectItem>
                    <SelectItem value="app-2">病虫害智能预警</SelectItem>
                    <SelectItem value="app-3">精准施肥推荐</SelectItem>
                    <SelectItem value="app-4">作物产量预测</SelectItem>
                    <SelectItem value="app-5">气象灾害预警</SelectItem>
                  </SelectContent>
                </Select>
              </div>
            </div>

            <div>
              <Label>规则描述</Label>
              <Textarea
                value={editingRule.description || ''}
                onChange={(e) =>
                  setEditingRule({ ...editingRule, description: e.target.value })
                }
                placeholder="描述规则的用途和触发条件"
                rows={2}
              />
            </div>

            <div className="grid grid-cols-2 gap-4">
              <div>
                <Label>触发类型</Label>
                <Select
                  value={editingRule.triggerType || 'cron'}
                  onValueChange={(value) =>
                    setEditingRule({ ...editingRule, triggerType: value as TriggerType })
                  }
                >
                  <SelectTrigger>
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="cron">Cron定时</SelectItem>
                    <SelectItem value="interval">周期间隔</SelectItem>
                    <SelectItem value="event">事件触发</SelectItem>
                    <SelectItem value="threshold">阈值触发</SelectItem>
                    <SelectItem value="manual">手动触发</SelectItem>
                  </SelectContent>
                </Select>
              </div>
              <div>
                <Label>优先级</Label>
                <Select
                  value={editingRule.priority || 'medium'}
                  onValueChange={(value) =>
                    setEditingRule({ ...editingRule, priority: value as Priority })
                  }
                >
                  <SelectTrigger>
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="critical">紧急</SelectItem>
                    <SelectItem value="high">高</SelectItem>
                    <SelectItem value="medium">中</SelectItem>
                    <SelectItem value="low">低</SelectItem>
                  </SelectContent>
                </Select>
              </div>
            </div>

            <div className="grid grid-cols-3 gap-4">
              <div>
                <Label>最大重试次数</Label>
                <Input
                  type="number"
                  value={editingRule.maxRetry || 3}
                  onChange={(e) =>
                    setEditingRule({ ...editingRule, maxRetry: parseInt(e.target.value) })
                  }
                />
              </div>
              <div>
                <Label>重试策略</Label>
                <Select
                  value={editingRule.retryStrategy || 'exponential'}
                  onValueChange={(value) =>
                    setEditingRule({
                      ...editingRule,
                      retryStrategy: value as RetryStrategy,
                    })
                  }
                >
                  <SelectTrigger>
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="immediate">立即重试</SelectItem>
                    <SelectItem value="exponential">指数退避</SelectItem>
                    <SelectItem value="fixed">固定间隔</SelectItem>
                    <SelectItem value="none">不重试</SelectItem>
                  </SelectContent>
                </Select>
              </div>
              <div>
                <Label>超时时间(秒)</Label>
                <Input
                  type="number"
                  value={editingRule.timeout || 300}
                  onChange={(e) =>
                    setEditingRule({ ...editingRule, timeout: parseInt(e.target.value) })
                  }
                />
              </div>
            </div>

            <div className="flex items-center gap-4">
              <div className="flex items-center gap-2">
                <Switch
                  checked={editingRule.concurrent || false}
                  onCheckedChange={(checked) =>
                    setEditingRule({ ...editingRule, concurrent: checked })
                  }
                />
                <Label>允许并发执行</Label>
              </div>
              {editingRule.concurrent && (
                <div className="flex-1">
                  <Label>最大并发数</Label>
                  <Input
                    type="number"
                    value={editingRule.maxConcurrent || 1}
                    onChange={(e) =>
                      setEditingRule({
                        ...editingRule,
                        maxConcurrent: parseInt(e.target.value),
                      })
                    }
                  />
                </div>
              )}
            </div>
          </div>

          <DialogFooter>
            <Button variant="outline" onClick={() => setShowRuleDialog(false)}>
              取消
            </Button>
            <Button onClick={handleSaveRule} className="bg-blue-600 hover:bg-blue-700">
              保存
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* 日志详情对话框 */}
      <Dialog open={showLogDialog} onOpenChange={setShowLogDialog}>
        <DialogContent className="max-w-2xl">
          <DialogHeader>
            <DialogTitle>执行日志详情</DialogTitle>
            <DialogDescription>查看任务执行的详细信息</DialogDescription>
          </DialogHeader>

          {selectedTask && (
            <div className="space-y-4">
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <Label>任务编号</Label>
                  <div className="field-value font-mono">{(selectedTask as any).taskNo}</div>
                </div>
                <div>
                  <Label>应用名称</Label>
                  <div className="field-value">{(selectedTask as any).applicationName}</div>
                </div>
                <div>
                  <Label>开始时间</Label>
                  <div className="field-value">{(selectedTask as any).startTime}</div>
                </div>
                <div>
                  <Label>结束时间</Label>
                  <div className="field-value">{(selectedTask as any).endTime || '-'}</div>
                </div>
                <div>
                  <Label>执行时长</Label>
                  <div className="field-value">
                    {(selectedTask as any).executionTime
                      ? `${(selectedTask as any).executionTime}秒`
                      : '-'}
                  </div>
                </div>
                <div>
                  <Label>执行状态</Label>
                  <div className="field-value">
                    {getStatusBadge((selectedTask as any).status)}
                  </div>
                </div>
              </div>

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

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

      {/* 新增调度任务对话框 */}
      <Dialog open={showCreateTaskDialog} onOpenChange={setShowCreateTaskDialog}>
        <DialogContent className="max-w-4xl max-h-[90vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle className="flex items-center gap-2">
              <PlayCircle className="w-5 h-5 text-green-600" />
              新增调度任务
            </DialogTitle>
            <DialogDescription>
              创建自动化调度任务，配置输入数据源和执行策略
            </DialogDescription>
          </DialogHeader>

          <div className="space-y-6">
            {/* 基本信息 */}
            <Card className="p-4 bg-blue-50 border-blue-200">
              <div className="flex items-center gap-2 text-blue-900">
                <FileText className="w-4 h-4" />
                <span className="text-sm">任务基本信息</span>
              </div>
            </Card>

            <div className="grid grid-cols-2 gap-4">
              <div>
                <Label>任务名称 *</Label>
                <Input
                  placeholder="请输入任务名称，如：每日土壤检测任务"
                  value={newTaskData.name}
                  onChange={(e) => setNewTaskData({ ...newTaskData, name: e.target.value })}
                />
              </div>
              <div>
                <Label>优先级 *</Label>
                <Select
                  value={newTaskData.priority}
                  onValueChange={(value) =>
                    setNewTaskData({ ...newTaskData, priority: value as Priority })
                  }
                >
                  <SelectTrigger>
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="critical">紧急</SelectItem>
                    <SelectItem value="high">高</SelectItem>
                    <SelectItem value="medium">中</SelectItem>
                    <SelectItem value="low">低</SelectItem>
                  </SelectContent>
                </Select>
              </div>
            </div>

            {/* 选择应用 */}
            <Card className="p-4 bg-purple-50 border-purple-200">
              <div className="flex items-center gap-2 text-purple-900">
                <Cpu className="w-4 h-4" />
                <span className="text-sm">选择应用</span>
              </div>
            </Card>

            <div>
              <Label>关联应用 *</Label>
              <Select
                value={newTaskData.applicationId}
                onValueChange={(value) => {
                  setNewTaskData({
                    ...newTaskData,
                    applicationId: value,
                    inputDataSources: {},
                  });
                }}
              >
                <SelectTrigger>
                  <SelectValue placeholder="请选择要调度的应用" />
                </SelectTrigger>
                <SelectContent>
                  {availableApplications.map((app) => (
                    <SelectItem key={app.id} value={app.id}>
                      {app.name}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>

            {/* 配置输入参数数据源 */}
            {newTaskData.applicationId && (
              <>
                <Card className="p-4 bg-green-50 border-green-200">
                  <div className="flex items-center gap-2 text-green-900">
                    <Database className="w-4 h-4" />
                    <span className="text-sm">配置输入参数数据源</span>
                  </div>
                </Card>

                <div className="space-y-3">
                  {availableApplications
                    .find((app) => app.id === newTaskData.applicationId)
                    ?.inputFields.map((field) => (
                      <div key={field} className="grid grid-cols-2 gap-4 items-center">
                        <div>
                          <Label>{field} *</Label>
                          <div className="field-value-inline text-sm">{field}</div>
                        </div>
                        <div>
                          <Select
                            value={newTaskData.inputDataSources[field] || ''}
                            onValueChange={(value) =>
                              setNewTaskData({
                                ...newTaskData,
                                inputDataSources: {
                                  ...newTaskData.inputDataSources,
                                  [field]: value,
                                },
                              })
                            }
                          >
                            <SelectTrigger>
                              <SelectValue placeholder="选择数据源" />
                            </SelectTrigger>
                            <SelectContent>
                              {dataSourceOptions.map((source) => (
                                <SelectItem key={source} value={source}>
                                  {source}
                                </SelectItem>
                              ))}
                            </SelectContent>
                          </Select>
                        </div>
                      </div>
                    ))}
                </div>
              </>
            )}

            {/* 时间策略 */}
            <Card className="p-4 bg-orange-50 border-orange-200">
              <div className="flex items-center gap-2 text-orange-900">
                <Clock className="w-4 h-4" />
                <span className="text-sm">时间策略</span>
              </div>
            </Card>

            <div>
              <Label>执行策略 *</Label>
              <Select
                value={newTaskData.timeStrategy}
                onValueChange={(value) =>
                  setNewTaskData({
                    ...newTaskData,
                    timeStrategy: value as 'cron' | 'interval' | 'daily',
                  })
                }
              >
                <SelectTrigger>
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="daily">每天定时</SelectItem>
                  <SelectItem value="interval">周期执行</SelectItem>
                  <SelectItem value="cron">Cron表达式</SelectItem>
                </SelectContent>
              </Select>
            </div>

            {newTaskData.timeStrategy === 'daily' && (
              <div>
                <Label>执行时间</Label>
                <Input
                  type="time"
                  value={newTaskData.dailyTime}
                  onChange={(e) =>
                    setNewTaskData({ ...newTaskData, dailyTime: e.target.value })
                  }
                />
                <p className="text-xs text-muted-foreground mt-1">
                  每天在指定时间执行任务
                </p>
              </div>
            )}

            {newTaskData.timeStrategy === 'interval' && (
              <div>
                <Label>执行间隔（分钟）</Label>
                <Input
                  type="number"
                  min="1"
                  value={newTaskData.intervalMinutes}
                  onChange={(e) =>
                    setNewTaskData({
                      ...newTaskData,
                      intervalMinutes: parseInt(e.target.value) || 60,
                    })
                  }
                />
                <p className="text-xs text-muted-foreground mt-1">
                  每隔指定分钟数执行一次任务
                </p>
              </div>
            )}

            {newTaskData.timeStrategy === 'cron' && (
              <div>
                <Label>Cron表达式</Label>
                <Input
                  placeholder="例如：0 8 * * * (每天8点)"
                  value={newTaskData.cronExpression}
                  onChange={(e) =>
                    setNewTaskData({ ...newTaskData, cronExpression: e.target.value })
                  }
                />
                <p className="text-xs text-muted-foreground mt-1">
                  使用标准Cron表达式格式
                </p>
              </div>
            )}

            {/* 手动执行提示 */}
            <Card className="p-4 bg-yellow-50 border-yellow-300">
              <div className="flex items-center gap-2 text-yellow-800">
                <AlertTriangle className="w-4 h-4" />
                <span className="text-sm">
                  保存后可以通过"手动触发"按钮立即执行任务，无需等待定时调度
                </span>
              </div>
            </Card>
          </div>

          <DialogFooter>
            <div className="flex gap-2 w-full justify-between">
              <Button
                variant="outline"
                onClick={handleManualExecute}
                disabled={!newTaskData.applicationId || !newTaskData.name}
              >
                <Zap className="w-4 h-4 mr-2" />
                手动执行
              </Button>
              <div className="flex gap-2">
                <Button variant="outline" onClick={() => setShowCreateTaskDialog(false)}>
                  取消
                </Button>
                <Button
                  onClick={handleSaveTask}
                  className="bg-green-600 hover:bg-green-700"
                >
                  <CheckCircle className="w-4 h-4 mr-2" />
                  保存任务
                </Button>
              </div>
            </div>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* 任务详情对话框（包含执行状态监控） */}
      <Dialog open={showTaskDetailDialog} onOpenChange={setShowTaskDetailDialog}>
        <DialogContent className="max-w-5xl max-h-[90vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle className="flex items-center gap-2">
              <Eye className="w-5 h-5 text-blue-600" />
              任务执行详情
            </DialogTitle>
            <DialogDescription>
              查看任务的详细信息和执行状态监控
            </DialogDescription>
          </DialogHeader>

          {selectedTask && (
            <div className="space-y-6">
              {/* 任务基本信息 */}
              <Card className="p-4 bg-gradient-to-r from-blue-50 to-cyan-50 border-blue-200">
                <div className="grid grid-cols-4 gap-4">
                  <div>
                    <div className="text-xs text-muted-foreground mb-1">任务编号</div>
                    <div className="font-mono text-sm">{selectedTask.taskNo}</div>
                  </div>
                  <div>
                    <div className="text-xs text-muted-foreground mb-1">任务名称</div>
                    <div className="text-sm font-medium">{selectedTask.name}</div>
                  </div>
                  <div>
                    <div className="text-xs text-muted-foreground mb-1">应用</div>
                    <div className="text-sm">{selectedTask.applicationName}</div>
                  </div>
                  <div>
                    <div className="text-xs text-muted-foreground mb-1">优先级</div>
                    <div>{getPriorityBadge(selectedTask.priority)}</div>
                  </div>
                </div>
              </Card>

              {/* 执行状态监控 */}
              <div>
                <h4 className="mb-4 flex items-center gap-2">
                  <Activity className="w-5 h-5 text-green-600" />
                  执行状态监控
                </h4>

                <div className="grid grid-cols-3 gap-4 mb-6">
                  <Card className="p-4">
                    <div className="flex items-center justify-between mb-2">
                      <div className="text-sm text-muted-foreground">当前状态</div>
                      <CircleDot
                        className={`w-5 h-5 ${
                          selectedTask.status === 'running'
                            ? 'text-blue-500 animate-pulse'
                            : selectedTask.status === 'completed'
                            ? 'text-green-500'
                            : selectedTask.status === 'failed'
                            ? 'text-red-500'
                            : 'text-gray-500'
                        }`}
                      />
                    </div>
                    <div className="text-2xl mb-1">
                      {getStatusBadge(selectedTask.status)}
                    </div>
                  </Card>

                  <Card className="p-4">
                    <div className="flex items-center justify-between mb-2">
                      <div className="text-sm text-muted-foreground">执行时长</div>
                      <Timer className="w-5 h-5 text-blue-500" />
                    </div>
                    <div className="text-2xl mb-1">
                      {selectedTask.executionTime || 0}
                      <span className="text-sm text-muted-foreground ml-1">秒</span>
                    </div>
                  </Card>

                  <Card className="p-4">
                    <div className="flex items-center justify-between mb-2">
                      <div className="text-sm text-muted-foreground">重试次数</div>
                      <RotateCcw className="w-5 h-5 text-orange-500" />
                    </div>
                    <div className="text-2xl mb-1">
                      {selectedTask.retryCount}
                      <span className="text-sm text-muted-foreground ml-1">
                        / {selectedTask.maxRetry}
                      </span>
                    </div>
                  </Card>
                </div>

                {/* 执行进度 */}
                {selectedTask.status === 'running' && (
                  <Card className="p-4 bg-blue-50 border-blue-200">
                    <div className="flex items-center justify-between mb-2">
                      <span className="text-sm">执行进度</span>
                      <span className="text-sm text-blue-600">
                        {Math.min((selectedTask.executionTime || 0) % 100, 100)}%
                      </span>
                    </div>
                    <Progress
                      value={Math.min((selectedTask.executionTime || 0) % 100, 100)}
                      className="h-2"
                    />
                  </Card>
                )}
              </div>

              {/* 时间信息 */}
              <div>
                <h4 className="mb-4 flex items-center gap-2">
                  <Clock className="w-5 h-5 text-purple-600" />
                  时间信息
                </h4>

                <div className="grid grid-cols-2 gap-4">
                  <Card className="p-4">
                    <Label>计划执行时间</Label>
                    <div className="field-value-inline mt-2">{selectedTask.scheduledTime}</div>
                  </Card>
                  <Card className="p-4">
                    <Label>实际开始时间</Label>
                    <div className="field-value-inline mt-2">
                      {selectedTask.actualStartTime || '-'}
                    </div>
                  </Card>
                  <Card className="p-4">
                    <Label>实际结束时间</Label>
                    <div className="field-value-inline mt-2">
                      {selectedTask.actualEndTime || '-'}
                    </div>
                  </Card>
                  <Card className="p-4">
                    <Label>触发方式</Label>
                    <div className="field-value-inline mt-2">
                      <Badge variant="outline">{getTriggerTypeLabel(selectedTask.triggerType)}</Badge>
                    </div>
                  </Card>
                </div>
              </div>

              {/* 执行结果 */}
              <div>
                <h4 className="mb-4 flex items-center gap-2">
                  <BarChart3 className="w-5 h-5 text-cyan-600" />
                  执行结果
                </h4>

                <Card className="p-4">
                  {selectedTask.status === 'completed' && selectedTask.result && (
                    <div className="text-sm">
                      <div className="font-medium text-green-600 mb-2">✓ 执行成功</div>
                      <div className="whitespace-pre-wrap">{selectedTask.result}</div>
                    </div>
                  )}
                  {selectedTask.status === 'failed' && selectedTask.errorMessage && (
                    <div className="text-sm">
                      <div className="font-medium text-red-600 mb-2">✗ 执行失败</div>
                      <div className="text-red-600">{selectedTask.errorMessage}</div>
                    </div>
                  )}
                  {selectedTask.status === 'running' && (
                    <div className="text-sm text-blue-600 flex items-center gap-2">
                      <Activity className="w-4 h-4 animate-pulse" />
                      任务正在执行中，请等待...
                    </div>
                  )}
                  {selectedTask.status === 'waiting' && (
                    <div className="text-sm text-gray-600 flex items-center gap-2">
                      <Clock className="w-4 h-4" />
                      任务等待执行中...
                    </div>
                  )}
                </Card>
              </div>

              {/* 操作按钮 */}
              {selectedTask.status === 'running' && (
                <Card className="p-4 bg-yellow-50 border-yellow-300">
                  <div className="flex items-center justify-between">
                    <div className="flex items-center gap-2">
                      <AlertTriangle className="w-4 h-4 text-yellow-600" />
                      <span className="text-sm text-yellow-800">任务正在执行</span>
                    </div>
                    <div className="flex gap-2">
                      <Button
                        size="sm"
                        variant="outline"
                        onClick={() => handlePauseTask(selectedTask.id)}
                      >
                        <Pause className="w-4 h-4 mr-1" />
                        暂停
                      </Button>
                      <Button
                        size="sm"
                        variant="outline"
                        onClick={() => handleCancelTask(selectedTask.id)}
                      >
                        <StopCircle className="w-4 h-4 mr-1" />
                        取消
                      </Button>
                    </div>
                  </div>
                </Card>
              )}

              {selectedTask.status === 'failed' && (
                <Card className="p-4 bg-red-50 border-red-300">
                  <div className="flex items-center justify-between">
                    <div className="flex items-center gap-2">
                      <XCircle className="w-4 h-4 text-red-600" />
                      <span className="text-sm text-red-800">任务执行失败</span>
                    </div>
                    <Button
                      size="sm"
                      variant="outline"
                      onClick={() => handleRetryTask(selectedTask.id)}
                    >
                      <RotateCcw className="w-4 h-4 mr-1" />
                      重新执行
                    </Button>
                  </div>
                </Card>
              )}
            </div>
          )}

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