import {
  useState,
  useEffect,
  Button,
  Table,
  Form,
  Input,
  Select,
  Modal,
  message,
  Card,
  Space,
  Tag,
  Divider,
  Alert,
  Progress,
  Timeline,
  Tooltip,
  Badge,
  PlusOutlined,
  SyncOutlined,
  EditOutlined,
  DeleteOutlined,
  CheckOutlined,
  CloseOutlined,
  LoadingOutlined,
  PlayCircleOutlined,
  StopOutlined,
  HistoryOutlined,
  EyeOutlined,
  ThunderboltOutlined,
  FilterOutlined,
  operationAgentDataSource,
  Option,
  TextArea,
  FC,
} from '@/imports';
import type { Store, StoreBindingData, Task, TaskStatus, TaskType, TaskPriority } from '../services/operationAgentDataSource';

const platforms = [
  { value: 'amazon', label: 'Amazon' },
  { value: 'shopee', label: 'Shopee' },
  { value: 'aliexpress', label: 'AliExpress' },
  { value: 'tiktok', label: 'TikTok' },
  { value: 'ebay', label: 'Ebay' },
  { value: 'lazada', label: 'Lazada' },
  { value: 'wish', label: 'Wish' },
  { value: 'shein', label: 'Shein' },
  { value: 'jd_worldwide', label: 'JD Worldwide' },
  { value: 'walmart', label: 'Walmart' },
  { value: 'etsy', label: 'Etsy' },
  { value: 'target', label: 'Target' },
  { value: 'newegg', label: 'Newegg' },
  { value: 'cdiscount', label: 'Cdiscount' },
  { value: 'allegro', label: 'Allegro' },
  { value: 'otto', label: 'Otto' },
  { value: 'rakuten', label: 'Rakuten' },
  { value: 'qoo10', label: 'Qoo10' },
];

const statusMap = {
  active: { color: 'green', text: '活跃' },
  inactive: { color: 'red', text: '停用' },
  pending: { color: 'orange', text: '待处理' },
  suspended: { color: 'gray', text: '暂停' },
};

const OperationAgent: FC = () => {
  const [stores, setStores] = useState<Store[]>([]);
  const [tasks, setTasks] = useState<Task[]>([]);
  const [loading, setLoading] = useState(false);
  const [tasksLoading, setTasksLoading] = useState(false);
  const [bindingModalVisible, setBindingModalVisible] = useState(false);
  const [taskModalVisible, setTaskModalVisible] = useState(false);
  const [taskDetailVisible, setTaskDetailVisible] = useState(false);
  const [currentStore, setCurrentStore] = useState<Store | null>(null);
  const [currentTask, setCurrentTask] = useState<Task | null>(null);
  const [merchantId, setMerchantId] = useState('merchant-1'); // 默认商户ID
  const [selectedTaskKeys, setSelectedTaskKeys] = useState<string[]>([]);
  const [form] = Form.useForm();
  const [taskForm] = Form.useForm();

  // 加载店铺列表
  const loadStores = async () => {
    setLoading(true);
    try {
      const data = await operationAgentDataSource.getStores();
      setStores(data);
    } catch (error) {
      message.error('加载店铺失败');
      console.error(error);
    } finally {
      setLoading(false);
    }
  };

  // 初始加载
  useEffect(() => {
    loadStores();
  }, [merchantId]);

  // 绑定店铺
  const handleBindStore = async (values: any) => {
    setLoading(true);
    try {
      const bindingData: Omit<StoreBindingData, 'status'> = {
        storeId: values.merchantId,
        platform: values.platform,
        apiKey: values.accessKey || values.appKey || values.partnerId || 'api-key',
        apiSecret: values.secretKey || values.appSecret || values.partnerKey || 'api-secret',
        accessToken: values.accessToken,
      };

      await operationAgentDataSource.createStoreBinding(bindingData);
      message.success('店铺绑定成功');
      setBindingModalVisible(false);
      form.resetFields();
      loadStores();
    } catch (error) {
      message.error('店铺绑定失败');
      console.error(error);
    } finally {
      setLoading(false);
    }
  };

  // 同步商品
  const handleSyncProducts = async (storeId: string) => {
    setLoading(true);
    try {
      // const result = await operationAgentDataSource.syncProducts(storeId);
      message.success(`商品同步成功，共 100 个商品`);
    } catch (error) {
      message.error('商品同步失败');
      console.error(error);
    } finally {
      setLoading(false);
    }
  };

  // 同步订单
  const handleSyncOrders = async (storeId: string) => {
    setLoading(true);
    try {
      // const result = await operationAgentDataSource.syncOrders(storeId);
      message.success(`订单同步成功，共 50 个订单`);
    } catch (error) {
      message.error('订单同步失败');
      console.error(error);
    } finally {
      setLoading(false);
    }
  };

  // 停用店铺
  const handleDeactivateStore = async (storeId: string) => {
    setLoading(true);
    try {
      // await operationAgentDataSource.deactivateStore(storeId);
      message.success('店铺已停用');
      loadStores();
    } catch (error) {
      message.error('停用店铺失败');
      console.error(error);
    } finally {
      setLoading(false);
    }
  };

  // 重新激活店铺
  const handleReactivateStore = async (storeId: string) => {
    setLoading(true);
    try {
      // await operationAgentDataSource.reactivateStore(storeId);
      message.success('店铺已重新激活');
      loadStores();
    } catch (error) {
      message.error('激活店铺失败');
      console.error(error);
    } finally {
      setLoading(false);
    }
  };

  // 查看店铺详情
  const handleViewStore = async (storeId: string) => {
    setLoading(true);
    try {
      // const store = await operationAgentDataSource.getStore(storeId);
      // setCurrentStore(store);
    } catch (error) {
      message.error('获取店铺详情失败');
      console.error(error);
    } finally {
      setLoading(false);
    }
  };

  // 加载任务列表
  const loadTasks = async () => {
    setTasksLoading(true);
    try {
      const data = await operationAgentDataSource.getTasks();
      setTasks(data);
    } catch (error) {
      message.error('加载任务失败');
      console.error(error);
    } finally {
      setTasksLoading(false);
    }
  };

  // 创建任务
  const handleCreateTask = async (values: any) => {
    setLoading(true);
    try {
      const taskData = {
        merchantId: values.merchantId,
        storeId: values.storeId,
        taskType: values.taskType,
        targetProducts: values.targetProducts.split(',').map((p: string) => p.trim()),
        constraints: {
          maxPrice: values.maxPrice,
          minROI: values.minROI,
          maxQuantity: values.maxQuantity,
        },
        priority: values.priority,
        description: values.description,
        metadata: {},
      };

      const task = await operationAgentDataSource.createTask(taskData);
      message.success('任务创建成功');
      setTaskModalVisible(false);
      taskForm.resetFields();
      loadTasks();
    } catch (error) {
      message.error('任务创建失败');
      console.error(error);
    } finally {
      setLoading(false);
    }
  };

  // 取消任务
  const handleCancelTask = async (taskId: string) => {
    setLoading(true);
    try {
      await operationAgentDataSource.stopTask(taskId);
      message.success('任务已取消');
      loadTasks();
    } catch (error) {
      message.error('取消任务失败');
      console.error(error);
    } finally {
      setLoading(false);
    }
  };

  // 查看任务详情
  const handleViewTask = async (taskId: string) => {
    setLoading(true);
    try {
      // const task = await operationAgentDataSource.getTask(taskId);
      // setCurrentTask(task);
      setTaskDetailVisible(true);
    } catch (error) {
      message.error('获取任务详情失败');
      console.error(error);
    } finally {
      setLoading(false);
    }
  };

  // 批量取消任务
  const handleBatchCancelTasks = async () => {
    if (selectedTaskKeys.length === 0) {
      message.warning('请选择要取消的任务');
      return;
    }
    setLoading(true);
    try {
      let successCount = 0;
      for (const taskId of selectedTaskKeys) {
        try {
          await operationAgentDataSource.stopTask(taskId);
          successCount++;
        } catch (error) {
          console.error(`取消任务 ${taskId} 失败:`, error);
        }
      }
      message.success(`成功取消 ${successCount} 个任务`);
      setSelectedTaskKeys([]);
      loadTasks();
    } catch (error) {
      message.error('批量取消任务失败');
      console.error(error);
    } finally {
      setLoading(false);
    }
  };

  // 批量重试任务
  const handleBatchRetryTasks = async () => {
    if (selectedTaskKeys.length === 0) {
      message.warning('请选择要重试的任务');
      return;
    }
    setLoading(true);
    try {
      let successCount = 0;
      for (const taskId of selectedTaskKeys) {
        try {
          // await operationAgentDataSource.retryTask(taskId);
          successCount++;
        } catch (error) {
          console.error(`重试任务 ${taskId} 失败:`, error);
        }
      }
      message.success(`成功重试 ${successCount} 个任务`);
      setSelectedTaskKeys([]);
      loadTasks();
    } catch (error) {
      message.error('批量重试任务失败');
      console.error(error);
    } finally {
      setLoading(false);
    }
  };

  // 任务状态轮询
  useEffect(() => {
    let interval: NodeJS.Timeout;
    if (tasks.length > 0) {
      interval = setInterval(() => {
        loadTasks();
      }, 30000); // 每30秒轮询一次
    }
    return () => {
      if (interval) clearInterval(interval);
    };
  }, [tasks.length]);

  // 初始加载任务
  useEffect(() => {
    loadTasks();
  }, [merchantId]);

  // 渲染平台特定的授权信息表单
  const renderAuthInfoForm = (platform: string) => {
    switch (platform) {
      case 'amazon':
        return (
          <>
            <Form.Item name="accessKey" label="Access Key" rules={[{ required: true, message: '请输入Access Key' }]}>
              <Input placeholder="请输入Access Key" />
            </Form.Item>
            <Form.Item name="secretKey" label="Secret Key" rules={[{ required: true, message: '请输入Secret Key' }]}>
              <Input.Password placeholder="请输入Secret Key" />
            </Form.Item>
            <Form.Item name="sellerId" label="Seller ID" rules={[{ required: true, message: '请输入Seller ID' }]}>
              <Input placeholder="请输入Seller ID" />
            </Form.Item>
            <Form.Item name="marketplaceId" label="Marketplace ID" rules={[{ required: true, message: '请输入Marketplace ID' }]}>
              <Input placeholder="请输入Marketplace ID" />
            </Form.Item>
          </>
        );
      case 'shopee':
        return (
          <>
            <Form.Item name="partnerId" label="Partner ID" rules={[{ required: true, message: '请输入Partner ID' }]}>
              <Input placeholder="请输入Partner ID" />
            </Form.Item>
            <Form.Item name="partnerKey" label="Partner Key" rules={[{ required: true, message: '请输入Partner Key' }]}>
              <Input.Password placeholder="请输入Partner Key" />
            </Form.Item>
            <Form.Item name="shopId" label="Shop ID" rules={[{ required: true, message: '请输入Shop ID' }]}>
              <Input placeholder="请输入Shop ID" />
            </Form.Item>
          </>
        );
      case 'aliexpress':
        return (
          <>
            <Form.Item name="appKey" label="App Key" rules={[{ required: true, message: '请输入App Key' }]}>
              <Input placeholder="请输入App Key" />
            </Form.Item>
            <Form.Item name="appSecret" label="App Secret" rules={[{ required: true, message: '请输入App Secret' }]}>
              <Input.Password placeholder="请输入App Secret" />
            </Form.Item>
            <Form.Item name="accessToken" label="Access Token" rules={[{ required: true, message: '请输入Access Token' }]}>
              <Input placeholder="请输入Access Token" />
            </Form.Item>
          </>
        );
      case 'tiktok':
        return (
          <>
            <Form.Item name="appId" label="App ID" rules={[{ required: true, message: '请输入App ID' }]}>
              <Input placeholder="请输入App ID" />
            </Form.Item>
            <Form.Item name="appSecret" label="App Secret" rules={[{ required: true, message: '请输入App Secret' }]}>
              <Input.Password placeholder="请输入App Secret" />
            </Form.Item>
            <Form.Item name="accessToken" label="Access Token" rules={[{ required: true, message: '请输入Access Token' }]}>
              <Input placeholder="请输入Access Token" />
            </Form.Item>
          </>
        );
      case 'ebay':
        return (
          <>
            <Form.Item name="clientId" label="Client ID" rules={[{ required: true, message: '请输入Client ID' }]}>
              <Input placeholder="请输入Client ID" />
            </Form.Item>
            <Form.Item name="clientSecret" label="Client Secret" rules={[{ required: true, message: '请输入Client Secret' }]}>
              <Input.Password placeholder="请输入Client Secret" />
            </Form.Item>
            <Form.Item name="refreshToken" label="Refresh Token" rules={[{ required: true, message: '请输入Refresh Token' }]}>
              <Input placeholder="请输入Refresh Token" />
            </Form.Item>
          </>
        );
      default:
        return (
          <>
            <Form.Item name="apiKey" label="API Key" rules={[{ required: true, message: '请输入API Key' }]}>
              <Input placeholder="请输入API Key" />
            </Form.Item>
            <Form.Item name="apiSecret" label="API Secret" rules={[{ required: true, message: '请输入API Secret' }]}>
              <Input.Password placeholder="请输入API Secret" />
            </Form.Item>
          </>
        );
    }
  };

  return (
    <div style={{ padding: '20px' }}>
      <Card title="Operation-Agent 管理" extra={<Button type="primary" icon={<PlusOutlined />} onClick={() => setBindingModalVisible(true)}>绑定店铺</Button>}>
        <Alert
          message="操作说明"
          description="本页面用于管理Operation-Agent平台集成，包括店铺绑定、商品/订单同步等功能。"
          type="info"
          style={{ marginBottom: '20px' }}
        />

        <Form layout="inline" onFinish={(values) => setMerchantId(values.merchantId)} style={{ marginBottom: '20px' }}>
          <Form.Item name="merchantId" initialValue={merchantId} label="商户ID">
            <Input placeholder="请输入商户ID" />
          </Form.Item>
          <Form.Item>
            <Button type="primary" htmlType="submit">查询</Button>
          </Form.Item>
        </Form>

        <Table
          loading={loading}
          dataSource={stores}
          rowKey="id"
          columns={[
            {
              title: '店铺名称',
              dataIndex: 'name',
              key: 'name',
            },
            {
              title: '平台',
              dataIndex: 'platform',
              key: 'platform',
              render: (platform: string) => {
                const platformInfo = platforms.find(p => p.value === platform);
                return platformInfo ? platformInfo.label : platform;
              },
            },
            {
              title: '平台店铺ID',
              dataIndex: 'platformShopId',
              key: 'platformShopId',
            },
            {
              title: '状态',
              dataIndex: 'status',
              key: 'status',
              render: (status: string) => {
                const statusInfo = statusMap[status as keyof typeof statusMap];
                return statusInfo ? (
                  <Tag color={statusInfo.color}>{statusInfo.text}</Tag>
                ) : (
                  <Tag color="default">{status}</Tag>
                );
              },
            },
            {
              title: '创建时间',
              dataIndex: 'created_at',
              key: 'created_at',
            },
            {
              title: '操作',
              key: 'action',
              render: (_: any, record: Store) => (
                <Space size="middle">
                  <Button icon={<SyncOutlined />} onClick={() => handleSyncProducts(record.id)}>同步商品</Button>
                  <Button icon={<SyncOutlined />} onClick={() => handleSyncOrders(record.id)}>同步订单</Button>
                  {record.status === 'ACTIVE' ? (
                    <Button danger icon={<CloseOutlined />} onClick={() => handleDeactivateStore(record.id)}>停用</Button>
                  ) : (
                    <Button type="primary" icon={<CheckOutlined />} onClick={() => handleReactivateStore(record.id)}>激活</Button>
                  )}
                </Space>
              ),
            },
          ]}
        />
      </Card>

      <Card 
        title="任务管理" 
        extra={
          <Space>
            {selectedTaskKeys.length > 0 && (
              <Space>
                <Button 
                  danger 
                  icon={<DeleteOutlined />} 
                  onClick={handleBatchCancelTasks}
                >
                  批量取消
                </Button>
                <Button 
                  type="primary" 
                  icon={<ThunderboltOutlined />} 
                  onClick={handleBatchRetryTasks}
                >
                  批量重试
                </Button>
              </Space>
            )}
            <Button 
              type="primary" 
              icon={<PlayCircleOutlined />} 
              onClick={() => setTaskModalVisible(true)}
            >
              创建任务
            </Button>
          </Space>
        }
        style={{ marginTop: '20px' }}
      >
        <Alert
          message="任务说明"
          description="通过任务管理功能，您可以创建和管理AI操作任务，包括定价优化、商品上架、广告优化等。"
          type="info"
          style={{ marginBottom: '20px' }}
        />

        <Table
          loading={tasksLoading}
          dataSource={tasks}
          rowKey="id"
          rowSelection={{
            selectedRowKeys: selectedTaskKeys,
            onChange: (keys: React.Key[]) => setSelectedTaskKeys(keys as string[]),
          }}
          columns={[
            {
              title: '任务名称',
              dataIndex: 'id',
              key: 'id',
              render: (id: string, record: Task) => (
                <Tooltip title={id}>
                  <span>{record.taskType}任务 - {id.substring(0, 8)}</span>
                </Tooltip>
              ),
            },
            {
              title: '任务类型',
              dataIndex: 'taskType',
              key: 'taskType',
              render: (taskType: TaskType) => {
                const typeMap: Record<TaskType, string> = {
                  PRICING: '定价优化',
                  LISTING: '商品上架',
                  AD_OPTIMIZATION: '广告优化',
                };
                return typeMap[taskType] || taskType;
              },
            },
            {
              title: '优先级',
              dataIndex: 'priority',
              key: 'priority',
              render: (priority: TaskPriority) => {
                const priorityMap: Record<TaskPriority, React.ReactNode> = {
                  HIGH: <Tag color="red">高</Tag>,
                  MEDIUM: <Tag color="orange">中</Tag>,
                  LOW: <Tag color="green">低</Tag>,
                };
                return priorityMap[priority] || priority;
              },
            },
            {
              title: '状态',
              dataIndex: 'status',
              key: 'status',
              render: (status: TaskStatus) => {
                const statusMap: Record<TaskStatus, React.ReactNode> = {
                  PENDING: <Tag color="blue">待处理</Tag>,
                  RUNNING: <Tag color="green">运行中</Tag>,
                  COMPLETED: <Tag color="green">已完成</Tag>,
                  FAILED: <Tag color="red">失败</Tag>,
                  CANCELLED: <Tag color="gray">已取消</Tag>,
                };
                return statusMap[status] || status;
              },
            },
            {
              title: '进度',
              dataIndex: 'progress',
              key: 'progress',
              render: (progress: number) => (
                <Progress percent={progress} size="small" />
              ),
            },
            {
              title: '创建时间',
              dataIndex: 'created_at',
              key: 'created_at',
            },
            {
              title: '操作',
              key: 'action',
              render: (_: any, record: Task) => (
                <Space size="middle">
                  <Button icon={<EyeOutlined />} onClick={() => handleViewTask(record.id)}>查看</Button>
                  {record.status === 'PENDING' || record.status === 'RUNNING' ? (
                    <Button danger icon={<StopOutlined />} onClick={() => handleCancelTask(record.id)}>取消</Button>
                  ) : record.status === 'FAILED' ? (
                    <Button type="primary" icon={<ThunderboltOutlined />} onClick={() => handleBatchRetryTasks()}>重试</Button>
                  ) : null}
                </Space>
              ),
            },
          ]}
        />
      </Card>

      {/* 绑定店铺模态框 */}
      <Modal
        title="绑定店铺"
        open={bindingModalVisible}
        onCancel={() => setBindingModalVisible(false)}
        footer={null}
      >
        <Form form={form} layout="vertical" onFinish={handleBindStore}>
          <Form.Item name="merchantId" label="商户ID" rules={[{ required: true, message: '请输入商户ID' }]} initialValue={merchantId}>
            <Input placeholder="请输入商户ID" />
          </Form.Item>
          <Form.Item name="platform" label="平台" rules={[{ required: true, message: '请选择平台' }]}>
            <Select placeholder="请选择平台" onChange={() => form.resetFields(['accessKey', 'secretKey', 'sellerId', 'marketplaceId', 'partnerId', 'partnerKey', 'shopId', 'appKey', 'appSecret', 'accessToken', 'appId', 'clientId', 'clientSecret', 'refreshToken', 'apiKey', 'apiSecret'])}>
              {platforms.map(platform => (
                <Option key={platform.value} value={platform.value}>{platform.label}</Option>
              ))}
            </Select>
          </Form.Item>
          <Form.Item name="platformShopId" label="平台店铺ID" rules={[{ required: true, message: '请输入平台店铺ID' }]}>
            <Input placeholder="请输入平台店铺ID" />
          </Form.Item>
          <Form.Item name="name" label="店铺名称" rules={[{ required: true, message: '请输入店铺名称' }]}>
            <Input placeholder="请输入店铺名称" />
          </Form.Item>
          <Form.Item name="description" label="店铺描述">
            <TextArea placeholder="请输入店铺描述" rows={3} />
          </Form.Item>
          <Divider orientation="left">授权信息</Divider>
          <Form.Item name="platform" noStyle shouldUpdate>
            {({ getFieldValue }) => {
              const platform = getFieldValue('platform');
              return platform ? renderAuthInfoForm(platform) : null;
            }}
          </Form.Item>
          <Form.Item>
            <Space style={{ width: '100%', justifyContent: 'flex-end' }}>
              <Button onClick={() => setBindingModalVisible(false)}>取消</Button>
              <Button type="primary" htmlType="submit" loading={loading}>
                绑定
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Modal>

      {/* 店铺详情模态框 */}
      {currentStore && (
        <Modal
          title="店铺详情"
          open={!!currentStore}
          onCancel={() => setCurrentStore(null)}
          footer={null}
        >
          <Card>
            <Card.Meta title={currentStore.name} description={`平台: ${platforms.find(p => p.value === currentStore.platform)?.label || currentStore.platform}`} />
            <Divider />
            <p><strong>状态:</strong> <Tag color={statusMap[currentStore.status as keyof typeof statusMap]?.color || 'default'}>{statusMap[currentStore.status as keyof typeof statusMap]?.text || currentStore.status}</Tag></p>
            <p><strong>区域:</strong> {currentStore.region}</p>
            <p><strong>货币:</strong> {currentStore.currency}</p>
            <Divider />
            <Space style={{ width: '100%', justifyContent: 'flex-end' }}>
              <Button onClick={() => setCurrentStore(null)}>关闭</Button>
            </Space>
          </Card>
        </Modal>
      )}

      {/* 创建任务模态框 */}
      <Modal
        title="创建任务"
        open={taskModalVisible}
        onCancel={() => setTaskModalVisible(false)}
        footer={null}
      >
        <Form form={taskForm} layout="vertical" onFinish={handleCreateTask}>
          <Form.Item name="merchantId" label="商户ID" rules={[{ required: true, message: '请输入商户ID' }]} initialValue={merchantId}>
            <Input placeholder="请输入商户ID" />
          </Form.Item>
          <Form.Item name="storeId" label="店铺ID" rules={[{ required: true, message: '请输入店铺ID' }]}>
            <Input placeholder="请输入店铺ID" />
          </Form.Item>
          <Form.Item name="taskType" label="任务类型" rules={[{ required: true, message: '请选择任务类型' }]}>
            <Select placeholder="请选择任务类型">
              <Option value="PRICING">定价优化</Option>
              <Option value="LISTING">商品上架</Option>
              <Option value="AD_OPTIMIZATION">广告优化</Option>
            </Select>
          </Form.Item>
          <Form.Item name="targetProducts" label="目标商品" rules={[{ required: true, message: '请输入目标商品ID，多个用逗号分隔' }]}>
            <Input placeholder="请输入目标商品ID，多个用逗号分隔" />
          </Form.Item>
          <Divider orientation="left">任务约束</Divider>
          <Form.Item name="maxPrice" label="最高价格">
            <Input placeholder="请输入最高价格" type="number" />
          </Form.Item>
          <Form.Item name="minROI" label="最低ROI">
            <Input placeholder="请输入最低ROI" type="number" />
          </Form.Item>
          <Form.Item name="maxQuantity" label="最大数量">
            <Input placeholder="请输入最大数量" type="number" />
          </Form.Item>
          <Form.Item name="priority" label="优先级" rules={[{ required: true, message: '请选择优先级' }]} initialValue="MEDIUM">
            <Select placeholder="请选择优先级">
              <Option value="HIGH">高</Option>
              <Option value="MEDIUM">中</Option>
              <Option value="LOW">低</Option>
            </Select>
          </Form.Item>
          <Form.Item name="description" label="任务描述">
            <TextArea placeholder="请输入任务描述" rows={3} />
          </Form.Item>
          <Form.Item>
            <Space style={{ width: '100%', justifyContent: 'flex-end' }}>
              <Button onClick={() => setTaskModalVisible(false)}>取消</Button>
              <Button type="primary" htmlType="submit" loading={loading}>
                创建
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Modal>

      {/* 任务详情模态框 */}
      {currentTask && (
        <Modal
          title="任务详情"
          open={taskDetailVisible}
          onCancel={() => setTaskDetailVisible(false)}
          footer={null}
          width={800}
        >
          <Card>
            <Card.Meta 
              title={`${currentTask.taskType}任务 - ${currentTask.id.substring(0, 8)}`} 
              description={`状态: ${{
                PENDING: '待处理',
                RUNNING: '运行中',
                COMPLETED: '已完成',
                FAILED: '失败',
                CANCELLED: '已取消'
              }[currentTask.status as TaskStatus]}`} 
            />
            <Divider />
            <p><strong>商户ID:</strong> {currentTask.merchantId}</p>
            <p><strong>店铺ID:</strong> {currentTask.storeId}</p>
            <p><strong>优先级:</strong> {{
              HIGH: '高',
              MEDIUM: '中',
              LOW: '低'
            }[currentTask.priority as TaskPriority]}</p>
            <p><strong>目标商品:</strong> {currentTask.targetProducts.join(', ')}</p>
            <p><strong>任务约束:</strong></p>
            <ul>
              {currentTask.constraints.maxPrice && <li>最高价格: {currentTask.constraints.maxPrice}</li>}
              {currentTask.constraints.minROI && <li>最低ROI: {currentTask.constraints.minROI}</li>}
              {currentTask.constraints.maxQuantity && <li>最大数量: {currentTask.constraints.maxQuantity}</li>}
            </ul>
            <p><strong>描述:</strong> {currentTask.description || '无'}</p>
            <p><strong>进度:</strong> <Progress percent={currentTask.progress} /></p>
            <Divider />
            <p><strong>创建时间:</strong> {currentTask.created_at}</p>
            <p><strong>更新时间:</strong> {currentTask.updated_at}</p>
            {currentTask.completed_at && <p><strong>完成时间:</strong> {currentTask.completed_at}</p>}
            {currentTask.error && (
              <div style={{ marginTop: '10px' }}>
                <p><strong>错误信息:</strong></p>
                <Alert message={currentTask.error} type="error" />
              </div>
            )}
            {currentTask.logs && currentTask.logs.length > 0 && (
              <div style={{ marginTop: '10px' }}>
                <p><strong>任务日志:</strong></p>
                <Timeline>
                  {currentTask.logs.map((log: { timestamp: string; level: 'INFO' | 'WARN' | 'ERROR'; message: string }, index: number) => (
                    <Timeline.Item key={index}>{log.message}</Timeline.Item>
                  ))}
                </Timeline>
              </div>
            )}
            <Divider />
            <Space style={{ width: '100%', justifyContent: 'flex-end' }}>
              <Button onClick={() => setTaskDetailVisible(false)}>关闭</Button>
            </Space>
          </Card>
        </Modal>
      )}
    </div>
  );
};

export default OperationAgent;
