/**
 * [FE-SELECT001] 自动选品+自动上架系统前端页面
 * 使用DataSource抽象层获取数据，符合项目Mock规范
 * 
 * @module pages/AutoProductSelection
 * @author AI-Frontend-33
 * @created 2026-03-20
 */

import React, { useState, useEffect, useCallback } from 'react';
import {
  Card,
  Row,
  Col,
  Table,
  Button,
  Space,
  Tag,
  Input,
  Select,
  Slider,
  Switch,
  Form,
  Modal,
  message,
  Tooltip,
  Badge,
  Tabs,
  Alert,
  Statistic,
  Progress,
  Typography,
  Divider,
  Popconfirm,
  InputNumber,
  DatePicker,
  Checkbox,
  Empty,
} from 'antd';
import {
  ShoppingOutlined,
  DollarOutlined,
  ThunderboltOutlined,
  SettingOutlined,
  PlayCircleOutlined,
  PauseCircleOutlined,
  ReloadOutlined,
  CheckCircleOutlined,
  ClockCircleOutlined,
  ArrowUpOutlined,
  ArrowDownOutlined,
  FilterOutlined,
  StarOutlined,
  EyeOutlined,
  DeleteOutlined,
  SyncOutlined,
  BarChartOutlined,
  TrendingUpOutlined,
  FireOutlined,
  RobotOutlined,
  AlertOutlined,
  InfoCircleOutlined,
  PlusOutlined,
} from '@ant-design/icons';
import type { ColumnsType } from 'antd/es/table';
import moment from 'moment';
import {
  productSelectionDataSource,
  ProductPoolQueryParams,
  SelectionRuleQueryParams,
  ListingTaskQueryParams,
} from '@/services/productSelectionDataSource';
import type {
  ProductPool,
  SelectionRule,
  ListingTask,
  AutoListingConfig,
} from '@/mock/data/productSelection.mock';

const { Title, Text } = Typography;
const { TabPane } = Tabs;
const { Option } = Select;

const COMPETITION_CONFIG = {
  LOW: { color: 'success', text: '低' },
  MEDIUM: { color: 'warning', text: '中' },
  HIGH: { color: 'error', text: '高' },
};

const TREND_CONFIG = {
  UP: { icon: <ArrowUpOutlined />, color: 'success', text: '上升' },
  DOWN: { icon: <ArrowDownOutlined />, color: 'error', text: '下降' },
  STABLE: { icon: <ClockCircleOutlined />, color: 'default', text: '稳定' },
};

const AutoProductSelection: React.FC = () => {
  const [activeTab, setActiveTab] = useState('pool');
  const [loading, setLoading] = useState(false);
  const [productPool, setProductPool] = useState<ProductPool[]>([]);
  const [selectionRules, setSelectionRules] = useState<SelectionRule[]>([]);
  const [listingTasks, setListingTasks] = useState<ListingTask[]>([]);
  const [autoListingConfig, setAutoListingConfig] = useState<AutoListingConfig | null>(null);
  const [categories, setCategories] = useState<string[]>([]);
  const [platforms, setPlatforms] = useState<string[]>([]);
  const [selectionStats, setSelectionStats] = useState<{
    totalPool: number;
    avgROI: number;
    lowCompetition: number;
    upTrend: number;
  } | null>(null);
  const [listingStats, setListingStats] = useState<{
    totalTasks: number;
    pendingTasks: number;
    processingTasks: number;
    completedTasks: number;
    failedTasks: number;
  } | null>(null);

  const [ruleModalVisible, setRuleModalVisible] = useState(false);
  const [configModalVisible, setConfigModalVisible] = useState(false);
  const [selectedProduct, setSelectedProduct] = useState<ProductPool | null>(null);
  const [productDetailVisible, setProductDetailVisible] = useState(false);
  const [ruleForm] = Form.useForm();
  const [configForm] = Form.useForm();

  const [filters, setFilters] = useState({
    keyword: '',
    category: '',
    minROI: 0,
    maxROI: 100,
    competitionLevel: '',
    trend: '',
  });

  const fetchData = useCallback(async () => {
    setLoading(true);
    try {
      const [pool, rules, tasks, config, cats, plats, selStats, listStats] = await Promise.all([
        productSelectionDataSource.getProductPool(),
        productSelectionDataSource.getSelectionRules(),
        productSelectionDataSource.getListingTasks(),
        productSelectionDataSource.getAutoListingConfig(),
        productSelectionDataSource.getCategories(),
        productSelectionDataSource.getPlatforms(),
        productSelectionDataSource.getSelectionStats(),
        productSelectionDataSource.getListingStats(),
      ]);

      setProductPool(pool);
      setSelectionRules(rules);
      setListingTasks(tasks);
      setAutoListingConfig(config);
      setCategories(cats);
      setPlatforms(plats);
      setSelectionStats(selStats);
      setListingStats(listStats);
    } catch (error) {
      console.error('Failed to fetch data:', error);
      message.error('数据加载失败');
    } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => {
    fetchData();
  }, [fetchData]);

  const handleRunSelection = async () => {
    setLoading(true);
    try {
      await new Promise(resolve => setTimeout(resolve, 2000));
      message.success('选品任务已启动，预计完成时间：10分钟');
    } catch (error) {
      message.error('选品任务启动失败');
    } finally {
      setLoading(false);
    }
  };

  const handleSelectProduct = (product: ProductPool) => {
    setSelectedProduct(product);
    setProductDetailVisible(true);
  };

  const handleAddToSelection = (productId: string) => {
    message.success('商品已添加到选品列表');
  };

  const handleCreateRule = async () => {
    try {
      const values = await ruleForm.validateFields();
      await productSelectionDataSource.createSelectionRule({
        name: values.name,
        category: values.category,
        min_roi: values.minROI,
        max_roi: values.maxROI,
        min_profit: values.minProfit,
        max_price: values.maxPrice,
        min_sales_volume: values.minSalesVolume,
        max_competition_level: values.maxCompetitionLevel,
        min_rating: values.minRating,
        trend_filter: values.trendFilter,
      });
      setRuleModalVisible(false);
      ruleForm.resetFields();
      message.success('选品规则创建成功');
      fetchData();
    } catch (error) {
      message.error('请填写完整的规则信息');
    }
  };

  const handleToggleRule = async (ruleId: string) => {
    try {
      await productSelectionDataSource.toggleSelectionRule(ruleId);
      message.success('规则状态已更新');
      fetchData();
    } catch (error) {
      message.error('操作失败');
    }
  };

  const handleDeleteRule = async (ruleId: string) => {
    try {
      await productSelectionDataSource.deleteSelectionRule(ruleId);
      message.success('规则已删除');
      fetchData();
    } catch (error) {
      message.error('删除失败');
    }
  };

  const handleRunRule = async (ruleId: string) => {
    setLoading(true);
    try {
      const result = await productSelectionDataSource.executeSelectionRule(ruleId);
      message.success(`规则执行完成，已选择 ${result.count} 个商品`);
      fetchData();
    } catch (error) {
      message.error('规则执行失败');
    } finally {
      setLoading(false);
    }
  };

  const handleSaveConfig = async () => {
    try {
      const values = await configForm.validateFields();
      await productSelectionDataSource.updateAutoListingConfig({
        enabled: values.enabled,
        batch_size: values.batchSize,
        interval_hours: values.intervalHours,
        target_platforms: values.targetPlatforms,
        auto_pricing: values.autoPricing,
        auto_inventory: values.autoInventory,
        auto_description: values.autoDescription,
        auto_images: values.autoImages,
      });
      setConfigModalVisible(false);
      message.success('自动上架配置已保存');
      fetchData();
    } catch (error) {
      message.error('请填写完整的配置信息');
    }
  };

  const handleToggleAutoListing = async () => {
    setLoading(true);
    try {
      const enabled = await productSelectionDataSource.toggleAutoListing();
      message.success(enabled ? '自动上架已启动' : '自动上架已暂停');
      fetchData();
    } catch (error) {
      message.error('操作失败');
    } finally {
      setLoading(false);
    }
  };

  const handleRetryListing = async (taskId: string) => {
    setLoading(true);
    try {
      await productSelectionDataSource.retryListingTask(taskId);
      message.success('上架任务已重新启动');
      fetchData();
    } catch (error) {
      message.error('重试失败');
    } finally {
      setLoading(false);
    }
  };

  const handleDeleteListing = async (taskId: string) => {
    try {
      await productSelectionDataSource.deleteListingTask(taskId);
      message.success('上架任务已删除');
      fetchData();
    } catch (error) {
      message.error('删除失败');
    }
  };

  const handleApplyFilters = async () => {
    setLoading(true);
    try {
      const params: ProductPoolQueryParams = {};
      if (filters.keyword) params.keyword = filters.keyword;
      if (filters.category) params.category = filters.category;
      if (filters.minROI > 0) params.min_roi = filters.minROI;
      if (filters.maxROI < 100) params.max_roi = filters.maxROI;
      if (filters.competitionLevel) params.competition_level = filters.competitionLevel;
      if (filters.trend) params.trend = filters.trend;

      const pool = await productSelectionDataSource.getProductPool(params);
      setProductPool(pool);
    } catch (error) {
      message.error('筛选失败');
    } finally {
      setLoading(false);
    }
  };

  const poolColumns: ColumnsType<ProductPool> = [
    {
      title: '商品信息',
      dataIndex: 'name',
      key: 'name',
      width: 300,
      render: (text, record) => (
        <Space>
          <img src={record.image_url} alt={text} style={{ width: 60, height: 60, objectFit: 'cover', borderRadius: 4 }} />
          <div>
            <div style={{ fontWeight: 500 }}>{text}</div>
            <Text type="secondary" style={{ fontSize: 12 }}>SKU: {record.product_id}</Text>
            <div>
              {record.tags.map(tag => (
                <Tag key={tag} color="blue" style={{ fontSize: 10 }}>{tag}</Tag>
              ))}
            </div>
          </div>
        </Space>
      ),
    },
    {
      title: '分类',
      dataIndex: 'category',
      key: 'category',
      width: 120,
    },
    {
      title: '价格/成本',
      key: 'price',
      width: 150,
      render: (_, record) => (
        <div>
          <div>¥{record.price.toFixed(2)}</div>
          <Text type="secondary" style={{ fontSize: 12 }}>成本: ¥{record.cost_price.toFixed(2)}</Text>
        </div>
      ),
    },
    {
      title: '利润/ROI',
      key: 'profit',
      width: 120,
      render: (_, record) => (
        <div>
          <div style={{ color: '#52c41a', fontWeight: 500 }}>¥{record.profit.toFixed(2)}</div>
          <Tag color="green" style={{ fontSize: 11 }}>{record.roi.toFixed(0)}% ROI</Tag>
        </div>
      ),
    },
    {
      title: '销量/评分',
      key: 'sales',
      width: 120,
      render: (_, record) => (
        <div>
          <div>{record.sales_volume.toLocaleString()} 销量</div>
          <Space>
            <StarOutlined style={{ color: '#faad14', fontSize: 12 }} />
            <Text style={{ fontSize: 12 }}>{record.rating} ({record.review_count})</Text>
          </Space>
        </div>
      ),
    },
    {
      title: '竞争/趋势',
      key: 'competition',
      width: 120,
      render: (_, record) => (
        <Space direction="vertical" size={4}>
          <Tag color={COMPETITION_CONFIG[record.competition_level].color}>
            竞争: {COMPETITION_CONFIG[record.competition_level].text}
          </Tag>
          <Tag icon={TREND_CONFIG[record.trend].icon} color={TREND_CONFIG[record.trend].color}>
            {TREND_CONFIG[record.trend].text}
          </Tag>
        </Space>
      ),
    },
    {
      title: '选品评分',
      dataIndex: 'selection_score',
      key: 'selection_score',
      width: 100,
      render: (score) => (
        <Progress
          type="circle"
          percent={score}
          width={50}
          strokeColor={score >= 90 ? '#52c41a' : score >= 80 ? '#faad14' : '#ff4d4f'}
          format={percent => <span style={{ fontSize: 12 }}>{percent}</span>}
        />
      ),
    },
    {
      title: '操作',
      key: 'action',
      width: 150,
      fixed: 'right',
      render: (_, record) => (
        <Space size="small">
          <Tooltip title="查看详情">
            <Button type="link" size="small" icon={<EyeOutlined />} onClick={() => handleSelectProduct(record)} />
          </Tooltip>
          <Tooltip title="添加到选品">
            <Button type="link" size="small" icon={<ShoppingOutlined />} onClick={() => handleAddToSelection(record.id)} />
          </Tooltip>
        </Space>
      ),
    },
  ];

  const ruleColumns: ColumnsType<SelectionRule> = [
    {
      title: '规则名称',
      dataIndex: 'name',
      key: 'name',
      width: 200,
    },
    {
      title: '分类',
      dataIndex: 'category',
      key: 'category',
      width: 150,
      render: (categories: string[]) => (
        <Space wrap>
          {categories.map(cat => <Tag key={cat}>{cat}</Tag>)}
        </Space>
      ),
    },
    {
      title: 'ROI范围',
      key: 'roi',
      width: 120,
      render: (_, record) => `${record.min_roi}% - ${record.max_roi}%`,
    },
    {
      title: '利润要求',
      dataIndex: 'min_profit',
      key: 'min_profit',
      width: 100,
      render: (profit) => `≥ ¥${profit}`,
    },
    {
      title: '竞争水平',
      dataIndex: 'max_competition_level',
      key: 'max_competition_level',
      width: 100,
      render: (level) => <Tag color={COMPETITION_CONFIG[level].color}>{COMPETITION_CONFIG[level].text}</Tag>,
    },
    {
      title: '已选商品',
      dataIndex: 'selected_count',
      key: 'selected_count',
      width: 100,
      render: (count) => <Badge count={count} showZero style={{ backgroundColor: '#52c41a' }} />,
    },
    {
      title: '状态',
      dataIndex: 'enabled',
      key: 'enabled',
      width: 80,
      render: (enabled) => (
        <Tag color={enabled ? 'success' : 'default'}>{enabled ? '启用' : '禁用'}</Tag>
      ),
    },
    {
      title: '操作',
      key: 'action',
      width: 200,
      fixed: 'right',
      render: (_, record) => (
        <Space size="small">
          <Tooltip title={record.enabled ? '禁用' : '启用'}>
            <Button
              type="link"
              size="small"
              icon={record.enabled ? <PauseCircleOutlined /> : <PlayCircleOutlined />}
              onClick={() => handleToggleRule(record.id)}
            />
          </Tooltip>
          <Tooltip title="立即执行">
            <Button
              type="link"
              size="small"
              icon={<PlayCircleOutlined />}
              onClick={() => handleRunRule(record.id)}
            />
          </Tooltip>
          <Tooltip title="删除">
            <Popconfirm
              title="确定要删除这个规则吗？"
              onConfirm={() => handleDeleteRule(record.id)}
              okText="确定"
              cancelText="取消"
            >
              <Button type="link" size="small" danger icon={<DeleteOutlined />} />
            </Popconfirm>
          </Tooltip>
        </Space>
      ),
    },
  ];

  const taskColumns: ColumnsType<ListingTask> = [
    {
      title: '商品信息',
      dataIndex: 'product_name',
      key: 'product_name',
      width: 200,
    },
    {
      title: '目标平台',
      dataIndex: 'target_platforms',
      key: 'target_platforms',
      width: 150,
      render: (platforms: string[]) => (
        <Space wrap>
          {platforms.map(platform => <Tag key={platform}>{platform}</Tag>)}
        </Space>
      ),
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: 100,
      render: (status) => {
        const statusConfig = {
          PENDING: { color: 'default', text: '待处理' },
          PROCESSING: { color: 'processing', text: '处理中' },
          COMPLETED: { color: 'success', text: '已完成' },
          FAILED: { color: 'error', text: '失败' },
        };
        const config = statusConfig[status as keyof typeof statusConfig];
        return <Tag color={config.color}>{config.text}</Tag>;
      },
    },
    {
      title: '进度',
      dataIndex: 'progress',
      key: 'progress',
      width: 150,
      render: (progress) => <Progress percent={progress} size="small" />,
    },
    {
      title: '创建时间',
      dataIndex: 'created_at',
      key: 'created_at',
      width: 150,
    },
    {
      title: '操作',
      key: 'action',
      width: 150,
      fixed: 'right',
      render: (_, record) => (
        <Space size="small">
          {record.status === 'FAILED' && (
            <Tooltip title="重试">
              <Button type="link" size="small" icon={<ReloadOutlined />} onClick={() => handleRetryListing(record.id)} />
            </Tooltip>
          )}
          <Popconfirm
            title="确定要删除这个任务吗？"
            onConfirm={() => handleDeleteListing(record.id)}
            okText="确定"
            cancelText="取消"
          >
            <Button type="link" size="small" danger icon={<DeleteOutlined />} />
          </Popconfirm>
        </Space>
      ),
    },
  ];

  return (
    <div style={{ padding: 24 }}>
      <Row justify="space-between" align="middle" style={{ marginBottom: 24 }}>
        <Col>
          <Title level={4}>
            <Space>
              <RobotOutlined />
              自动选品 + 自动上架系统
            </Space>
          </Title>
          <Text type="secondary">AI驱动的智能选品和自动化上架解决方案</Text>
        </Col>
        <Col>
          <Space>
            <Button icon={<SettingOutlined />} onClick={() => {
              if (autoListingConfig) {
                configForm.setFieldsValue({
                  enabled: autoListingConfig.enabled,
                  batchSize: autoListingConfig.batch_size,
                  intervalHours: autoListingConfig.interval_hours,
                  targetPlatforms: autoListingConfig.target_platforms,
                  autoPricing: autoListingConfig.auto_pricing,
                  autoInventory: autoListingConfig.auto_inventory,
                  autoDescription: autoListingConfig.auto_description,
                  autoImages: autoListingConfig.auto_images,
                });
              }
              setConfigModalVisible(true);
            }}>
              配置
            </Button>
            <Button type="primary" icon={<ThunderboltOutlined />} onClick={handleRunSelection} loading={loading}>
              立即选品
            </Button>
          </Space>
        </Col>
      </Row>

      <Alert
        message="系统状态"
        description={
          <Space>
            <Badge status="processing" text="自动选品运行中" />
            <Badge status={autoListingConfig?.enabled ? "processing" : "default"} text={autoListingConfig?.enabled ? "自动上架运行中" : "自动上架已暂停"} />
            <Text type="secondary">|</Text>
            <Text>商品池: {productPool.length} 个</Text>
            <Text>选品规则: {selectionRules.length} 条</Text>
            <Text>上架任务: {listingTasks.length} 个</Text>
          </Space>
        }
        type="info"
        showIcon
        style={{ marginBottom: 24 }}
      />

      <Tabs activeKey={activeTab} onChange={setActiveTab}>
        <TabPane tab={<span><ShoppingOutlined /> 商品池</span>} key="pool">
          <Card>
            <Row gutter={[16, 16]} style={{ marginBottom: 24 }}>
              <Col xs={24} sm={12} lg={6}>
                <Statistic
                  title="商品总数"
                  value={selectionStats?.totalPool || 0}
                  prefix={<ShoppingOutlined />}
                  valueStyle={{ color: '#1890ff' }}
                />
              </Col>
              <Col xs={24} sm={12} lg={6}>
                <Statistic
                  title="平均ROI"
                  value={selectionStats?.avgROI.toFixed(1) || 0}
                  suffix="%"
                  prefix={<TrendingUpOutlined />}
                  valueStyle={{ color: '#52c41a' }}
                />
              </Col>
              <Col xs={24} sm={12} lg={6}>
                <Statistic
                  title="低竞争商品"
                  value={selectionStats?.lowCompetition || 0}
                  prefix={<FireOutlined />}
                  valueStyle={{ color: '#faad14' }}
                />
              </Col>
              <Col xs={24} sm={12} lg={6}>
                <Statistic
                  title="上升趋势商品"
                  value={selectionStats?.upTrend || 0}
                  prefix={<ArrowUpOutlined />}
                  valueStyle={{ color: '#52c41a' }}
                />
              </Col>
            </Row>

            <Card size="small" style={{ marginBottom: 16 }}>
              <Row gutter={[16, 16]} align="middle">
                <Col xs={24} sm={12} lg={4}>
                  <Input
                    placeholder="搜索商品名称"
                    prefix={<FilterOutlined />}
                    value={filters.keyword}
                    onChange={(e) => setFilters({ ...filters, keyword: e.target.value })}
                  />
                </Col>
                <Col xs={24} sm={12} lg={3}>
                  <Select
                    placeholder="分类"
                    style={{ width: '100%' }}
                    value={filters.category}
                    onChange={(value) => setFilters({ ...filters, category: value })}
                  >
                    <Option value="">全部</Option>
                    {categories.map(cat => <Option key={cat} value={cat}>{cat}</Option>)}
                  </Select>
                </Col>
                <Col xs={24} sm={12} lg={6}>
                  <Space>
                    <Text>ROI:</Text>
                    <Slider
                      range
                      min={0}
                      max={100}
                      value={[filters.minROI, filters.maxROI]}
                      onChange={(value) => setFilters({ ...filters, minROI: value[0], maxROI: value[1] })}
                      style={{ width: 150 }}
                    />
                  </Space>
                </Col>
                <Col xs={24} sm={12} lg={3}>
                  <Select
                    placeholder="竞争水平"
                    style={{ width: '100%' }}
                    value={filters.competitionLevel}
                    onChange={(value) => setFilters({ ...filters, competitionLevel: value })}
                  >
                    <Option value="">全部</Option>
                    <Option value="LOW">低</Option>
                    <Option value="MEDIUM">中</Option>
                    <Option value="HIGH">高</Option>
                  </Select>
                </Col>
                <Col xs={24} sm={12} lg={3}>
                  <Select
                    placeholder="趋势"
                    style={{ width: '100%' }}
                    value={filters.trend}
                    onChange={(value) => setFilters({ ...filters, trend: value })}
                  >
                    <Option value="">全部</Option>
                    <Option value="UP">上升</Option>
                    <Option value="DOWN">下降</Option>
                    <Option value="STABLE">稳定</Option>
                  </Select>
                </Col>
                <Col xs={24} sm={12} lg={5}>
                  <Button type="primary" icon={<FilterOutlined />} block onClick={handleApplyFilters}>
                    应用筛选
                  </Button>
                </Col>
              </Row>
            </Card>

            <Table
              columns={poolColumns}
              dataSource={productPool}
              rowKey="id"
              loading={loading}
              scroll={{ x: 1200 }}
              pagination={{
                pageSize: 10,
                showSizeChanger: true,
                showQuickJumper: true,
                showTotal: (total) => `共 ${total} 个商品`,
              }}
            />
          </Card>
        </TabPane>

        <TabPane tab={<span><BarChartOutlined /> 选品规则</span>} key="rules">
          <Card>
            <Row justify="space-between" align="middle" style={{ marginBottom: 16 }}>
              <Col>
                <Title level={5}>选品规则管理</Title>
                <Text type="secondary">配置自动选品规则，AI将根据规则自动筛选高潜力商品</Text>
              </Col>
              <Col>
                <Button type="primary" icon={<PlusOutlined />} onClick={() => setRuleModalVisible(true)}>
                  创建规则
                </Button>
              </Col>
            </Row>

            <Table
              columns={ruleColumns}
              dataSource={selectionRules}
              rowKey="id"
              loading={loading}
              scroll={{ x: 1000 }}
              pagination={{
                pageSize: 10,
                showTotal: (total) => `共 ${total} 条规则`,
              }}
            />
          </Card>
        </TabPane>

        <TabPane tab={<span><SyncOutlined /> 上架任务</span>} key="tasks">
          <Card>
            <Row justify="space-between" align="middle" style={{ marginBottom: 16 }}>
              <Col>
                <Title level={5}>自动上架任务</Title>
                <Text type="secondary">查看和管理自动上架任务的执行状态</Text>
              </Col>
              <Col>
                <Space>
                  <Button
                    icon={autoListingConfig?.enabled ? <PauseCircleOutlined /> : <PlayCircleOutlined />}
                    onClick={handleToggleAutoListing}
                    loading={loading}
                  >
                    {autoListingConfig?.enabled ? '暂停自动上架' : '启动自动上架'}
                  </Button>
                  <Button icon={<ReloadOutlined />} onClick={fetchData}>
                    刷新
                  </Button>
                </Space>
              </Col>
            </Row>

            <Row gutter={[16, 16]} style={{ marginBottom: 24 }}>
              <Col xs={24} sm={12} lg={6}>
                <Statistic
                  title="总任务数"
                  value={listingStats?.totalTasks || 0}
                  prefix={<SyncOutlined />}
                />
              </Col>
              <Col xs={24} sm={12} lg={6}>
                <Statistic
                  title="处理中"
                  value={listingStats?.processingTasks || 0}
                  prefix={<ClockCircleOutlined />}
                  valueStyle={{ color: '#1890ff' }}
                />
              </Col>
              <Col xs={24} sm={12} lg={6}>
                <Statistic
                  title="已完成"
                  value={listingStats?.completedTasks || 0}
                  prefix={<CheckCircleOutlined />}
                  valueStyle={{ color: '#52c41a' }}
                />
              </Col>
              <Col xs={24} sm={12} lg={6}>
                <Statistic
                  title="失败"
                  value={listingStats?.failedTasks || 0}
                  prefix={<AlertOutlined />}
                  valueStyle={{ color: '#ff4d4f' }}
                />
              </Col>
            </Row>

            <Table
              columns={taskColumns}
              dataSource={listingTasks}
              rowKey="id"
              loading={loading}
              scroll={{ x: 800 }}
              pagination={{
                pageSize: 10,
                showTotal: (total) => `共 ${total} 个任务`,
              }}
            />
          </Card>
        </TabPane>
      </Tabs>

      <Modal
        title="创建选品规则"
        open={ruleModalVisible}
        onOk={handleCreateRule}
        onCancel={() => {
          setRuleModalVisible(false);
          ruleForm.resetFields();
        }}
        width={800}
      >
        <Form form={ruleForm} layout="vertical">
          <Form.Item
            name="name"
            label="规则名称"
            rules={[{ required: true, message: '请输入规则名称' }]}
          >
            <Input placeholder="例如：高ROI低竞争策略" />
          </Form.Item>

          <Form.Item
            name="category"
            label="商品分类"
            rules={[{ required: true, message: '请选择商品分类' }]}
          >
            <Select mode="multiple" placeholder="选择商品分类">
              {categories.map(cat => <Option key={cat} value={cat}>{cat}</Option>)}
            </Select>
          </Form.Item>

          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                name="minROI"
                label="最低ROI (%)"
                rules={[{ required: true, message: '请输入最低ROI' }]}
              >
                <InputNumber min={0} max={100} style={{ width: '100%' }} />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="maxROI"
                label="最高ROI (%)"
                rules={[{ required: true, message: '请输入最高ROI' }]}
              >
                <InputNumber min={0} max={100} style={{ width: '100%' }} />
              </Form.Item>
            </Col>
          </Row>

          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                name="minProfit"
                label="最低利润 (¥)"
                rules={[{ required: true, message: '请输入最低利润' }]}
              >
                <InputNumber min={0} style={{ width: '100%' }} />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="maxPrice"
                label="最高价格 (¥)"
                rules={[{ required: true, message: '请输入最高价格' }]}
              >
                <InputNumber min={0} style={{ width: '100%' }} />
              </Form.Item>
            </Col>
          </Row>

          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                name="minSalesVolume"
                label="最低销量"
                rules={[{ required: true, message: '请输入最低销量' }]}
              >
                <InputNumber min={0} style={{ width: '100%' }} />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="minRating"
                label="最低评分"
                rules={[{ required: true, message: '请输入最低评分' }]}
              >
                <InputNumber min={0} max={5} step={0.1} style={{ width: '100%' }} />
              </Form.Item>
            </Col>
          </Row>

          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                name="maxCompetitionLevel"
                label="最高竞争水平"
                rules={[{ required: true, message: '请选择最高竞争水平' }]}
              >
                <Select placeholder="选择竞争水平">
                  <Option value="LOW">低</Option>
                  <Option value="MEDIUM">中</Option>
                  <Option value="HIGH">高</Option>
                </Select>
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="trendFilter"
                label="趋势筛选"
                rules={[{ required: true, message: '请选择趋势筛选' }]}
              >
                <Select placeholder="选择趋势">
                  <Option value="ALL">全部</Option>
                  <Option value="UP">上升</Option>
                  <Option value="STABLE">稳定</Option>
                </Select>
              </Form.Item>
            </Col>
          </Row>
        </Form>
      </Modal>

      <Modal
        title="自动上架配置"
        open={configModalVisible}
        onOk={handleSaveConfig}
        onCancel={() => {
          setConfigModalVisible(false);
          configForm.resetFields();
        }}
        width={700}
      >
        <Form form={configForm} layout="vertical">
          <Form.Item
            name="enabled"
            label="启用自动上架"
            valuePropName="checked"
          >
            <Switch />
          </Form.Item>

          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                name="batchSize"
                label="每批上架数量"
                rules={[{ required: true, message: '请输入每批上架数量' }]}
              >
                <InputNumber min={1} max={50} style={{ width: '100%' }} />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="intervalHours"
                label="执行间隔（小时）"
                rules={[{ required: true, message: '请输入执行间隔' }]}
              >
                <InputNumber min={1} max={24} style={{ width: '100%' }} />
              </Form.Item>
            </Col>
          </Row>

          <Form.Item
            name="targetPlatforms"
            label="目标平台"
            rules={[{ required: true, message: '请选择目标平台' }]}
          >
            <Select mode="multiple" placeholder="选择目标平台">
              {platforms.map(platform => <Option key={platform} value={platform}>{platform}</Option>)}
            </Select>
          </Form.Item>

          <Divider>自动化选项</Divider>

          <Form.Item
            name="autoPricing"
            label="自动定价"
            valuePropName="checked"
          >
            <Switch />
          </Form.Item>

          <Form.Item
            name="autoInventory"
            label="自动库存管理"
            valuePropName="checked"
          >
            <Switch />
          </Form.Item>

          <Form.Item
            name="autoDescription"
            label="自动生成描述"
            valuePropName="checked"
          >
            <Switch />
          </Form.Item>

          <Form.Item
            name="autoImages"
            label="自动优化图片"
            valuePropName="checked"
          >
            <Switch />
          </Form.Item>
        </Form>
      </Modal>

      <Drawer
        title="商品详情"
        placement="right"
        width={600}
        open={productDetailVisible}
        onClose={() => setProductDetailVisible(false)}
      >
        {selectedProduct && (
          <div>
            <img
              src={selectedProduct.image_url}
              alt={selectedProduct.name}
              style={{ width: '100%', height: 300, objectFit: 'cover', borderRadius: 8, marginBottom: 16 }}
            />
            <Title level={4}>{selectedProduct.name}</Title>
            <Text type="secondary">SKU: {selectedProduct.product_id}</Text>
            <Divider />
            <Row gutter={[16, 16]}>
              <Col span={12}>
                <Statistic title="售价" value={selectedProduct.price} prefix="¥" precision={2} />
              </Col>
              <Col span={12}>
                <Statistic title="成本" value={selectedProduct.cost_price} prefix="¥" precision={2} />
              </Col>
              <Col span={12}>
                <Statistic title="利润" value={selectedProduct.profit} prefix="¥" precision={2} valueStyle={{ color: '#52c41a' }} />
              </Col>
              <Col span={12}>
                <Statistic title="ROI" value={selectedProduct.roi} suffix="%" valueStyle={{ color: '#52c41a' }} />
              </Col>
              <Col span={12}>
                <Statistic title="销量" value={selectedProduct.sales_volume} />
              </Col>
              <Col span={12}>
                <Statistic title="评分" value={selectedProduct.rating} suffix={`/ 5`} />
              </Col>
            </Row>
            <Divider />
            <Space direction="vertical" style={{ width: '100%' }}>
              <div>
                <Text strong>分类: </Text>
                <Tag>{selectedProduct.category}</Tag>
              </div>
              <div>
                <Text strong>竞争水平: </Text>
                <Tag color={COMPETITION_CONFIG[selectedProduct.competition_level].color}>
                  {COMPETITION_CONFIG[selectedProduct.competition_level].text}
                </Tag>
              </div>
              <div>
                <Text strong>趋势: </Text>
                <Tag icon={TREND_CONFIG[selectedProduct.trend].icon} color={TREND_CONFIG[selectedProduct.trend].color}>
                  {TREND_CONFIG[selectedProduct.trend].text}
                </Tag>
              </div>
              <div>
                <Text strong>来源平台: </Text>
                <Tag>{selectedProduct.source_platform}</Tag>
              </div>
              <div>
                <Text strong>选品评分: </Text>
                <Progress
                  percent={selectedProduct.selection_score}
                  strokeColor={selectedProduct.selection_score >= 90 ? '#52c41a' : selectedProduct.selection_score >= 80 ? '#faad14' : '#ff4d4f'}
                />
              </div>
              <div>
                <Text strong>标签: </Text>
                <Space wrap>
                  {selectedProduct.tags.map(tag => <Tag key={tag} color="blue">{tag}</Tag>)}
                </Space>
              </div>
            </Space>
            <Divider />
            <Button type="primary" block icon={<ShoppingOutlined />} onClick={() => handleAddToSelection(selectedProduct.id)}>
              添加到选品列表
            </Button>
          </div>
        )}
      </Drawer>
    </div>
  );
};

export default AutoProductSelection;
