/**
 * 增强版Operation-Agent管理界面 - 性能优化版本
 * 
 * 性能优化措施：
 * 1. 使用 React.memo 优化组件渲染
 * 2. 使用 useMemo 缓存计算结果
 * 3. 使用 useCallback 缓存回调函数
 * 4. 使用虚拟滚动优化长列表
 * 5. 减少不必要的重新渲染
 * 6. 优化状态更新
 */

import {
  useState,
  useEffect,
  useCallback,
  useMemo,
  memo,
  Card,
  Row,
  Col,
  Statistic,
  Table,
  Button,
  Modal,
  Form,
  Input,
  InputNumber,
  Select,
  Switch,
  Tabs,
  Tag,
  message,
  Space,
  Progress,
  Badge,
  Tooltip,
  Popconfirm,
  Timeline,
  Descriptions,
  Alert,
  List,
  Avatar,
  Drawer,
  Result,
  Empty,
  Typography,
  Collapse,
  Checkbox,
  PlayCircleOutlined,
  PauseCircleOutlined,
  PlusOutlined,
  SyncOutlined,
  EyeOutlined,
  DeleteOutlined,
  ReloadOutlined,
  CloudServerOutlined,
  ScheduleOutlined,
  SafetyCertificateOutlined,
  DesktopOutlined,
  GlobalOutlined,
  CloudDownloadOutlined,
  CheckCircleOutlined,
  CloseCircleOutlined,
  ExclamationCircleOutlined,
  InfoCircleOutlined,
  SettingOutlined,
  HistoryOutlined,
  FileTextOutlined,
  MonitorOutlined,
  ShopOutlined,
  ShoppingCartOutlined,
  DollarOutlined,
  UserOutlined,
  LockOutlined,
  UnlockOutlined,
  LinkOutlined,
  ClockCircleOutlined,
  Option,
  TabPane,
  Title,
  Text,
  Paragraph,
  FC,
} from '@/imports';
import { lightweightClientService } from '../services/lightweightClientService';
import { cloudService, CreateInstanceRequest, CloudInstance, CloudProvider, CloudRegion, InstanceType, CloudImage, InstanceMetrics } from '../services/cloud-service';
import { 
  CloudControlLayerService,
  ControlCommand,
  LayerStatus
} from '../services/cloud-control-layer';

interface ClientStatus {
  platform: string;
  version: string;
  uptime: number;
  platforms: {
    supported: string[];
    loggedIn: string[];
    total: number;
  };
  tasks: {
    total: number;
    enabled: number;
    disabled: number;
  };
  connections: {
    active: number;
    max: number;
    webSocket: number;
    http: string;
  };
  timestamp: number;
}

interface PlatformInfo {
  name: string;
  status: 'connected' | 'disconnected' | 'error';
  lastSync: string;
  orderCount: number;
  productCount: number;
  loginTime?: string;
  cookies?: boolean;
  proxy?: string;
}

interface TaskInfo {
  id: string;
  name: string;
  description?: string;
  platform: string;
  type: string;
  schedule: string;
  enabled: boolean;
  lastRun?: string;
  nextRun?: string;
  status: 'running' | 'success' | 'failed' | 'idle';
  progress?: number;
  result?: string;
  errorCount?: number;
  successCount?: number;
}

interface WebRemoteSession {
  id: string;
  platform: string;
  status: 'ready' | 'active' | 'error' | 'closed';
  currentUrl: string;
  title: string;
  lastActivity: string;
}

interface OperationLog {
  id: string;
  timestamp: string;
  level: 'info' | 'success' | 'warning' | 'error';
  operation: string;
  platform?: string;
  details: string;
  duration?: number;
}

interface PlatformLoginFormValues {
  platform: string;
  username: string;
  password: string;
  twoFactorCode?: string;
}

interface TaskFormValues {
  name: string;
  description?: string;
  platform: string;
  type: string;
  schedule: string;
}

interface CloudInstanceFormValues {
  name: string;
  provider: string;
  region: string;
  instanceType: string;
  imageId: string;
  systemDiskSize: number;
  dataDiskSize?: number;
  billingType: 'prepaid' | 'postpaid';
  period?: number;
  password?: string;
  keyPairName?: string;
}

interface WebRemoteFormValues {
  platform: string;
  url: string;
  userAgent?: string;
}

interface ClientInfo {
  id: string;
  name: string;
  ip: string;
  port: number;
  status: 'online' | 'offline' | 'connecting' | 'error';
  version: string;
  uptime: number;
  lastSeen: number;
  cpu: number;
  memory: number;
  disk: number;
  platform: string;
  tasks: number;
  platforms: number;
  region: string;
  group: string;
  tags: string[];
}

interface ClientGroup {
  id: string;
  name: string;
  description: string;
  clientIds: string[];
  color: string;
}

interface ClientStats {
  total: number;
  online: number;
  offline: number;
  error: number;
  groups: number;
  totalTasks: number;
  totalPlatforms: number;
}

const logLevelIcon = (level: string) => {
  switch (level) {
    case 'success': return <CheckCircleOutlined style={{ color: '#52c41a' }} />;
    case 'warning': return <ExclamationCircleOutlined style={{ color: '#faad14' }} />;
    case 'error': return <CloseCircleOutlined style={{ color: '#ff4d4f' }} />;
    default: return <InfoCircleOutlined style={{ color: '#1890ff' }} />;
  }
};

const statusColor = (status: string) => {
  const colorMap: Record<string, string> = {
    'connected': 'green',
    'disconnected': 'orange',
    'error': 'red',
    'running': 'blue',
    'success': 'green',
    'failed': 'red',
    'idle': 'default',
    'stopped': 'red',
    'starting': 'blue',
    'stopping': 'orange',
    'ready': 'blue',
    'active': 'green',
    'closed': 'default'
  };
  return colorMap[status] || 'default';
};

const OperationAgentEnhancedBase: FC = () => {
  const [clientStatus, setClientStatus] = useState<ClientStatus | null>(null);
  const [platforms, setPlatforms] = useState<PlatformInfo[]>([]);
  const [tasks, setTasks] = useState<TaskInfo[]>([]);
  const [cloudInstances, setCloudInstances] = useState<CloudInstance[]>([]);
  const [webSessions, setWebSessions] = useState<WebRemoteSession[]>([]);
  const [connected, setConnected] = useState(false);
  const [loading, setLoading] = useState(false);
  const [loginModalVisible, setLoginModalVisible] = useState(false);
  const [taskModalVisible, setTaskModalVisible] = useState(false);
  const [cloudModalVisible, setCloudModalVisible] = useState(false);
  const [webRemoteModalVisible, setWebRemoteModalVisible] = useState(false);
  const [form] = Form.useForm();
  const [taskForm] = Form.useForm();
  const [cloudForm] = Form.useForm();
  const [webRemoteForm] = Form.useForm();
  const [instanceDetailModalVisible, setInstanceDetailModalVisible] = useState(false);
  const [selectedInstance, setSelectedInstance] = useState<CloudInstance | null>(null);
  const [instanceMetrics, setInstanceMetrics] = useState<InstanceMetrics | null>(null);
  const [providers, setProviders] = useState<CloudProvider[]>([]);
  const [regions, setRegions] = useState<CloudRegion[]>([]);
  const [instanceTypes, setInstanceTypes] = useState<InstanceType[]>([]);
  const [images, setImages] = useState<CloudImage[]>([]);
  const [estimatedPrice, setEstimatedPrice] = useState<number>(0);
  const [operationLogs, setOperationLogs] = useState<OperationLog[]>([]);
  const [layerStatus, setLayerStatus] = useState<LayerStatus[]>([]);
  const [configDrawerVisible, setConfigDrawerVisible] = useState(false);
  const [taskDetailDrawerVisible, setTaskDetailDrawerVisible] = useState(false);
  const [selectedTask, setSelectedTask] = useState<TaskInfo | null>(null);
  
  // 多客户端管理状态
  const [clients, setClients] = useState<ClientInfo[]>([]);
  const [clientGroups, setClientGroups] = useState<ClientGroup[]>([]);
  const [clientStats, setClientStats] = useState<ClientStats>({
    total: 0,
    online: 0,
    offline: 0,
    error: 0,
    groups: 0,
    totalTasks: 0,
    totalPlatforms: 0
  });
  const [selectedClient, setSelectedClient] = useState<ClientInfo | null>(null);
  const [clientDetailDrawerVisible, setClientDetailDrawerVisible] = useState(false);
  const [clientGroupModalVisible, setClientGroupModalVisible] = useState(false);
  const [selectedGroup, setSelectedGroup] = useState<ClientGroup | null>(null);
  const [clientForm] = Form.useForm();
  const [groupForm] = Form.useForm();
  const [selectedClientIds, setSelectedClientIds] = useState<string[]>([]);
  const [isSelectAll, setIsSelectAll] = useState(false);

  const addOperationLog = useCallback((level: OperationLog['level'], operation: string, details: string, platform?: string, duration?: number) => {
    const newLog: OperationLog = {
      id: `log-${Date.now()}`,
      timestamp: new Date().toLocaleString(),
      level,
      operation,
      platform,
      details,
      duration
    };
    setOperationLogs(prev => [newLog, ...prev].slice(0, 100));
  }, []);

  const connectToClient = useCallback(async () => {
    setLoading(true);
    try {
      await lightweightClientService.connectToClient('localhost', 8080);
      setConnected(true);
      message.success('客户端连接成功');
      addOperationLog('success', '客户端连接', '成功连接到本地客户端');
      await loadClientStatus();
    } catch (error) {
      message.error('客户端连接失败');
      addOperationLog('error', '客户端连接', `连接失败: ${error}`);
    } finally {
      setLoading(false);
    }
  }, [addOperationLog]);

  const loadClientStatus = useCallback(async () => {
    if (!connected) return;
    
    try {
      const mockStatus: ClientStatus = {
        platform: 'windows',
        version: '2.0.0',
        uptime: 3600,
        platforms: {
          supported: ['tiktok', 'shopee', 'amazon', 'temu', 'lazada'],
          loggedIn: ['tiktok', 'shopee'],
          total: 5
        },
        tasks: {
          total: 8,
          enabled: 5,
          disabled: 3
        },
        connections: {
          active: 2,
          max: 10,
          webSocket: 1,
          http: 'active'
        },
        timestamp: Date.now()
      };
      
      setClientStatus(mockStatus);
      
      const mockPlatforms: PlatformInfo[] = [
        { name: 'TikTok', status: 'connected', lastSync: '2024-01-20 10:30:00', orderCount: 156, productCount: 89, loginTime: '2024-01-20 08:00:00', cookies: true, proxy: 'socks5://proxy1.example.com:1080' },
        { name: 'Shopee', status: 'connected', lastSync: '2024-01-20 10:25:00', orderCount: 234, productCount: 167, loginTime: '2024-01-20 08:15:00', cookies: true, proxy: 'socks5://proxy2.example.com:1080' },
        { name: 'Amazon', status: 'disconnected', lastSync: '2024-01-19 15:20:00', orderCount: 89, productCount: 45, cookies: false },
        { name: 'Temu', status: 'disconnected', lastSync: '2024-01-18 09:15:00', orderCount: 0, productCount: 0, cookies: false },
        { name: 'Lazada', status: 'error', lastSync: '2024-01-17 14:30:00', orderCount: 12, productCount: 8, cookies: true }
      ];
      
      setPlatforms(mockPlatforms);
      
      const mockTasks: TaskInfo[] = [
        { id: '1', name: '每日订单同步', description: '每天凌晨同步所有平台订单', platform: 'all', type: 'sync', schedule: '0 2 * * *', enabled: true, lastRun: '2024-01-20 02:00:00', nextRun: '2024-01-21 02:00:00', status: 'success', progress: 100, successCount: 156, errorCount: 0 },
        { id: '2', name: '价格监控', description: '监控商品价格变化', platform: 'all', type: 'monitor', schedule: '*/15 * * * *', enabled: true, lastRun: '2024-01-20 10:15:00', nextRun: '2024-01-20 10:30:00', status: 'running', progress: 45, successCount: 23, errorCount: 2 },
        { id: '3', name: '库存同步', description: '同步商品库存信息', platform: 'tiktok', type: 'sync', schedule: '0 */6 * * *', enabled: false, lastRun: '2024-01-19 18:00:00', nextRun: '2024-01-20 00:00:00', status: 'idle', progress: 0 },
        { id: '4', name: '商品上架', description: '自动上架采集的商品', platform: 'shopee', type: 'publish', schedule: '0 9 * * *', enabled: true, lastRun: '2024-01-20 09:00:00', nextRun: '2024-01-21 09:00:00', status: 'success', progress: 100, successCount: 15, errorCount: 1 },
        { id: '5', name: '评价监控', description: '监控商品评价变化', platform: 'amazon', type: 'monitor', schedule: '0 8,20 * * *', enabled: true, lastRun: '2024-01-20 08:00:00', nextRun: '2024-01-20 20:00:00', status: 'success', progress: 100, successCount: 45, errorCount: 0 },
        { id: '6', name: '竞品分析', description: '分析竞争对手价格和销量', platform: 'all', type: 'analysis', schedule: '0 3 * * 1', enabled: false, lastRun: '2024-01-15 03:00:00', nextRun: '2024-01-22 03:00:00', status: 'idle', progress: 0 },
        { id: '7', name: '广告优化', description: '自动优化广告出价', platform: 'tiktok', type: 'optimize', schedule: '*/30 * * * *', enabled: true, lastRun: '2024-01-20 10:00:00', nextRun: '2024-01-20 10:30:00', status: 'running', progress: 60, successCount: 8, errorCount: 0 },
        { id: '8', name: '财务对账', description: '每日财务数据对账', platform: 'all', type: 'finance', schedule: '0 4 * * *', enabled: true, lastRun: '2024-01-20 04:00:00', nextRun: '2024-01-21 04:00:00', status: 'success', progress: 100, successCount: 1, errorCount: 0 }
      ];
      
      setTasks(mockTasks);
      
      const mockCloudInstances: CloudInstance[] = [
        { id: 'i-1234567890abcdef0', name: 'TikTok-Proxy-01', provider: 'aliyun', region: 'cn-hangzhou', status: 'running', ipAddress: '47.100.100.100', instanceType: 'ecs.g6.large', createdTime: '2024-01-15 10:00:00', expiredTime: '2024-02-15 10:00:00' },
        { id: 'i-0987654321fedcba0', name: 'Shopee-Proxy-01', provider: 'tencent', region: 'ap-guangzhou', status: 'stopped', ipAddress: '118.100.100.100', instanceType: 'S2.SMALL1', createdTime: '2024-01-10 14:30:00' },
        { id: 'i-abcdef1234567890', name: 'Amazon-Proxy-01', provider: 'aliyun', region: 'us-west-1', status: 'running', ipAddress: '52.100.100.100', instanceType: 'ecs.g6.xlarge', createdTime: '2024-01-12 09:00:00', expiredTime: '2024-02-12 09:00:00' }
      ];
      
      setCloudInstances(mockCloudInstances);
      
      const mockWebSessions: WebRemoteSession[] = [
        { id: 'web-1234567890', platform: 'tiktok', status: 'active', currentUrl: 'https://seller.tiktok.com/orders', title: 'TikTok Seller Center - Orders', lastActivity: '2024-01-20 10:25:00' },
        { id: 'web-0987654321', platform: 'shopee', status: 'ready', currentUrl: 'https://seller.shopee.com', title: 'Shopee Seller Center', lastActivity: '2024-01-20 09:45:00' }
      ];
      
      setWebSessions(mockWebSessions);
      
      const mockLayerStatus: LayerStatus[] = [
        { layer: 'API模拟层', available: true, latency: 120, lastUsed: Date.now() - 300000, errorCount: 2, successRate: 0.98 },
        { layer: 'WEB远程控制层', available: true, latency: 350, lastUsed: Date.now() - 600000, errorCount: 5, successRate: 0.95 },
        { layer: '远程桌面层', available: false, latency: 0, lastUsed: 0, errorCount: 0, successRate: 0 },
        { layer: '云服务商API层', available: true, latency: 200, lastUsed: Date.now() - 900000, errorCount: 1, successRate: 0.99 }
      ];
      
      setLayerStatus(mockLayerStatus);
      
    } catch (error) {
      message.error('加载状态失败');
      addOperationLog('error', '状态加载', `加载失败: ${error}`);
    }
  }, [connected, addOperationLog]);

  const handlePlatformLogin = useCallback(async (values: PlatformLoginFormValues) => {
    try {
      addOperationLog('info', '平台登录', `开始登录 ${values.platform}`, values.platform);
      
      const command: ControlCommand = {
        type: 'api',
        target: values.platform,
        action: 'login',
        parameters: { username: values.username, password: values.password, twoFactorCode: values.twoFactorCode },
        priority: 'high'
      };
      
      const result = await CloudControlLayerService.executeCommand(command);
      
      if (result.success) {
        message.success(`${values.platform} 登录成功`);
        addOperationLog('success', '平台登录', `${values.platform} 登录成功`, values.platform, result.duration);
        setLoginModalVisible(false);
        form.resetFields();
        await loadClientStatus();
      } else {
        message.error(`登录失败: ${result.error}`);
        addOperationLog('error', '平台登录', `${values.platform} 登录失败: ${result.error}`, values.platform);
      }
    } catch (error) {
      message.error('登录失败');
      addOperationLog('error', '平台登录', `登录异常: ${error}`, values.platform);
    }
  }, [addOperationLog, form, loadClientStatus]);

  const handleAddTask = useCallback(async (values: TaskFormValues) => {
    try {
      addOperationLog('info', '任务创建', `创建任务: ${values.name}`, values.platform);
      
      const newTask: TaskInfo = {
        id: `task-${Date.now()}`,
        name: values.name,
        description: values.description,
        platform: values.platform,
        type: values.type,
        schedule: values.schedule,
        enabled: true,
        status: 'idle',
        progress: 0
      };
      
      setTasks(prev => [...prev, newTask]);
      message.success('任务添加成功');
      addOperationLog('success', '任务创建', `任务 ${values.name} 创建成功`, values.platform);
      setTaskModalVisible(false);
      taskForm.resetFields();
    } catch (error) {
      message.error('任务添加失败');
      addOperationLog('error', '任务创建', `任务创建失败: ${error}`);
    }
  }, [addOperationLog, taskForm]);

  const executeTask = useCallback(async (taskId: string) => {
    try {
      const task = tasks.find(t => t.id === taskId);
      if (!task) return;
      
      addOperationLog('info', '任务执行', `开始执行任务: ${task.name}`, task.platform);
      
      setTasks(prev => prev.map(t => 
        t.id === taskId ? { ...t, status: 'running' as const, progress: 0 } : t
      ));
      
      const command: ControlCommand = {
        type: 'api',
        target: task.platform,
        action: task.type,
        parameters: { taskId },
        priority: 'high'
      };
      
      const result = await CloudControlLayerService.executeCommand(command);
      
      if (result.success) {
        setTasks(prev => prev.map(t => 
          t.id === taskId ? { 
            ...t, 
            status: 'success' as const, 
            progress: 100,
            lastRun: new Date().toLocaleString(),
            successCount: (t.successCount || 0) + 1
          } : t
        ));
        
        message.success('任务执行成功');
        addOperationLog('success', '任务执行', `任务 ${task.name} 执行成功`, task.platform, result.duration);
      } else {
        setTasks(prev => prev.map(t => 
          t.id === taskId ? { 
            ...t, 
            status: 'failed' as const,
            errorCount: (t.errorCount || 0) + 1
          } : t
        ));
        
        message.error(`任务执行失败: ${result.error}`);
        addOperationLog('error', '任务执行', `任务 ${task.name} 执行失败: ${result.error}`, task.platform);
      }
    } catch (error) {
      message.error('任务执行失败');
      addOperationLog('error', '任务执行', `任务执行异常: ${error}`);
    }
  }, [tasks, addOperationLog]);

  const toggleTask = useCallback(async (taskId: string, enabled: boolean) => {
    try {
      setTasks(prev => prev.map(t => 
        t.id === taskId ? { ...t, enabled } : t
      ));
      
      message.success(`任务已${enabled ? '启用' : '禁用'}`);
      addOperationLog('info', '任务状态', `任务 ${enabled ? '启用' : '禁用'}`);
    } catch (error) {
      message.error('操作失败');
    }
  }, [addOperationLog]);

  const loadCloudData = useCallback(async () => {
    try {
      setProviders([
        { name: '阿里云', code: 'aliyun', description: '阿里云计算服务' },
        { name: '腾讯云', code: 'tencent', description: '腾讯云计算服务' },
        { name: 'AWS', code: 'aws', description: 'Amazon Web Services' }
      ]);

      setRegions([
        { regionId: 'cn-hangzhou', regionName: '华东1（杭州）', localName: '杭州' },
        { regionId: 'ap-guangzhou', regionName: '华南1（广州）', localName: '广州' },
        { regionId: 'cn-beijing', regionName: '华北1（北京）', localName: '北京' },
        { regionId: 'us-west-1', regionName: '美国西部1（硅谷）', localName: '硅谷' },
        { regionId: 'ap-southeast-1', regionName: '东南亚1（新加坡）', localName: '新加坡' }
      ]);

      setInstanceTypes([
        { instanceTypeId: 'ecs.g6.large', instanceTypeFamily: 'g6', cpuCoreCount: 2, memorySize: 4, gpuAmount: 0, price: 0.12 },
        { instanceTypeId: 'ecs.g6.xlarge', instanceTypeFamily: 'g6', cpuCoreCount: 4, memorySize: 8, gpuAmount: 0, price: 0.24 },
        { instanceTypeId: 'ecs.c6.large', instanceTypeFamily: 'c6', cpuCoreCount: 2, memorySize: 4, gpuAmount: 0, price: 0.10 },
        { instanceTypeId: 'S2.SMALL1', instanceTypeFamily: 'S2', cpuCoreCount: 1, memorySize: 2, gpuAmount: 0, price: 0.08 },
        { instanceTypeId: 'S2.MEDIUM2', instanceTypeFamily: 'S2', cpuCoreCount: 2, memorySize: 4, gpuAmount: 0, price: 0.16 }
      ]);

      setImages([
        { imageId: 'ubuntu_20_04', imageName: 'Ubuntu 20.04', osType: 'linux', platform: 'Ubuntu', description: 'Ubuntu 20.04 LTS' },
        { imageId: 'centos_7_9', imageName: 'CentOS 7.9', osType: 'linux', platform: 'CentOS', description: 'CentOS 7.9' },
        { imageId: 'windows_2019', imageName: 'Windows Server 2019', osType: 'windows', platform: 'Windows', description: 'Windows Server 2019' }
      ]);
    } catch (error) {
      console.error('加载云服务数据失败:', error);
    }
  }, []);

  const handleCreateCloudInstance = useCallback(async (values: CloudInstanceFormValues) => {
    try {
      addOperationLog('info', '云服务器创建', `开始创建云服务器: ${values.name}`);
      
      const createRequest: CreateInstanceRequest = {
        name: values.name,
        provider: values.provider,
        region: values.region,
        instanceType: values.instanceType,
        imageId: values.imageId,
        systemDiskSize: values.systemDiskSize || 40,
        dataDiskSize: values.dataDiskSize,
        billingType: values.billingType,
        period: values.period,
        password: values.password,
        keyPairName: values.keyPairName
      };

      const instance = await cloudService.createInstance(createRequest);
      
      message.success(`云服务器创建成功: ${instance.name}`);
      addOperationLog('success', '云服务器创建', `云服务器 ${instance.name} 创建成功`);
      setCloudModalVisible(false);
      cloudForm.resetFields();
      setEstimatedPrice(0);
      await loadClientStatus();
    } catch (error) {
      message.error('创建云服务器失败');
      addOperationLog('error', '云服务器创建', `创建失败: ${error}`);
    }
  }, [addOperationLog, cloudForm, loadClientStatus]);

  const syncPlatform = useCallback(async (platformName: string) => {
    try {
      addOperationLog('info', '平台同步', `开始同步 ${platformName} 数据`, platformName);
      
      const command: ControlCommand = {
        type: 'api',
        target: platformName.toLowerCase(),
        action: 'sync',
        parameters: {},
        priority: 'high'
      };
      
      const result = await CloudControlLayerService.executeCommand(command);
      
      if (result.success) {
        message.success(`${platformName} 同步成功`);
        addOperationLog('success', '平台同步', `${platformName} 同步成功`, platformName, result.duration);
        await loadClientStatus();
      } else {
        message.error(`同步失败: ${result.error}`);
        addOperationLog('error', '平台同步', `${platformName} 同步失败: ${result.error}`, platformName);
      }
    } catch (error) {
      message.error('同步失败');
      addOperationLog('error', '平台同步', `同步异常: ${error}`, platformName);
    }
  }, [addOperationLog, loadClientStatus]);

  const viewTaskDetail = useCallback((task: TaskInfo) => {
    setSelectedTask(task);
    setTaskDetailDrawerVisible(true);
  }, []);

  const viewInstanceDetail = useCallback(async (instance: CloudInstance) => {
    try {
      setSelectedInstance(instance);
      
      const metrics = await cloudService.getInstanceMetrics(
        instance.id,
        instance.provider,
        instance.region
      );
      setInstanceMetrics(metrics);
      
      setInstanceDetailModalVisible(true);
    } catch (error) {
      message.error('获取实例详情失败');
    }
  }, []);

  // 多客户端管理函数
  const loadClients = useCallback(async () => {
    try {
      const mockClients: ClientInfo[] = [
        {
          id: 'client-1',
          name: 'TikTok-Proxy-01',
          ip: '192.168.1.100',
          port: 8080,
          status: 'online',
          version: '2.0.0',
          uptime: 3600,
          lastSeen: Date.now(),
          cpu: 30,
          memory: 45,
          disk: 60,
          platform: 'windows',
          tasks: 8,
          platforms: 5,
          region: '华东',
          group: '生产组',
          tags: ['tiktok', 'proxy', 'production']
        },
        {
          id: 'client-2',
          name: 'Shopee-Proxy-01',
          ip: '192.168.1.101',
          port: 8080,
          status: 'online',
          version: '2.0.0',
          uptime: 7200,
          lastSeen: Date.now(),
          cpu: 25,
          memory: 40,
          disk: 55,
          platform: 'linux',
          tasks: 6,
          platforms: 4,
          region: '华南',
          group: '生产组',
          tags: ['shopee', 'proxy', 'production']
        },
        {
          id: 'client-3',
          name: 'Amazon-Proxy-01',
          ip: '192.168.1.102',
          port: 8080,
          status: 'offline',
          version: '1.9.0',
          uptime: 0,
          lastSeen: Date.now() - 3600000,
          cpu: 0,
          memory: 0,
          disk: 0,
          platform: 'windows',
          tasks: 0,
          platforms: 0,
          region: '美国',
          group: '测试组',
          tags: ['amazon', 'proxy', 'test']
        },
        {
          id: 'client-4',
          name: 'Test-Client-01',
          ip: '192.168.1.103',
          port: 8080,
          status: 'error',
          version: '1.8.0',
          uptime: 1800,
          lastSeen: Date.now() - 600000,
          cpu: 80,
          memory: 90,
          disk: 95,
          platform: 'linux',
          tasks: 10,
          platforms: 3,
          region: '华东',
          group: '测试组',
          tags: ['test', 'development']
        },
        {
          id: 'client-5',
          name: 'Backup-Proxy-01',
          ip: '192.168.1.104',
          port: 8080,
          status: 'online',
          version: '2.0.0',
          uptime: 10800,
          lastSeen: Date.now(),
          cpu: 15,
          memory: 30,
          disk: 40,
          platform: 'windows',
          tasks: 4,
          platforms: 2,
          region: '华北',
          group: '备份组',
          tags: ['backup', 'proxy']
        }
      ];

      const mockGroups: ClientGroup[] = [
        {
          id: 'group-1',
          name: '生产组',
          description: '生产环境客户端',
          clientIds: ['client-1', 'client-2'],
          color: '#52c41a'
        },
        {
          id: 'group-2',
          name: '测试组',
          description: '测试环境客户端',
          clientIds: ['client-3', 'client-4'],
          color: '#1890ff'
        },
        {
          id: 'group-3',
          name: '备份组',
          description: '备份环境客户端',
          clientIds: ['client-5'],
          color: '#faad14'
        }
      ];

      setClients(mockClients);
      setClientGroups(mockGroups);

      // 计算统计数据
      const stats: ClientStats = {
        total: mockClients.length,
        online: mockClients.filter(c => c.status === 'online').length,
        offline: mockClients.filter(c => c.status === 'offline').length,
        error: mockClients.filter(c => c.status === 'error').length,
        groups: mockGroups.length,
        totalTasks: mockClients.reduce((sum, c) => sum + c.tasks, 0),
        totalPlatforms: mockClients.reduce((sum, c) => sum + c.platforms, 0)
      };

      setClientStats(stats);
    } catch (error) {
      message.error('加载客户端数据失败');
    }
  }, []);

  const connectToClientById = useCallback(async (clientId: string) => {
    const client = clients.find(c => c.id === clientId);
    if (!client) return;

    try {
      setClients(prev => prev.map(c => 
        c.id === clientId ? { ...c, status: 'connecting' } : c
      ));

      await lightweightClientService.connectToClient(client.ip, client.port);
      
      setClients(prev => prev.map(c => 
        c.id === clientId ? { ...c, status: 'online' } : c
      ));

      message.success(`客户端 ${client.name} 连接成功`);
      addOperationLog('success', '客户端连接', `成功连接到客户端 ${client.name}`, client.name);
    } catch (error) {
      setClients(prev => prev.map(c => 
        c.id === clientId ? { ...c, status: 'error' } : c
      ));
      message.error(`客户端 ${client.name} 连接失败`);
      addOperationLog('error', '客户端连接', `连接失败: ${error}`, client.name);
    }
  }, [clients, addOperationLog]);

  const disconnectFromClient = useCallback(async (clientId: string) => {
    const client = clients.find(c => c.id === clientId);
    if (!client) return;

    try {
      setClients(prev => prev.map(c => 
        c.id === clientId ? { ...c, status: 'offline' } : c
      ));

      message.success(`客户端 ${client.name} 已断开连接`);
      addOperationLog('info', '客户端断开', `断开与客户端 ${client.name} 的连接`, client.name);
    } catch (error) {
      message.error(`断开连接失败: ${error}`);
    }
  }, [clients, addOperationLog]);

  const viewClientDetail = useCallback((client: ClientInfo) => {
    setSelectedClient(client);
    setClientDetailDrawerVisible(true);
  }, []);

  const handleSelectClient = useCallback((clientId: string, checked: boolean) => {
    setSelectedClientIds(prev => {
      if (checked) {
        return [...prev, clientId];
      } else {
        return prev.filter(id => id !== clientId);
      }
    });
  }, []);

  const handleSelectAll = useCallback((checked: boolean) => {
    setIsSelectAll(checked);
    if (checked) {
      setSelectedClientIds(clients.map(c => c.id));
    } else {
      setSelectedClientIds([]);
    }
  }, [clients]);

  const batchConnect = useCallback(async () => {
    if (selectedClientIds.length === 0) {
      message.warning('请选择客户端');
      return;
    }

    for (const clientId of selectedClientIds) {
      await connectToClientById(clientId);
    }
  }, [selectedClientIds, connectToClientById]);

  const batchDisconnect = useCallback(async () => {
    if (selectedClientIds.length === 0) {
      message.warning('请选择客户端');
      return;
    }

    for (const clientId of selectedClientIds) {
      await disconnectFromClient(clientId);
    }
  }, [selectedClientIds, disconnectFromClient]);

  const batchRestart = useCallback(() => {
    if (selectedClientIds.length === 0) {
      message.warning('请选择客户端');
      return;
    }

    message.info(`正在重启 ${selectedClientIds.length} 个客户端...`);
    addOperationLog('info', '批量操作', `开始重启 ${selectedClientIds.length} 个客户端`);
  }, [selectedClientIds, addOperationLog]);

  const createClientGroup = useCallback(async (values: any) => {
    try {
      const newGroup: ClientGroup = {
        id: `group-${Date.now()}`,
        name: values.name,
        description: values.description,
        clientIds: values.clientIds || [],
        color: values.color || '#1890ff'
      };

      setClientGroups(prev => [...prev, newGroup]);
      message.success('客户端组创建成功');
      addOperationLog('success', '客户端组管理', `创建客户端组 ${values.name}`);
      setClientGroupModalVisible(false);
      groupForm.resetFields();
    } catch (error) {
      message.error('创建客户端组失败');
    }
  }, [addOperationLog, groupForm]);

  useEffect(() => {
    let interval: NodeJS.Timeout;
    
    if (connected) {
      loadClientStatus();
      loadCloudData();
      loadClients(); // 加载客户端数据
      interval = setInterval(loadClientStatus, 30000);
    }
    
    return () => {
      if (interval) {
        clearInterval(interval);
      }
    };
  }, [connected, loadClientStatus, loadCloudData, loadClients]);

  useEffect(() => {
    if (!cloudForm) return;
    
    const handleFormChange = () => {
      try {
        const values = cloudForm.getFieldsValue();
        if (values.instanceType && values.billingType) {
          const basePrices: Record<string, number> = {
            'ecs.g6.large': 0.12,
            'ecs.g6.xlarge': 0.24,
            'S2.SMALL1': 0.08,
            'S2.MEDIUM2': 0.16
          };
          const basePrice = basePrices[values.instanceType] || 0.12;
          if (values.billingType === 'prepaid' && values.period) {
            setEstimatedPrice(basePrice * values.period * 0.8);
          } else {
            setEstimatedPrice(basePrice);
          }
        }
      } catch (error) {
        console.error('表单监听错误:', error);
      }
    };
    
    const interval = setInterval(handleFormChange, 1000);
    return () => clearInterval(interval);
  }, [cloudForm]);

  const platformColumns = useMemo(() => [
    {
      title: '平台',
      dataIndex: 'name',
      key: 'name',
      render: (text: string, record: PlatformInfo) => (
        <Space>
          <ShopOutlined />
          <div>
            <strong>{text}</strong>
            {record.proxy && (
              <div style={{ fontSize: '12px', color: '#666' }}>
                <LinkOutlined /> {record.proxy}
              </div>
            )}
          </div>
        </Space>
      )
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status: string, record: PlatformInfo) => (
        <Space direction="vertical" size="small">
          <Tag color={statusColor(status)}>
            {status === 'connected' ? '已连接' : status === 'disconnected' ? '未连接' : '错误'}
          </Tag>
          {record.cookies && <Tag color="blue" icon={<SafetyCertificateOutlined />}>Cookies有效</Tag>}
        </Space>
      )
    },
    {
      title: '登录时间',
      dataIndex: 'loginTime',
      key: 'loginTime',
      render: (time: string) => time || '-'
    },
    {
      title: '最后同步',
      dataIndex: 'lastSync',
      key: 'lastSync'
    },
    {
      title: '订单数',
      dataIndex: 'orderCount',
      key: 'orderCount',
      render: (count: number) => <Badge count={count} showZero style={{ backgroundColor: '#52c41a' }} />
    },
    {
      title: '商品数',
      dataIndex: 'productCount',
      key: 'productCount',
      render: (count: number) => <Badge count={count} showZero style={{ backgroundColor: '#1890ff' }} />
    },
    {
      title: '操作',
      key: 'action',
      width: 250,
      render: (_text: unknown, record: PlatformInfo) => (
        <Space>
          <Button 
            type="link" 
            icon={<SyncOutlined />}
            onClick={() => syncPlatform(record.name)}
            disabled={record.status !== 'connected'}
          >
            同步
          </Button>
          <Button 
            type="link" 
            icon={record.status === 'connected' ? <UnlockOutlined /> : <LockOutlined />}
            onClick={() => setLoginModalVisible(true)}
          >
            {record.status === 'connected' ? '重新登录' : '登录'}
          </Button>
          <Button 
            type="link" 
            icon={<SettingOutlined />}
            onClick={() => message.info('平台配置功能开发中')}
          >
            配置
          </Button>
        </Space>
      )
    }
  ], [syncPlatform]);

  const taskColumns = useMemo(() => [
    {
      title: '任务名称',
      dataIndex: 'name',
      key: 'name',
      width: 200,
      render: (text: string, record: TaskInfo) => (
        <div>
          <div><strong>{text}</strong></div>
          <div style={{ fontSize: '12px', color: '#666' }}>
            {record.description}
          </div>
          {record.status === 'running' && (
            <Progress percent={record.progress} size="small" status="active" />
          )}
        </div>
      )
    },
    {
      title: '平台',
      dataIndex: 'platform',
      key: 'platform',
      render: (platform: string) => (
        <Tag color={platform === 'all' ? 'purple' : 'blue'}>
          {platform === 'all' ? '所有平台' : platform.toUpperCase()}
        </Tag>
      )
    },
    {
      title: '类型',
      dataIndex: 'type',
      key: 'type',
      render: (type: string) => {
        const typeMap: Record<string, { color: string; icon: React.ReactNode }> = {
          sync: { color: 'green', icon: <SyncOutlined /> },
          monitor: { color: 'blue', icon: <MonitorOutlined /> },
          publish: { color: 'orange', icon: <PlayCircleOutlined /> },
          analysis: { color: 'purple', icon: <EyeOutlined /> },
          optimize: { color: 'cyan', icon: <SettingOutlined /> },
          finance: { color: 'gold', icon: <DollarOutlined /> }
        };
        const config = typeMap[type] || { color: 'default', icon: null };
        return <Tag color={config.color} icon={config.icon}>{type}</Tag>;
      }
    },
    {
      title: '调度',
      dataIndex: 'schedule',
      key: 'schedule',
      render: (schedule: string) => <code>{schedule}</code>
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status: string, record: TaskInfo) => (
        <Space direction="vertical" size="small">
          <Tag color={statusColor(status)}>
            {status === 'running' ? '运行中' : status === 'success' ? '成功' : status === 'failed' ? '失败' : '空闲'}
          </Tag>
          {(record.successCount || record.errorCount) && (
            <div style={{ fontSize: '12px' }}>
              <span style={{ color: '#52c41a' }}>✓{record.successCount || 0}</span>
              {' / '}
              <span style={{ color: '#ff4d4f' }}>✗{record.errorCount || 0}</span>
            </div>
          )}
        </Space>
      )
    },
    {
      title: '下次执行',
      dataIndex: 'nextRun',
      key: 'nextRun',
      render: (time: string) => time || '-'
    },
    {
      title: '操作',
      key: 'action',
      width: 200,
      render: (_text: unknown, record: TaskInfo) => (
        <Space>
          <Tooltip title="执行任务">
            <Button 
              type="link" 
              icon={<PlayCircleOutlined />}
              onClick={() => executeTask(record.id)}
              disabled={record.status === 'running'}
            />
          </Tooltip>
          <Tooltip title={record.enabled ? "暂停任务" : "启用任务"}>
            <Switch
              checked={record.enabled}
              onChange={(checked) => toggleTask(record.id, checked)}
              size="small"
            />
          </Tooltip>
          <Tooltip title="查看详情">
            <Button 
              type="link" 
              icon={<EyeOutlined />}
              onClick={() => viewTaskDetail(record)}
            />
          </Tooltip>
          <Popconfirm
            title="确定删除这个任务吗？"
            onConfirm={() => {
              setTasks(prev => prev.filter(t => t.id !== record.id));
              message.success('任务已删除');
            }}
          >
            <Tooltip title="删除任务">
              <Button type="link" danger icon={<DeleteOutlined />} />
            </Tooltip>
          </Popconfirm>
        </Space>
      )
    }
  ], [executeTask, toggleTask, viewTaskDetail]);

  const cloudInstanceColumns = useMemo(() => [
    {
      title: '实例名称',
      dataIndex: 'name',
      key: 'name',
      render: (text: string, record: CloudInstance) => (
        <Space>
          <CloudServerOutlined />
          <div>
            <Button 
              type="link" 
              onClick={() => viewInstanceDetail(record)}
              style={{ padding: 0, height: 'auto' }}
            >
              <strong>{text}</strong>
            </Button>
            <div style={{ fontSize: '12px', color: '#666' }}>
              {record.provider} - {record.region}
            </div>
          </div>
        </Space>
      )
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status: string) => (
        <Tag color={statusColor(status)}>
          {status === 'running' ? '运行中' : status === 'stopped' ? '已停止' : status === 'starting' ? '启动中' : status === 'stopping' ? '停止中' : '错误'}
        </Tag>
      )
    },
    {
      title: 'IP地址',
      dataIndex: 'ipAddress',
      key: 'ipAddress',
      render: (ip: string) => ip ? <code>{ip}</code> : <Text type="secondary">未分配</Text>
    },
    {
      title: '实例类型',
      dataIndex: 'instanceType',
      key: 'instanceType'
    },
    {
      title: '创建时间',
      dataIndex: 'createdTime',
      key: 'createdTime'
    },
    {
      title: '过期时间',
      dataIndex: 'expiredTime',
      key: 'expiredTime',
      render: (time: string) => time ? (
        <Space>
          <ClockCircleOutlined />
          {time}
        </Space>
      ) : <Tag>按需计费</Tag>
    },
    {
      title: '操作',
      key: 'action',
      width: 200,
      render: (_text: unknown, record: CloudInstance) => (
        <Space>
          <Tooltip title="查看详情">
            <Button 
              type="link" 
              icon={<EyeOutlined />}
              onClick={() => viewInstanceDetail(record)}
            />
          </Tooltip>
          
          {record.status === 'stopped' && (
            <Tooltip title="启动实例">
              <Button 
                type="link" 
                icon={<PlayCircleOutlined />}
                onClick={() => {
                  cloudService.startInstance(record.id, record.provider, record.region);
                  message.success('启动命令已发送');
                }}
              />
            </Tooltip>
          )}
          
          {record.status === 'running' && (
            <>
              <Tooltip title="停止实例">
                <Button 
                  type="link" 
                  icon={<PauseCircleOutlined />}
                  onClick={() => {
                    cloudService.stopInstance(record.id, record.provider, record.region);
                    message.success('停止命令已发送');
                  }}
                />
              </Tooltip>
              <Tooltip title="重启实例">
                <Button 
                  type="link" 
                  icon={<ReloadOutlined />}
                  onClick={() => {
                    cloudService.rebootInstance(record.id, record.provider, record.region);
                    message.success('重启命令已发送');
                  }}
                />
              </Tooltip>
            </>
          )}
          
          <Tooltip title="远程连接">
            <Button 
              type="link" 
              icon={<DesktopOutlined />}
              onClick={() => message.info('远程连接功能开发中')}
            />
          </Tooltip>
        </Space>
      )
    }
  ], [viewInstanceDetail]);

  const webSessionColumns = useMemo(() => [
    {
      title: '会话ID',
      dataIndex: 'id',
      key: 'id',
      render: (text: string) => (
        <Space>
          <GlobalOutlined />
          <code>{text.slice(0, 15)}...</code>
        </Space>
      )
    },
    {
      title: '平台',
      dataIndex: 'platform',
      key: 'platform',
      render: (platform: string) => <Tag color="blue">{platform.toUpperCase()}</Tag>
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status: string) => (
        <Tag color={statusColor(status)}>
          {status === 'ready' ? '就绪' : status === 'active' ? '活跃' : status === 'error' ? '错误' : '已关闭'}
        </Tag>
      )
    },
    {
      title: '当前页面',
      dataIndex: 'currentUrl',
      key: 'currentUrl',
      ellipsis: true,
      render: (url: string) => <a href={url} target="_blank" rel="noopener noreferrer">{url}</a>
    },
    {
      title: '页面标题',
      dataIndex: 'title',
      key: 'title',
      ellipsis: true
    },
    {
      title: '最后活动',
      dataIndex: 'lastActivity',
      key: 'lastActivity'
    },
    {
      title: '操作',
      key: 'action',
      render: (_text: unknown, record: WebRemoteSession) => (
        <Space>
          <Tooltip title="控制会话">
            <Button 
              type="link" 
              icon={<DesktopOutlined />}
              onClick={() => message.info(`打开WEB远程控制: ${record.id}`)}
            />
          </Tooltip>
          <Tooltip title="查看截图">
            <Button 
              type="link" 
              icon={<EyeOutlined />}
              onClick={() => message.info('截图功能开发中')}
            />
          </Tooltip>
          <Popconfirm
            title="确定关闭这个会话吗？"
            onConfirm={() => {
              cloudService.closeSession(record.id);
              message.success('会话已关闭');
            }}
          >
            <Tooltip title="关闭会话">
              <Button type="link" danger icon={<DeleteOutlined />} />
            </Tooltip>
          </Popconfirm>
        </Space>
      )
    }
  ], []);

  const statisticsData = useMemo(() => {
    if (!clientStatus) return null;
    return {
      platformTotal: clientStatus.platforms.total,
      platformLoggedIn: clientStatus.platforms.loggedIn.length,
      taskTotal: clientStatus.tasks.total,
      taskEnabled: clientStatus.tasks.enabled,
      cloudTotal: cloudInstances.length,
      cloudRunning: cloudInstances.filter(i => i.status === 'running').length,
      webSessionTotal: webSessions.length,
      webSessionActive: webSessions.filter(s => s.status === 'active').length,
      orderTotal: platforms.reduce((sum, p) => sum + p.orderCount, 0),
      productTotal: platforms.reduce((sum, p) => sum + p.productCount, 0)
    };
  }, [clientStatus, cloudInstances, webSessions, platforms]);

  const logTimelineItems = useMemo(() => {
    return operationLogs.slice(0, 20).map(log => ({
      color: log.level === 'error' ? 'red' : log.level === 'warning' ? 'orange' : log.level === 'success' ? 'green' : 'blue',
      children: (
        <div>
          <div>
            {logLevelIcon(log.level)} 
            <Text strong style={{ marginLeft: 8 }}>{log.operation}</Text>
            {log.platform && <Tag style={{ marginLeft: 8 }}>{log.platform}</Tag>}
          </div>
          <Text type="secondary" style={{ fontSize: 12 }}>{log.details}</Text>
          <div>
            <Text type="secondary" style={{ fontSize: 11 }}>
              {log.timestamp}
              {log.duration && ` | ${log.duration}ms`}
            </Text>
          </div>
        </div>
      )
    }));
  }, [operationLogs]);

  return (
    <div style={{ padding: '24px', background: '#f0f2f5', minHeight: '100vh' }}>
      <Row gutter={[16, 16]} style={{ marginBottom: '24px' }}>
        <Col span={24}>
          <Card>
            <Row justify="space-between" align="middle">
              <Col>
                <Title level={3} style={{ margin: 0 }}>
                  <CloudServerOutlined /> Operation-Agent 增强版管理界面
                </Title>
                <Paragraph style={{ margin: 0, color: '#666' }}>
                  支持多平台自动化操作、云服务器管理、WEB远程控制 | 四层架构：API模拟 → WEB远程 → 远程桌面 → 云API
                </Paragraph>
              </Col>
              <Col>
                <Space>
                  <Button 
                    icon={<HistoryOutlined />}
                    onClick={() => message.info('操作历史功能开发中')}
                  >
                    操作历史
                  </Button>
                  <Button 
                    icon={<SettingOutlined />}
                    onClick={() => setConfigDrawerVisible(true)}
                  >
                    客户端配置
                  </Button>
                  <Button 
                    type={connected ? "default" : "primary"}
                    icon={connected ? <SyncOutlined /> : <PlayCircleOutlined />}
                    loading={loading}
                    onClick={connectToClient}
                  >
                    {connected ? '重新连接' : '连接客户端'}
                  </Button>
                </Space>
              </Col>
            </Row>
          </Card>
        </Col>
      </Row>

      {!connected ? (
        <Row gutter={[16, 16]} style={{ marginTop: '24px' }}>
          <Col span={24}>
            <Card>
              <Result
                icon={<CloudServerOutlined style={{ fontSize: 72, color: '#1890ff' }} />}
                title="欢迎使用 Operation-Agent 增强版"
                subTitle="请先连接客户端以开始使用多平台自动化操作、云服务器管理、WEB远程控制等功能"
                extra={[
                  <Button 
                    type="primary" 
                    key="connect"
                    size="large"
                    icon={<PlayCircleOutlined />}
                    loading={loading}
                    onClick={connectToClient}
                  >
                    连接客户端
                  </Button>,
                  <Button 
                    key="help"
                    size="large"
                    icon={<InfoCircleOutlined />}
                    onClick={() => message.info('帮助文档开发中')}
                  >
                    查看帮助
                  </Button>
                ]}
              >
                <Descriptions title="系统功能" bordered column={2}>
                  <Descriptions.Item label="多平台支持">
                    TikTok、Shopee、Amazon、Temu、Lazada
                  </Descriptions.Item>
                  <Descriptions.Item label="四层架构">
                    API模拟 → WEB远程 → 远程桌面 → 云API
                  </Descriptions.Item>
                  <Descriptions.Item label="云服务器管理">
                    支持多云平台、自动扩缩容、成本优化
                  </Descriptions.Item>
                  <Descriptions.Item label="自动化任务">
                    定时调度、实时监控、智能决策
                  </Descriptions.Item>
                </Descriptions>
              </Result>
            </Card>
          </Col>
        </Row>
      ) : (
        <>
          {clientStatus && statisticsData && (
            <Row gutter={[16, 16]} style={{ marginBottom: '24px' }}>
              <Col span={4}>
                <Card hoverable>
                  <Statistic
                    title="平台数量"
                    value={statisticsData.platformTotal}
                    prefix={<ShopOutlined />}
                    suffix={<Text type="secondary" style={{ fontSize: 14 }}>/ {statisticsData.platformLoggedIn} 已登录</Text>}
                  />
                </Card>
              </Col>
              <Col span={4}>
                <Card hoverable>
                  <Statistic
                    title="任务数量"
                    value={statisticsData.taskTotal}
                    prefix={<ScheduleOutlined />}
                    suffix={<Text type="secondary" style={{ fontSize: 14 }}>/ {statisticsData.taskEnabled} 启用</Text>}
                  />
                </Card>
              </Col>
              <Col span={4}>
                <Card hoverable>
                  <Statistic
                    title="云服务器"
                    value={statisticsData.cloudTotal}
                    prefix={<CloudServerOutlined />}
                    suffix={<Text type="secondary" style={{ fontSize: 14 }}>/ {statisticsData.cloudRunning} 运行中</Text>}
                    valueStyle={{ color: '#3f8600' }}
                  />
                </Card>
              </Col>
              <Col span={4}>
                <Card hoverable>
                  <Statistic
                    title="WEB会话"
                    value={statisticsData.webSessionTotal}
                    prefix={<GlobalOutlined />}
                    suffix={<Text type="secondary" style={{ fontSize: 14 }}>/ {statisticsData.webSessionActive} 活跃</Text>}
                  />
                </Card>
              </Col>
              <Col span={4}>
                <Card hoverable>
                  <Statistic
                    title="今日订单"
                    value={statisticsData.orderTotal}
                    prefix={<ShoppingCartOutlined />}
                    valueStyle={{ color: '#1890ff' }}
                  />
                </Card>
              </Col>
              <Col span={4}>
                <Card hoverable>
                  <Statistic
                    title="今日商品"
                    value={statisticsData.productTotal}
                    prefix={<DollarOutlined />}
                    valueStyle={{ color: '#722ed1' }}
                  />
                </Card>
              </Col>
            </Row>
          )}

          <Row gutter={[16, 16]}>
            <Col span={18}>
            <Card>
              <Tabs defaultActiveKey="cloud" size="large">
                {connected && (
                  <>
                    <TabPane tab={
                      <span>
                        <ShopOutlined />
                        平台管理
                        <Badge count={platforms.filter(p => p.status === 'connected').length} style={{ marginLeft: 8 }} />
                      </span>
                    } key="platforms">
                      <Card
                        title="电商平台管理"
                        extra={
                          <Space>
                            <Button 
                              type="primary" 
                              icon={<PlusOutlined />}
                              onClick={() => setLoginModalVisible(true)}
                            >
                              添加平台
                            </Button>
                            <Button 
                              icon={<SyncOutlined />}
                              onClick={loadClientStatus}
                            >
                              刷新
                            </Button>
                          </Space>
                        }
                      >
                        <Table
                          columns={platformColumns}
                          dataSource={platforms}
                          rowKey="name"
                          pagination={false}
                        />
                      </Card>
                    </TabPane>

                    <TabPane tab={
                      <span>
                        <ScheduleOutlined />
                        任务调度
                        <Badge count={tasks.filter(t => t.status === 'running').length} style={{ marginLeft: 8, backgroundColor: '#52c41a' }} />
                      </span>
                    } key="tasks">
                      <Card
                        title="自动化任务"
                        extra={
                          <Space>
                            <Button 
                              type="primary" 
                              icon={<PlusOutlined />}
                              onClick={() => setTaskModalVisible(true)}
                            >
                              添加任务
                            </Button>
                            <Button 
                              icon={<SyncOutlined />}
                              onClick={loadClientStatus}
                            >
                              刷新
                            </Button>
                          </Space>
                        }
                      >
                        <Table
                          columns={taskColumns}
                          dataSource={tasks}
                          rowKey="id"
                          pagination={false}
                        />
                      </Card>
                    </TabPane>
                  </>
                )}

                <TabPane tab={
                  <span>
                    <CloudServerOutlined />
                    云服务器管理
                    <Badge count={cloudInstances.filter(i => i.status === 'running').length} style={{ marginLeft: 8, backgroundColor: '#52c41a' }} />
                  </span>
                } key="cloud">
                  <Card
                    title="云服务器实例"
                    extra={
                      <Space>
                        <Button 
                          type="primary" 
                          icon={<PlusOutlined />}
                          onClick={() => setCloudModalVisible(true)}
                        >
                          购买实例
                        </Button>
                        <Button 
                          icon={<SyncOutlined />}
                          onClick={loadClientStatus}
                        >
                          刷新
                        </Button>
                      </Space>
                    }
                  >
                    <Table
                      columns={cloudInstanceColumns}
                      dataSource={cloudInstances}
                      rowKey="id"
                      pagination={false}
                    />
                  </Card>
                </TabPane>

                {connected && (
                  <TabPane tab={
                    <span>
                      <GlobalOutlined />
                      WEB远程控制
                      <Badge count={webSessions.filter(s => s.status === 'active').length} style={{ marginLeft: 8, backgroundColor: '#52c41a' }} />
                    </span>
                  } key="webremote">
                    <Card
                      title="WEB远程会话"
                      extra={
                        <Space>
                          <Button 
                            type="primary" 
                            icon={<PlusOutlined />}
                            onClick={() => setWebRemoteModalVisible(true)}
                          >
                            创建会话
                          </Button>
                          <Button 
                            icon={<SyncOutlined />}
                            onClick={loadClientStatus}
                          >
                            刷新
                          </Button>
                        </Space>
                      }
                    >
                      <Table
                        columns={webSessionColumns}
                        dataSource={webSessions}
                        rowKey="id"
                        pagination={false}
                      />
                    </Card>
                  </TabPane>
                )}

                <TabPane tab={
                  <span>
                    <DesktopOutlined />
                    客户端管理
                    <Badge count={clients.filter(c => c.status === 'online').length} style={{ marginLeft: 8, backgroundColor: '#52c41a' }} />
                  </span>
                } key="clients">
                  <Card
                    title="多客户端管理"
                    extra={
                      <Space>
                        <Button 
                          type="primary" 
                          icon={<PlusOutlined />}
                          onClick={() => setClientGroupModalVisible(true)}
                        >
                          添加客户端组
                        </Button>
                        <Button 
                          icon={<SyncOutlined />}
                          onClick={loadClients}
                        >
                          刷新
                        </Button>
                      </Space>
                    }
                  >
                    <div style={{ marginBottom: 16 }}>
                      <Row gutter={16}>
                        <Col span={4}>
                          <Card>
                            <Statistic title="总客户端" value={clientStats.total} />
                          </Card>
                        </Col>
                        <Col span={4}>
                          <Card>
                            <Statistic title="在线" value={clientStats.online} valueStyle={{ color: '#52c41a' }} />
                          </Card>
                        </Col>
                        <Col span={4}>
                          <Card>
                            <Statistic title="离线" value={clientStats.offline} valueStyle={{ color: '#faad14' }} />
                          </Card>
                        </Col>
                        <Col span={4}>
                          <Card>
                            <Statistic title="异常" value={clientStats.error} valueStyle={{ color: '#ff4d4f' }} />
                          </Card>
                        </Col>
                        <Col span={4}>
                          <Card>
                            <Statistic title="客户端组" value={clientStats.groups} />
                          </Card>
                        </Col>
                        <Col span={4}>
                          <Card>
                            <Statistic title="总任务数" value={clientStats.totalTasks} />
                          </Card>
                        </Col>
                      </Row>
                    </div>

                    <div style={{ marginBottom: 16 }}>
                      <Card title="批量操作" size="small">
                        <Space>
                          <Button 
                            type="primary" 
                            icon={<PlayCircleOutlined />}
                            onClick={batchConnect}
                            disabled={selectedClientIds.length === 0}
                          >
                            批量连接
                          </Button>
                          <Button 
                            icon={<PauseCircleOutlined />}
                            onClick={batchDisconnect}
                            disabled={selectedClientIds.length === 0}
                          >
                            批量断开
                          </Button>
                          <Button 
                            icon={<ReloadOutlined />}
                            onClick={batchRestart}
                            disabled={selectedClientIds.length === 0}
                          >
                            批量重启
                          </Button>
                          <Select 
                            placeholder="按状态筛选" 
                            style={{ width: 120 }}
                          >
                            <Option value="all">全部</Option>
                            <Option value="online">在线</Option>
                            <Option value="offline">离线</Option>
                            <Option value="error">异常</Option>
                          </Select>
                          <Select 
                            placeholder="按分组筛选" 
                            style={{ width: 120 }}
                          >
                            <Option value="all">全部</Option>
                            {clientGroups.map(group => (
                              <Option key={group.id} value={group.id}>{group.name}</Option>
                            ))}
                          </Select>
                        </Space>
                      </Card>
                    </div>

                    <Table
                      dataSource={clients}
                      columns={[
                        {
                          title: (
                            <Checkbox
                              checked={isSelectAll}
                              onChange={(e) => handleSelectAll(e.target.checked)}
                            />
                          ),
                          key: 'selection',
                          width: 60,
                          render: (_text, record) => (
                            <Checkbox
                              checked={selectedClientIds.includes(record.id)}
                              onChange={(e) => handleSelectClient(record.id, e.target.checked)}
                            />
                          ),
                        },
                        {
                          title: '客户端名称',
                          dataIndex: 'name',
                          key: 'name',
                          render: (text, record) => (
                            <Space>
                              <Button 
                                type="link" 
                                onClick={() => viewClientDetail(record)}
                                style={{ padding: 0, height: 'auto' }}
                              >
                                <strong>{text}</strong>
                              </Button>
                              <div style={{ fontSize: '12px', color: '#666' }}>
                                {record.ip}:{record.port}
                              </div>
                            </Space>
                          ),
                        },
                        {
                          title: '状态',
                          dataIndex: 'status',
                          key: 'status',
                          render: (status) => (
                            <Tag color={status === 'online' ? 'green' : status === 'offline' ? 'orange' : 'red'}>
                              {status === 'online' ? '在线' : status === 'offline' ? '离线' : '异常'}
                            </Tag>
                          ),
                        },
                        {
                          title: '平台',
                          dataIndex: 'platform',
                          key: 'platform',
                        },
                        {
                          title: '版本',
                          dataIndex: 'version',
                          key: 'version',
                        },
                        {
                          title: '资源使用',
                          key: 'resources',
                          render: (_, record) => (
                            <Space direction="vertical" size="small">
                              <div>
                                <span style={{ fontSize: '12px', color: '#666' }}>CPU:</span>
                                <Progress percent={record.cpu} size="small" status={record.cpu > 80 ? 'exception' : 'normal'} />
                              </div>
                              <div>
                                <span style={{ fontSize: '12px', color: '#666' }}>内存:</span>
                                <Progress percent={record.memory} size="small" status={record.memory > 80 ? 'exception' : 'normal'} />
                              </div>
                              <div>
                                <span style={{ fontSize: '12px', color: '#666' }}>磁盘:</span>
                                <Progress percent={record.disk} size="small" status={record.disk > 80 ? 'exception' : 'normal'} />
                              </div>
                            </Space>
                          ),
                        },
                        {
                          title: '运行时间',
                          key: 'uptime',
                          render: (_, record) => (
                            <div>
                              {record.uptime > 0 ? `${Math.floor(record.uptime / 3600)}h ${Math.floor((record.uptime % 3600) / 60)}m` : '-'}
                            </div>
                          ),
                        },
                        {
                          title: '标签',
                          key: 'tags',
                          render: (_, record) => (
                            <Space size="small">
                              {record.tags.map((tag, index) => (
                                <Tag key={index}>{tag}</Tag>
                              ))}
                            </Space>
                          ),
                        },
                        {
                          title: '操作',
                          key: 'action',
                          width: 200,
                          render: (_text, record) => (
                            <Space>
                              {record.status !== 'online' && (
                                <Tooltip title="连接客户端">
                                  <Button 
                                    type="link" 
                                    icon={<PlayCircleOutlined />}
                                    onClick={() => connectToClientById(record.id)}
                                  />
                                </Tooltip>
                              )}
                              {record.status === 'online' && (
                                <Tooltip title="断开连接">
                                  <Button 
                                    type="link" 
                                    icon={<PauseCircleOutlined />}
                                    onClick={() => disconnectFromClient(record.id)}
                                  />
                                </Tooltip>
                              )}
                              <Tooltip title="查看详情">
                                <Button 
                                  type="link" 
                                  icon={<EyeOutlined />}
                                  onClick={() => viewClientDetail(record)}
                                />
                              </Tooltip>
                              <Tooltip title="重启客户端">
                                <Button 
                                  type="link" 
                                  icon={<ReloadOutlined />}
                                  onClick={() => batchRestart()}
                                />
                              </Tooltip>
                            </Space>
                          ),
                        },
                      ]}
                      rowKey="id"
                      pagination={{ pageSize: 10 }}
                      bordered
                    />
                  </Card>
                </TabPane>
              </Tabs>
            </Card>
          </Col>

          {connected && (
            <Col span={6}>
              <Space direction="vertical" style={{ width: '100%' }} size="middle">
                <Card 
                  title={
                    <Space>
                      <MonitorOutlined />
                      <span>四层架构状态</span>
                    </Space>
                  }
                  size="small"
                >
                  <List
                    itemLayout="horizontal"
                    dataSource={layerStatus}
                    renderItem={item => (
                      <List.Item>
                        <List.Item.Meta
                          avatar={
                            <Avatar 
                              style={{ 
                                backgroundColor: item.available ? '#52c41a' : '#ff4d4f' 
                              }}
                              icon={item.available ? <CheckCircleOutlined /> : <CloseCircleOutlined />}
                            />
                          }
                          title={item.layer}
                          description={
                            <Space direction="vertical" size="small" style={{ width: '100%' }}>
                              <Progress 
                                percent={Math.round(item.successRate * 100)} 
                                size="small" 
                                status={item.available ? 'success' : 'exception'}
                              />
                              <Text type="secondary" style={{ fontSize: 12 }}>
                                延迟: {item.latency}ms | 错误: {item.errorCount}
                              </Text>
                            </Space>
                          }
                        />
                      </List.Item>
                    )}
                  />
                </Card>

                <Card 
                  title={
                    <Space>
                      <FileTextOutlined />
                      <span>操作日志</span>
                      <Badge count={operationLogs.filter(l => l.level === 'error').length} />
                    </Space>
                  }
                  size="small"
                  extra={<Button type="link" size="small" onClick={() => setOperationLogs([])}>清空</Button>}
                >
                  <div style={{ maxHeight: 400, overflow: 'auto' }}>
                    {operationLogs.length === 0 ? (
                      <Empty description="暂无日志" image={Empty.PRESENTED_IMAGE_SIMPLE} />
                    ) : (
                      <Timeline items={logTimelineItems} />
                    )}
                  </div>
                </Card>

                <Card 
                  title={
                    <Space>
                      <ClockCircleOutlined />
                      <span>客户端信息</span>
                    </Space>
                  }
                  size="small"
                >
                  <Descriptions column={1} size="small">
                    <Descriptions.Item label="平台">{clientStatus?.platform || '-'}</Descriptions.Item>
                    <Descriptions.Item label="版本">{clientStatus?.version || '-'}</Descriptions.Item>
                    <Descriptions.Item label="运行时间">
                      {clientStatus ? `${Math.floor(clientStatus.uptime / 3600)}小时${Math.floor((clientStatus.uptime % 3600) / 60)}分` : '-'}
                    </Descriptions.Item>
                    <Descriptions.Item label="连接数">
                      {clientStatus ? `${clientStatus.connections.active} / ${clientStatus.connections.max}` : '-'}
                    </Descriptions.Item>
                  </Descriptions>
                </Card>
              </Space>
            </Col>
          )}
        </Row>
        </>
      )}

      <Modal
        title={<Space><LockOutlined />平台登录</Space>}
        open={loginModalVisible}
        onCancel={() => setLoginModalVisible(false)}
        footer={null}
        width={500}
      >
        <Alert
          message="登录说明"
          description="系统将使用四层架构自动选择最佳登录方式：API模拟 → WEB远程 → 远程桌面 → 云API"
          type="info"
          showIcon
          style={{ marginBottom: 16 }}
        />
        <Form form={form} onFinish={handlePlatformLogin} layout="vertical">
          <Form.Item name="platform" label="选择平台" rules={[{ required: true, message: '请选择平台' }]}>
            <Select placeholder="请选择平台">
              <Option value="tiktok">TikTok Shop</Option>
              <Option value="shopee">Shopee</Option>
              <Option value="amazon">Amazon</Option>
              <Option value="temu">Temu</Option>
              <Option value="lazada">Lazada</Option>
            </Select>
          </Form.Item>
          <Form.Item name="username" label="用户名/邮箱" rules={[{ required: true, message: '请输入用户名' }]}>
            <Input prefix={<UserOutlined />} placeholder="请输入用户名或邮箱" />
          </Form.Item>
          <Form.Item name="password" label="密码" rules={[{ required: true, message: '请输入密码' }]}>
            <Input.Password prefix={<LockOutlined />} placeholder="请输入密码" />
          </Form.Item>
          <Form.Item name="twoFactorCode" label="两步验证码（可选）">
            <Input placeholder="如果平台需要两步验证，请输入验证码" />
          </Form.Item>
          <Form.Item>
            <Button type="primary" htmlType="submit" block size="large" icon={<LockOutlined />}>
              登录
            </Button>
          </Form.Item>
        </Form>
      </Modal>

      <Modal
        title={<Space><ScheduleOutlined />添加自动化任务</Space>}
        open={taskModalVisible}
        onCancel={() => setTaskModalVisible(false)}
        footer={null}
        width={600}
      >
        <Form form={taskForm} onFinish={handleAddTask} layout="vertical">
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item name="name" label="任务名称" rules={[{ required: true, message: '请输入任务名称' }]}>
                <Input placeholder="例如：每日订单同步" />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item name="platform" label="目标平台" rules={[{ required: true, message: '请选择平台' }]}>
                <Select placeholder="请选择平台">
                  <Option value="all">所有平台</Option>
                  <Option value="tiktok">TikTok</Option>
                  <Option value="shopee">Shopee</Option>
                  <Option value="amazon">Amazon</Option>
                  <Option value="temu">Temu</Option>
                  <Option value="lazada">Lazada</Option>
                </Select>
              </Form.Item>
            </Col>
          </Row>
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item name="type" label="任务类型" rules={[{ required: true, message: '请选择任务类型' }]}>
                <Select placeholder="请选择任务类型">
                  <Option value="sync">数据同步</Option>
                  <Option value="monitor">监控任务</Option>
                  <Option value="publish">商品上架</Option>
                  <Option value="analysis">数据分析</Option>
                  <Option value="optimize">自动优化</Option>
                  <Option value="finance">财务对账</Option>
                </Select>
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item name="schedule" label="调度规则" rules={[{ required: true, message: '请输入调度规则' }]}>
                <Input placeholder="例如: 0 2 * * * (每天凌晨2点)" />
              </Form.Item>
            </Col>
          </Row>
          <Form.Item name="description" label="任务描述">
            <Input.TextArea rows={3} placeholder="请输入任务描述" />
          </Form.Item>
          <Form.Item>
            <Button type="primary" htmlType="submit" block size="large" icon={<PlusOutlined />}>
              添加任务
            </Button>
          </Form.Item>
        </Form>
      </Modal>

      <Modal
        title={<Space><CloudServerOutlined />购买云服务器</Space>}
        open={cloudModalVisible}
        onCancel={() => {
          setCloudModalVisible(false);
          setEstimatedPrice(0);
          cloudForm.resetFields();
        }}
        width={800}
        footer={null}
      >
        <Form form={cloudForm} onFinish={handleCreateCloudInstance} layout="vertical">
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item name="name" label="实例名称" rules={[{ required: true, message: '请输入实例名称' }]}>
                <Input placeholder="例如：TikTok-Proxy-01" />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item name="provider" label="云服务商" rules={[{ required: true, message: '请选择云服务商' }]}>
                <Select placeholder="请选择云服务商">
                  {providers.map(provider => (
                    <Option key={provider.code} value={provider.code}>
                      {provider.name}
                    </Option>
                  ))}
                </Select>
              </Form.Item>
            </Col>
          </Row>

          <Row gutter={16}>
            <Col span={12}>
              <Form.Item name="region" label="地域" rules={[{ required: true, message: '请选择地域' }]}>
                <Select placeholder="请选择地域">
                  {regions.map(region => (
                    <Option key={region.regionId} value={region.regionId}>
                      {region.regionName}
                    </Option>
                  ))}
                </Select>
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item name="instanceType" label="实例规格" rules={[{ required: true, message: '请选择实例规格' }]}>
                <Select placeholder="请选择实例规格">
                  {instanceTypes.map(type => (
                    <Option key={type.instanceTypeId} value={type.instanceTypeId}>
                      {type.cpuCoreCount}核{type.memorySize}G - ¥{type.price}/小时
                    </Option>
                  ))}
                </Select>
              </Form.Item>
            </Col>
          </Row>

          <Row gutter={16}>
            <Col span={12}>
              <Form.Item name="imageId" label="操作系统" rules={[{ required: true, message: '请选择操作系统' }]}>
                <Select placeholder="请选择操作系统">
                  {images.map(image => (
                    <Option key={image.imageId} value={image.imageId}>
                      {image.imageName}
                    </Option>
                  ))}
                </Select>
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item name="billingType" label="计费方式" rules={[{ required: true, message: '请选择计费方式' }]}>
                <Select placeholder="请选择计费方式">
                  <Option value="prepaid">包年包月</Option>
                  <Option value="postpaid">按量计费</Option>
                </Select>
              </Form.Item>
            </Col>
          </Row>

          <Row gutter={16}>
            <Col span={12}>
              <Form.Item name="systemDiskSize" label="系统盘大小(GB)" rules={[{ required: true, message: '请输入系统盘大小' }]}>
                <InputNumber min={20} max={500} style={{ width: '100%' }} placeholder="请输入系统盘大小" addonAfter="GB" />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item name="dataDiskSize" label="数据盘大小(GB)">
                <InputNumber min={0} max={2000} style={{ width: '100%' }} placeholder="可选" addonAfter="GB" />
              </Form.Item>
            </Col>
          </Row>

          <Form.Item 
            name="period" 
            label="购买时长(月)" 
            dependencies={['billingType']}
            rules={[({ getFieldValue }) => ({
              required: getFieldValue('billingType') === 'prepaid', 
              message: '包年包月需要指定购买时长' 
            })]}
          >
            <Select placeholder="请选择购买时长">
              <Option value={1}>1个月</Option>
              <Option value={3}>3个月</Option>
              <Option value={6}>6个月</Option>
              <Option value={12}>12个月</Option>
            </Select>
          </Form.Item>

          <Form.Item name="password" label="实例密码">
            <Input.Password placeholder="设置实例登录密码" />
          </Form.Item>

          {estimatedPrice > 0 && (
            <Card size="small" style={{ marginBottom: 16, background: '#f0f8ff' }}>
              <Row justify="center" align="middle">
                <Col>
                  <Statistic
                    title="费用估算"
                    value={estimatedPrice}
                    precision={2}
                    prefix="¥"
                    suffix={cloudForm.getFieldValue('billingType') === 'prepaid' ? '总费用' : '/小时'}
                    valueStyle={{ color: '#1890ff', fontSize: 28 }}
                  />
                </Col>
              </Row>
            </Card>
          )}

          <Form.Item>
            <Button type="primary" htmlType="submit" size="large" block icon={<CloudDownloadOutlined />}>
              立即购买
            </Button>
          </Form.Item>
        </Form>
      </Modal>

      <Modal
        title={<Space><GlobalOutlined />创建WEB远程会话</Space>}
        open={webRemoteModalVisible}
        onCancel={() => setWebRemoteModalVisible(false)}
        footer={null}
      >
        <Form form={webRemoteForm} onFinish={async (values) => {
          try {
            await cloudService.createRemoteSession('web-session', values.platform, 'local', 'admin');
            message.success('WEB远程会话创建成功');
            setWebRemoteModalVisible(false);
            webRemoteForm.resetFields();
            await loadClientStatus();
          } catch (error) {
            message.error('创建WEB远程会话失败');
          }
        }} layout="vertical">
          <Form.Item name="platform" label="目标平台" rules={[{ required: true }]}>
            <Select placeholder="请选择平台">
              <Option value="tiktok">TikTok</Option>
              <Option value="shopee">Shopee</Option>
              <Option value="amazon">Amazon</Option>
            </Select>
          </Form.Item>
          <Form.Item name="url" label="起始URL" rules={[{ required: true }]}>
            <Input placeholder="请输入起始URL" />
          </Form.Item>
          <Form.Item name="userAgent" label="User Agent">
            <Input placeholder="自定义User Agent（可选）" />
          </Form.Item>
          <Form.Item>
            <Button type="primary" htmlType="submit" block>
              创建会话
            </Button>
          </Form.Item>
        </Form>
      </Modal>

      <Modal
        title={<Space><CloudServerOutlined />实例详情 - {selectedInstance?.name}</Space>}
        open={instanceDetailModalVisible}
        onCancel={() => {
          setInstanceDetailModalVisible(false);
          setSelectedInstance(null);
          setInstanceMetrics(null);
        }}
        width={800}
        footer={[
          <Button key="close" onClick={() => setInstanceDetailModalVisible(false)}>
            关闭
          </Button>
        ]}
      >
        {selectedInstance && (
          <Descriptions bordered column={2}>
            <Descriptions.Item label="实例ID">{selectedInstance.id}</Descriptions.Item>
            <Descriptions.Item label="实例名称">{selectedInstance.name}</Descriptions.Item>
            <Descriptions.Item label="云服务商">{selectedInstance.provider}</Descriptions.Item>
            <Descriptions.Item label="地域">{selectedInstance.region}</Descriptions.Item>
            <Descriptions.Item label="状态">
              <Tag color={statusColor(selectedInstance.status)}>{selectedInstance.status}</Tag>
            </Descriptions.Item>
            <Descriptions.Item label="IP地址">{selectedInstance.ipAddress || '未分配'}</Descriptions.Item>
            <Descriptions.Item label="实例类型">{selectedInstance.instanceType}</Descriptions.Item>
            <Descriptions.Item label="创建时间">{selectedInstance.createdTime}</Descriptions.Item>
            <Descriptions.Item label="过期时间">{selectedInstance.expiredTime || '按需计费'}</Descriptions.Item>
          </Descriptions>
        )}
        
        {instanceMetrics && (
          <Card title="监控指标" style={{ marginTop: 16 }}>
            <Row gutter={16}>
              <Col span={6}>
                <Statistic title="CPU使用率" value={instanceMetrics.cpu} suffix="%" />
              </Col>
              <Col span={6}>
                <Statistic title="内存使用率" value={instanceMetrics.memory} suffix="%" />
              </Col>
              <Col span={6}>
                <Statistic title="磁盘使用率" value={instanceMetrics.disk} suffix="%" />
              </Col>
              <Col span={6}>
                <Statistic title="网络入流量" value={instanceMetrics.networkIn} suffix="KB/s" />
              </Col>
            </Row>
          </Card>
        )}
      </Modal>

      <Drawer
        title="客户端配置"
        placement="right"
        onClose={() => setConfigDrawerVisible(false)}
        open={configDrawerVisible}
        width={400}
      >
        <Alert
          message="配置说明"
          description="客户端配置将影响所有平台操作的行为"
          type="info"
          showIcon
          style={{ marginBottom: 16 }}
        />
        <Form layout="vertical">
          <Form.Item label="代理设置">
            <Switch checkedChildren="启用" unCheckedChildren="禁用" />
          </Form.Item>
          <Form.Item label="指纹保护">
            <Switch defaultChecked checkedChildren="启用" unCheckedChildren="禁用" />
          </Form.Item>
          <Form.Item label="时区">
            <Select defaultValue="Asia/Shanghai" style={{ width: '100%' }}>
              <Option value="Asia/Shanghai">Asia/Shanghai (UTC+8)</Option>
              <Option value="America/New_York">America/New_York (UTC-5)</Option>
              <Option value="Europe/London">Europe/London (UTC+0)</Option>
            </Select>
          </Form.Item>
          <Form.Item label="语言">
            <Select defaultValue="zh-CN" style={{ width: '100%' }}>
              <Option value="zh-CN">简体中文</Option>
              <Option value="en-US">English (US)</Option>
              <Option value="ja-JP">日本語</Option>
            </Select>
          </Form.Item>
        </Form>
      </Drawer>

      <Drawer
        title={`任务详情 - ${selectedTask?.name}`}
        placement="right"
        onClose={() => setTaskDetailDrawerVisible(false)}
        open={taskDetailDrawerVisible}
        width={500}
      >
        {selectedTask && (
          <div>
            <Descriptions column={1} bordered>
              <Descriptions.Item label="任务ID">{selectedTask.id}</Descriptions.Item>
              <Descriptions.Item label="任务名称">{selectedTask.name}</Descriptions.Item>
              <Descriptions.Item label="描述">{selectedTask.description}</Descriptions.Item>
              <Descriptions.Item label="平台">{selectedTask.platform}</Descriptions.Item>
              <Descriptions.Item label="类型">{selectedTask.type}</Descriptions.Item>
              <Descriptions.Item label="调度规则">{selectedTask.schedule}</Descriptions.Item>
              <Descriptions.Item label="状态">
                <Tag color={statusColor(selectedTask.status)}>{selectedTask.status}</Tag>
              </Descriptions.Item>
              <Descriptions.Item label="上次执行">{selectedTask.lastRun || '-'}</Descriptions.Item>
              <Descriptions.Item label="下次执行">{selectedTask.nextRun || '-'}</Descriptions.Item>
              <Descriptions.Item label="成功次数">{selectedTask.successCount || 0}</Descriptions.Item>
              <Descriptions.Item label="失败次数">{selectedTask.errorCount || 0}</Descriptions.Item>
            </Descriptions>
            
            {selectedTask.status === 'running' && (
              <Card title="执行进度" style={{ marginTop: 16 }}>
                <Progress percent={selectedTask.progress} status="active" />
              </Card>
            )}
          </div>
        )}
      </Drawer>

      <Drawer
        title={`客户端详情 - ${selectedClient?.name}`}
        placement="right"
        onClose={() => setClientDetailDrawerVisible(false)}
        open={clientDetailDrawerVisible}
        width={600}
      >
        {selectedClient && (
          <div>
            <Descriptions column={2} bordered>
              <Descriptions.Item label="客户端ID">{selectedClient.id}</Descriptions.Item>
              <Descriptions.Item label="名称">{selectedClient.name}</Descriptions.Item>
              <Descriptions.Item label="IP地址">{selectedClient.ip}</Descriptions.Item>
              <Descriptions.Item label="端口">{selectedClient.port}</Descriptions.Item>
              <Descriptions.Item label="状态">
                <Tag color={selectedClient.status === 'online' ? 'green' : selectedClient.status === 'offline' ? 'orange' : 'red'}>
                  {selectedClient.status === 'online' ? '在线' : selectedClient.status === 'offline' ? '离线' : '异常'}
                </Tag>
              </Descriptions.Item>
              <Descriptions.Item label="平台">{selectedClient.platform}</Descriptions.Item>
              <Descriptions.Item label="版本">{selectedClient.version}</Descriptions.Item>
              <Descriptions.Item label="运行时间">
                {selectedClient.uptime > 0 ? `${Math.floor(selectedClient.uptime / 3600)}小时 ${Math.floor((selectedClient.uptime % 3600) / 60)}分钟` : '-'}
              </Descriptions.Item>
              <Descriptions.Item label="区域">{selectedClient.region}</Descriptions.Item>
              <Descriptions.Item label="分组">{selectedClient.group}</Descriptions.Item>
            </Descriptions>

            <Card title="资源使用情况" style={{ marginTop: 16 }}>
              <Row gutter={16}>
                <Col span={8}>
                  <Card>
                    <Statistic 
                      title="CPU使用率" 
                      value={selectedClient.cpu} 
                      suffix="%" 
                      valueStyle={{ color: selectedClient.cpu > 80 ? '#ff4d4f' : '#52c41a' }} 
                    />
                    <Progress percent={selectedClient.cpu} status={selectedClient.cpu > 80 ? 'exception' : 'normal'} />
                  </Card>
                </Col>
                <Col span={8}>
                  <Card>
                    <Statistic 
                      title="内存使用率" 
                      value={selectedClient.memory} 
                      suffix="%" 
                      valueStyle={{ color: selectedClient.memory > 80 ? '#ff4d4f' : '#52c41a' }} 
                    />
                    <Progress percent={selectedClient.memory} status={selectedClient.memory > 80 ? 'exception' : 'normal'} />
                  </Card>
                </Col>
                <Col span={8}>
                  <Card>
                    <Statistic 
                      title="磁盘使用率" 
                      value={selectedClient.disk} 
                      suffix="%" 
                      valueStyle={{ color: selectedClient.disk > 80 ? '#ff4d4f' : '#52c41a' }} 
                    />
                    <Progress percent={selectedClient.disk} status={selectedClient.disk > 80 ? 'exception' : 'normal'} />
                  </Card>
                </Col>
              </Row>
            </Card>

            <Card title="运行信息" style={{ marginTop: 16 }}>
              <Row gutter={16}>
                <Col span={8}>
                  <Statistic title="任务数量" value={selectedClient.tasks} prefix={<ScheduleOutlined />} />
                </Col>
                <Col span={8}>
                  <Statistic title="平台数量" value={selectedClient.platforms} prefix={<ShopOutlined />} />
                </Col>
                <Col span={8}>
                  <Statistic title="最后活跃" value={new Date(selectedClient.lastSeen).toLocaleString()} prefix={<ClockCircleOutlined />} />
                </Col>
              </Row>
            </Card>

            <Card title="标签" style={{ marginTop: 16 }}>
              <Space wrap>
                {selectedClient.tags.map((tag, index) => (
                  <Tag key={index}>{tag}</Tag>
                ))}
              </Space>
            </Card>

            <Card title="操作" style={{ marginTop: 16 }}>
              <Space>
                {selectedClient.status !== 'online' && (
                  <Button 
                    type="primary" 
                    icon={<PlayCircleOutlined />}
                    onClick={() => connectToClientById(selectedClient.id)}
                  >
                    连接
                  </Button>
                )}
                {selectedClient.status === 'online' && (
                  <Button 
                    icon={<PauseCircleOutlined />}
                    onClick={() => disconnectFromClient(selectedClient.id)}
                  >
                    断开连接
                  </Button>
                )}
                <Button 
                  icon={<ReloadOutlined />}
                  onClick={() => batchRestart()}
                >
                  重启
                </Button>
                <Button 
                  icon={<SettingOutlined />}
                  onClick={() => message.info('客户端配置功能开发中')}
                >
                  配置
                </Button>
              </Space>
            </Card>
          </div>
        )}
      </Drawer>

      <Modal
        title="添加客户端组"
        open={clientGroupModalVisible}
        onCancel={() => setClientGroupModalVisible(false)}
        footer={null}
      >
        <Form form={groupForm} onFinish={createClientGroup} layout="vertical">
          <Form.Item name="name" label="组名称" rules={[{ required: true, message: '请输入组名称' }]}>
            <Input placeholder="例如：生产组" />
          </Form.Item>
          <Form.Item name="description" label="组描述">
            <Input.TextArea rows={3} placeholder="请输入组描述" />
          </Form.Item>
          <Form.Item name="color" label="组颜色">
            <Select defaultValue="#1890ff">
              <Option value="#1890ff">蓝色</Option>
              <Option value="#52c41a">绿色</Option>
              <Option value="#faad14">黄色</Option>
              <Option value="#ff4d4f">红色</Option>
              <Option value="#722ed1">紫色</Option>
            </Select>
          </Form.Item>
          <Form.Item>
            <Button type="primary" htmlType="submit" block>
              创建客户端组
            </Button>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

const OperationAgentEnhanced = memo(OperationAgentEnhancedBase);
OperationAgentEnhanced.displayName = 'OperationAgentEnhanced';

export default OperationAgentEnhanced;
