import React, { useState, useEffect, useCallback, useMemo } from 'react';
import { useNavigate } from 'react-router-dom';
import {
  Card,
  Table,
  Button,
  Space,
  Tag,
  Input,
  InputNumber,
  Select,
  Row,
  Col,
  Modal,
  message,
  Tooltip,
  Badge,
  Dropdown,
  Menu,
  Image,
  Typography,
  DatePicker,
  Form,
  Drawer,
  Alert,
  Spin,
  Tabs,
  Statistic,
} from 'antd';
import {
  PlusOutlined,
  EditOutlined,
  DeleteOutlined,
  SyncOutlined,
  UploadOutlined,
  FilterOutlined,
  SortAscendingOutlined,
  SortDescendingOutlined,
  MoreOutlined,
  EyeOutlined,
  CopyOutlined,
  ArrowUpOutlined,
  ArrowDownOutlined,
  DollarOutlined,
  ShoppingOutlined,
  CheckCircleOutlined,
  CloseCircleOutlined,
  ExclamationCircleOutlined,
  AmazonOutlined,
  GlobalOutlined,
  ShopOutlined,
  AppstoreOutlined,
} from '@ant-design/icons';
import { LoadingState, EmptyState } from '../../components/ui';

import type { ColumnsType, TablePaginationConfig } from 'antd/es/table';
import type { FilterValue, SorterResult, TableCurrentDataSource } from 'antd/es/table/interface';
import moment from 'moment';

const { Title, Text } = Typography;
const { Option } = Select;
const { RangePicker } = DatePicker;
const { Search } = Input;

interface Product {
  id: string;
  sku: string;
  name: string;
  image: string;
  category: string;
  price: number;
  costPrice: number;
  profit: number;
  roi: number;
  stock: number;
  status: 'DRAFT' | 'PRICED' | 'LISTED' | 'SYNCING' | 'LIVE' | 'SYNC_FAILED' | 'OFFLINE';
  platformStatus: Record<string, string>;
  shopId: string;
  shopName: string;
  platform: string;
  createdAt: string;
  updatedAt: string;
}

interface Shop {
  id: string;
  name: string;
  platform: string;
  status: 'ACTIVE' | 'INACTIVE' | 'SUSPENDED';
  region: string;
  currency: string;
}

interface FilterState {
  keyword: string;
  status: string[];
  platform: string[];
  shop: string[];
  category: string[];
  priceRange: [number, number] | null;
  stockRange: [number, number] | null;
  roiRange: [number, number] | null;
  dateRange: any;
  minProfit: number | null;
  minStock: number | null;
  searchInDescription: boolean;
}

interface SortState {
  field: string;
  order: 'ascend' | 'descend' | null;
}

const STATUS_CONFIG: Record<string, { color: string; text: string; icon: React.ReactNode }> = {
  DRAFT: { color: 'default', text: '草稿', icon: <EditOutlined /> },
  PRICED: { color: 'processing', text: '已定价', icon: <DollarOutlined /> },
  LISTED: { color: 'warning', text: '已上架', icon: <ShoppingOutlined /> },
  SYNCING: { color: 'processing', text: '同步中', icon: <SyncOutlined spin /> },
  LIVE: { color: 'success', text: '已在线', icon: <CheckCircleOutlined /> },
  SYNC_FAILED: { color: 'error', text: '同步失败', icon: <CloseCircleOutlined /> },
  OFFLINE: { color: 'default', text: '已下架', icon: <ExclamationCircleOutlined /> },
};

const PLATFORMS = [
  // TikTok系列
  'TikTok', 'TikTokFull',
  
  // Shopee系列
  'Shopee', 'ShopeeFull', 'ShopeeLight',
  
  // Lazada系列
  'Lazada', 'LazadaFull',
  
  // Temu
  'TemuFull',
  
  // SHEIN系列
  'Shein', 'SheinHalf',
  
  // 其他平台
  'Ozon', 'Yandex', 'AliExpress', 'AliExpressHalf', 'AliExpressPop',
  'Coupang', 'Walmart', 'Wildberries', 'Allegro', 'MercadoLibre',
  'Jumia', 'Joom', 'Amazon', 'Wish', 'Emag', 'Miravia',
  'Daraz', 'Joybuy', 'Alibaba', 'Qoo10', 'Shopify', 'Shoplazza',
  'ShopyyV1', 'ShopyyV2', 'Shopline', 'GreatBoss', 'Other',
  
  // 原有平台
  'eBay',
];
const CATEGORIES = ['工业自动化', '电子元器件', '工具设备', '仪器仪表', '安防设备'];

// 店铺数据
const SHOPS: Shop[] = [
  // TikTok平台 - 多个店铺
  { id: 'shop-tiktok-1', name: 'TikTok旗舰店A', platform: 'TikTok', status: 'ACTIVE', region: '中国', currency: 'CNY' },
  { id: 'shop-tiktok-2', name: 'TikTok旗舰店B', platform: 'TikTok', status: 'ACTIVE', region: '美国', currency: 'USD' },
  { id: 'shop-tiktok-3', name: 'TikTok精品店C', platform: 'TikTok', status: 'ACTIVE', region: '欧洲', currency: 'EUR' },
  { id: 'shop-tiktok-4', name: 'TikTok精品店D', platform: 'TikTok', status: 'INACTIVE', region: '东南亚', currency: 'SGD' },
  
  // Shopee平台 - 多个店铺
  { id: 'shop-shopee-1', name: 'Shopee官方店A', platform: 'Shopee', status: 'ACTIVE', region: '东南亚', currency: 'SGD' },
  { id: 'shop-shopee-2', name: 'Shopee官方店B', platform: 'Shopee', status: 'ACTIVE', region: '台湾', currency: 'TWD' },
  { id: 'shop-shopee-3', name: 'Shopee旗舰店C', platform: 'Shopee', status: 'ACTIVE', region: '马来西亚', currency: 'MYR' },
  { id: 'shop-shopee-4', name: 'Shopee旗舰店D', platform: 'Shopee', status: 'SUSPENDED', region: '菲律宾', currency: 'PHP' },
  
  // Lazada平台 - 多个店铺
  { id: 'shop-lazada-1', name: 'Lazada官方店A', platform: 'Lazada', status: 'ACTIVE', region: '东南亚', currency: 'SGD' },
  { id: 'shop-lazada-2', name: 'Lazada官方店B', platform: 'Lazada', status: 'ACTIVE', region: '泰国', currency: 'THB' },
  { id: 'shop-lazada-3', name: 'Lazada旗舰店C', platform: 'Lazada', status: 'ACTIVE', region: '越南', currency: 'VND' },
  
  // Amazon平台 - 多个店铺
  { id: 'shop-amazon-1', name: 'Amazon美国店A', platform: 'Amazon', status: 'ACTIVE', region: '美国', currency: 'USD' },
  { id: 'shop-amazon-2', name: 'Amazon美国店B', platform: 'Amazon', status: 'ACTIVE', region: '美国', currency: 'USD' },
  { id: 'shop-amazon-3', name: 'Amazon欧洲店C', platform: 'Amazon', status: 'ACTIVE', region: '欧洲', currency: 'EUR' },
  { id: 'shop-amazon-4', name: 'Amazon欧洲店D', platform: 'Amazon', status: 'ACTIVE', region: '英国', currency: 'GBP' },
  { id: 'shop-amazon-5', name: 'Amazon日本店E', platform: 'Amazon', status: 'ACTIVE', region: '日本', currency: 'JPY' },
  
  // eBay平台 - 多个店铺
  { id: 'shop-ebay-1', name: 'eBay全球店A', platform: 'eBay', status: 'ACTIVE', region: '全球', currency: 'USD' },
  { id: 'shop-ebay-2', name: 'eBay全球店B', platform: 'eBay', status: 'ACTIVE', region: '欧洲', currency: 'EUR' },
  { id: 'shop-ebay-3', name: 'eBay美国店C', platform: 'eBay', status: 'ACTIVE', region: '美国', currency: 'USD' },
  
  // Shopify平台 - 多个店铺
  { id: 'shop-shopify-1', name: 'Shopify独立站A', platform: 'Shopify', status: 'ACTIVE', region: '全球', currency: 'USD' },
  { id: 'shop-shopify-2', name: 'Shopify独立站B', platform: 'Shopify', status: 'ACTIVE', region: '欧洲', currency: 'EUR' },
  { id: 'shop-shopify-3', name: 'Shopify独立站C', platform: 'Shopify', status: 'ACTIVE', region: '亚洲', currency: 'CNY' },
  
  // Temu平台 - 多个店铺
  { id: 'shop-temu-1', name: 'Temu旗舰店A', platform: 'Temu', status: 'ACTIVE', region: '美国', currency: 'USD' },
  { id: 'shop-temu-2', name: 'Temu旗舰店B', platform: 'Temu', status: 'ACTIVE', region: '欧洲', currency: 'EUR' },
  { id: 'shop-temu-3', name: 'Temu旗舰店C', platform: 'Temu', status: 'ACTIVE', region: '澳大利亚', currency: 'AUD' },
  
  // SHEIN平台 - 多个店铺
  { id: 'shop-shein-1', name: 'SHEIN官方店A', platform: 'Shein', status: 'ACTIVE', region: '全球', currency: 'USD' },
  { id: 'shop-shein-2', name: 'SHEIN官方店B', platform: 'Shein', status: 'ACTIVE', region: '欧洲', currency: 'EUR' },
  { id: 'shop-shein-3', name: 'SHEIN官方店C', platform: 'Shein', status: 'ACTIVE', region: '中东', currency: 'AED' },
  
  // 其他平台店铺
  { id: 'shop-ozon-1', name: 'Ozon旗舰店A', platform: 'Ozon', status: 'ACTIVE', region: '俄罗斯', currency: 'RUB' },
  { id: 'shop-ali-1', name: '速卖通旗舰店A', platform: 'AliExpress', status: 'ACTIVE', region: '全球', currency: 'USD' },
  { id: 'shop-walmart-1', name: 'Walmart旗舰店A', platform: 'Walmart', status: 'ACTIVE', region: '美国', currency: 'USD' },
];

const PLATFORM_CONFIG: Record<string, { icon: React.ReactNode; color: string }> = {
  // TikTok系列
  TikTok: { icon: <GlobalOutlined />, color: '#000000' },
  TikTokFull: { icon: <GlobalOutlined />, color: '#000000' },
  
  // Shopee系列
  Shopee: { icon: <ShopOutlined />, color: '#ee4d2d' },
  ShopeeFull: { icon: <ShopOutlined />, color: '#ee4d2d' },
  ShopeeLight: { icon: <ShopOutlined />, color: '#ee4d2d' },
  
  // Lazada系列
  Lazada: { icon: <ShopOutlined />, color: '#0F156D' },
  LazadaFull: { icon: <ShopOutlined />, color: '#0F156D' },
  
  // Temu
  TemuFull: { icon: <ShopOutlined />, color: '#96bf48' },
  
  // SHEIN系列
  Shein: { icon: <ShopOutlined />, color: '#FF6B6B' },
  SheinHalf: { icon: <ShopOutlined />, color: '#FF6B6B' },
  
  // 其他平台
  Ozon: { icon: <ShopOutlined />, color: '#FFD700' },
  Yandex: { icon: <ShopOutlined />, color: '#FF0000' },
  AliExpress: { icon: <ShopOutlined />, color: '#FF6A00' },
  AliExpressHalf: { icon: <ShopOutlined />, color: '#FF6A00' },
  AliExpressPop: { icon: <ShopOutlined />, color: '#FF6A00' },
  Coupang: { icon: <ShopOutlined />, color: '#FF3B30' },
  Walmart: { icon: <ShopOutlined />, color: '#007DC6' },
  Wildberries: { icon: <ShopOutlined />, color: '#9370DB' },
  Allegro: { icon: <ShopOutlined />, color: '#00A870' },
  MercadoLibre: { icon: <ShopOutlined />, color: '#6C3483' },
  Jumia: { icon: <ShopOutlined />, color: '#FF6B00' },
  Joom: { icon: <ShopOutlined />, color: '#8A2BE2' },
  Amazon: { icon: <AmazonOutlined />, color: '#ff9900' },
  Wish: { icon: <ShopOutlined />, color: '#4A90E2' },
  Emag: { icon: <ShopOutlined />, color: '#00B140' },
  Miravia: { icon: <ShopOutlined />, color: '#FF69B4' },
  Daraz: { icon: <ShopOutlined />, color: '#FF5722' },
  Joybuy: { icon: <ShopOutlined />, color: '#E74C3C' },
  Alibaba: { icon: <ShopOutlined />, color: '#FF6A00' },
  Qoo10: { icon: <ShopOutlined />, color: '#FF4500' },
  Shopify: { icon: <ShopOutlined />, color: '#96bf48' },
  Shoplazza: { icon: <ShopOutlined />, color: '#3498DB' },
  ShopyyV1: { icon: <ShopOutlined />, color: '#9370DB' },
  ShopyyV2: { icon: <ShopOutlined />, color: '#9370DB' },
  Shopline: { icon: <ShopOutlined />, color: '#27AE60' },
  GreatBoss: { icon: <ShopOutlined />, color: '#3498DB' },
  Other: { icon: <ShopOutlined />, color: '#999999' },
  
  // 原有平台
  eBay: { icon: <GlobalOutlined />, color: '#e53238' },
};

const MOCK_PRODUCTS: Product[] = [
  {
    id: '1',
    sku: 'TP-TEMP-001',
    name: '工业温度传感器 Pro',
    image: 'https://via.placeholder.com/80x80?text=Product',
    category: '工业自动化',
    price: 89.99,
    costPrice: 45.00,
    profit: 44.99,
    roi: 99.98,
    stock: 256,
    status: 'LIVE',
    platformStatus: { Amazon: 'LIVE', eBay: 'LIVE', Shopee: 'PENDING' },
    shopId: 'shop-amazon-1',
    shopName: 'Amazon美国店',
    platform: 'Amazon',
    createdAt: '2025-12-15',
    updatedAt: '2026-03-18',
  },
  {
    id: '2',
    sku: 'TP-PRES-002',
    name: '压力传感器 Digital',
    image: 'https://via.placeholder.com/80x80?text=Product',
    category: '工业自动化',
    price: 129.99,
    costPrice: 65.00,
    profit: 64.99,
    roi: 99.98,
    stock: 128,
    status: 'DRAFT',
    platformStatus: {},
    shopId: 'shop-tiktok-1',
    shopName: 'TikTok旗舰店',
    platform: 'TikTok',
    createdAt: '2026-03-10',
    updatedAt: '2026-03-10',
  },
  {
    id: '3',
    sku: 'TP-FLOW-003',
    name: '流量计 Ultra',
    image: 'https://via.placeholder.com/80x80?text=Product',
    category: '仪器仪表',
    price: 299.99,
    costPrice: 150.00,
    profit: 149.99,
    roi: 99.99,
    stock: 64,
    status: 'PRICED',
    platformStatus: {},
    shopId: 'shop-shopee-1',
    shopName: 'Shopee官方店',
    platform: 'Shopee',
    createdAt: '2026-03-15',
    updatedAt: '2026-03-16',
  },
  {
    id: '4',
    sku: 'TP-MOTR-004',
    name: '步进电机 57型',
    image: 'https://via.placeholder.com/80x80?text=Product',
    category: '工业自动化',
    price: 59.99,
    costPrice: 30.00,
    profit: 29.99,
    roi: 99.97,
    stock: 512,
    status: 'LISTED',
    platformStatus: { Amazon: 'LISTED' },
    shopId: 'shop-amazon-2',
    shopName: 'Amazon欧洲店',
    platform: 'Amazon',
    createdAt: '2026-03-01',
    updatedAt: '2026-03-17',
  },
  {
    id: '5',
    sku: 'TP-CTRL-005',
    name: 'PLC控制器 Mini',
    image: 'https://via.placeholder.com/80x80?text=Product',
    category: '工业自动化',
    price: 199.99,
    costPrice: 100.00,
    profit: 99.99,
    roi: 99.99,
    stock: 32,
    status: 'SYNCING',
    platformStatus: { Amazon: 'SYNCING', eBay: 'SYNCING' },
    shopId: 'shop-ebay-1',
    shopName: 'eBay全球店',
    platform: 'eBay',
    createdAt: '2026-03-18',
    updatedAt: '2026-03-18',
  },
  {
    id: '6',
    sku: 'TP-SENS-006',
    name: '光电传感器',
    image: 'https://via.placeholder.com/80x80?text=Product',
    category: '工业自动化',
    price: 39.99,
    costPrice: 20.00,
    profit: 19.99,
    roi: 99.95,
    stock: 0,
    status: 'SYNC_FAILED',
    platformStatus: { Amazon: 'FAILED' },
    shopId: 'shop-temu-1',
    shopName: 'Temu旗舰店',
    platform: 'Temu',
    createdAt: '2026-03-05',
    updatedAt: '2026-03-18',
  },
  {
    id: '7',
    sku: 'TP-VALV-007',
    name: '电磁阀 24V',
    image: 'https://via.placeholder.com/80x80?text=Product',
    category: '工具设备',
    price: 79.99,
    costPrice: 40.00,
    profit: 39.99,
    roi: 99.98,
    stock: 200,
    status: 'OFFLINE',
    platformStatus: { Amazon: 'OFFLINE', eBay: 'OFFLINE' },
    shopId: 'shop-shein-1',
    shopName: 'SHEIN官方店',
    platform: 'Shein',
    createdAt: '2025-11-20',
    updatedAt: '2026-02-28',
  },
];

export const ProductList: React.FC = () => {
  const navigate = useNavigate();
  const [products, setProducts] = useState<Product[]>([]);
  const [loading, setLoading] = useState(false);
  const [selectedRows, setSelectedRows] = useState<Product[]>([]);
  const [filterVisible, setFilterVisible] = useState(false);
  const [sortDrawerVisible, setSortDrawerVisible] = useState(false);
  const [pricingModalVisible, setPricingModalVisible] = useState(false);
  const [columnDrawerVisible, setColumnDrawerVisible] = useState(false);
  const [currentProduct, setCurrentProduct] = useState<Product | null>(null);
  const [syncLoading, setSyncLoading] = useState<Record<string, boolean>>({});
  const [activePlatformTab, setActivePlatformTab] = useState<string>('all');
  
  const [filters, setFilters] = useState<FilterState>({
    keyword: '',
    status: [],
    platform: [],
    shop: [],
    category: [],
    priceRange: null,
    stockRange: null,
    roiRange: null,
    dateRange: null,
    minProfit: null,
    minStock: null,
    searchInDescription: false,
  });
  
  const [sort, setSort] = useState<SortState>({
    field: 'updatedAt',
    order: 'descend',
  });
  
  const [visibleColumns, setVisibleColumns] = useState<string[]>([
    'name', 'price', 'costPrice', 'profit', 'roi', 'stock', 'status', 'platformStatus', 'updatedAt', 'action'
  ]);
  const [columnOrder, setColumnOrder] = useState<string[]>([
    'name', 'price', 'costPrice', 'profit', 'roi', 'stock', 'status', 'platformStatus', 'updatedAt', 'action'
  ]);

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

  const fetchProducts = useCallback(async () => {
    setLoading(true);
    await new Promise(resolve => setTimeout(resolve, 500));
    setProducts(MOCK_PRODUCTS);
    setLoading(false);
  }, []);

  const handleFilterChange = (key: keyof FilterState, value: any) => {
    setFilters(prev => ({ ...prev, [key]: value }));
  };

  const handleSortChange = (field: string, order: 'ascend' | 'descend') => {
    setSort({ field, order });
    setSortDrawerVisible(false);
    message.success(`已按 ${field} ${order === 'ascend' ? '升序' : '降序'} 排序`);
  };

  const handleTableChange = (
    pagination: TablePaginationConfig,
    filters: Record<string, FilterValue | null>,
    sorter: SorterResult<Product> | SorterResult<Product>[],
    extra: TableCurrentDataSource<Product>
  ) => {
    if (!Array.isArray(sorter) && sorter.field) {
      setSort({
        field: sorter.field as string,
        order: sorter.order || null,
      });
    }
  };

  const handleSearch = (value: string) => {
    handleFilterChange('keyword', value);
  };

  const handleResetFilters = () => {
    setFilters({
      keyword: '',
      status: [],
      platform: [],
      shop: [],
      category: [],
      priceRange: null,
      stockRange: null,
      roiRange: null,
      dateRange: null,
      minProfit: null,
      minStock: null,
      searchInDescription: false,
    });
    message.success('筛选条件已重置');
  };

  const handleColumnVisibilityChange = (columnKey: string, visible: boolean) => {
    if (visible) {
      setVisibleColumns([...visibleColumns, columnKey]);
    } else {
      setVisibleColumns(visibleColumns.filter(key => key !== columnKey));
    }
  };

  const handleColumnOrderChange = (newOrder: string[]) => {
    setColumnOrder(newOrder);
  };

  const handleAddProduct = () => {
    navigate('/dashboard/product/publish');
  };

  const handleEditProduct = (record: Product) => {
    navigate(`/dashboard/product/detail/${record.id}`);
  };

  const handleViewProduct = (record: Product) => {
    navigate(`/dashboard/product/detail/${record.id}`);
  };

  const handleDeleteProduct = (record: Product) => {
    Modal.confirm({
      title: '确认删除',
      content: `确定要删除商品 "${record.name}" 吗？此操作不可恢复。`,
      okText: '删除',
      okType: 'danger',
      onOk: () => {
        setProducts(products.filter(p => p.id !== record.id));
        message.success('商品删除成功');
      },
    });
  };

  const handleDuplicateProduct = (record: Product) => {
    const newProduct: Product = {
      ...record,
      id: `${Date.now()}`,
      sku: `${record.sku}-COPY`,
      name: `${record.name} (复制)`,
      status: 'DRAFT',
      platformStatus: {},
      createdAt: moment().format('YYYY-MM-DD'),
      updatedAt: moment().format('YYYY-MM-DD'),
    };
    setProducts([newProduct, ...products]);
    message.success('商品复制成功');
  };

  const handlePricing = (record: Product) => {
    setCurrentProduct(record);
    setPricingModalVisible(true);
  };

  const handlePublish = (record: Product) => {
    Modal.confirm({
      title: '确认上架',
      content: `确定要上架商品 "${record.name}" 吗？`,
      onOk: () => {
        updateProductStatus(record.id, 'LISTED');
        message.success('商品上架成功');
      },
    });
  };

  const handleSync = async (record: Product) => {
    setSyncLoading(prev => ({ ...prev, [record.id]: true }));
    
    updateProductStatus(record.id, 'SYNCING');
    message.loading({ content: '正在同步到平台...', key: record.id });
    
    await new Promise(resolve => setTimeout(resolve, 2000));
    
    const success = Math.random() > 0.3;
    if (success) {
      updateProductStatus(record.id, 'LIVE');
      message.success({ content: '同步成功', key: record.id });
    } else {
      updateProductStatus(record.id, 'SYNC_FAILED');
      message.error({ content: '同步失败，请重试', key: record.id });
    }
    
    setSyncLoading(prev => ({ ...prev, [record.id]: false }));
  };

  const handleOffline = (record: Product) => {
    Modal.confirm({
      title: '确认下架',
      content: `确定要下架商品 "${record.name}" 吗？`,
      onOk: () => {
        updateProductStatus(record.id, 'OFFLINE');
        message.success('商品已下架');
      },
    });
  };

  const handleRetrySync = (record: Product) => {
    handleSync(record);
  };

  const updateProductStatus = (productId: string, status: Product['status']) => {
    setProducts(products.map(p => 
      p.id === productId ? { ...p, status, updatedAt: moment().format('YYYY-MM-DD') } : p
    ));
  };

  const handleBatchDelete = () => {
    if (selectedRows.length === 0) {
      message.warning('请先选择要删除的商品');
      return;
    }
    Modal.confirm({
      title: '确认批量删除',
      content: `确定要删除选中的 ${selectedRows.length} 个商品吗？`,
      okText: '删除',
      okType: 'danger',
      onOk: () => {
        const ids = selectedRows.map(r => r.id);
        setProducts(products.filter(p => !ids.includes(p.id)));
        setSelectedRows([]);
        message.success(`成功删除 ${ids.length} 个商品`);
      },
    });
  };

  const handleBatchPricing = () => {
    if (selectedRows.length === 0) {
      message.warning('请先选择要定价的商品');
      return;
    }
    message.info(`批量定价功能：已选择 ${selectedRows.length} 个商品`);
  };

  const handleBatchPublish = () => {
    if (selectedRows.length === 0) {
      message.warning('请先选择要上架的商品');
      return;
    }
    const pricedProducts = selectedRows.filter(p => p.status === 'PRICED');
    if (pricedProducts.length === 0) {
      message.warning('选中的商品中没有已定价的商品');
      return;
    }
    Modal.confirm({
      title: '确认批量上架',
      content: `确定要上架选中的 ${pricedProducts.length} 个商品吗？`,
      onOk: () => {
        pricedProducts.forEach(p => updateProductStatus(p.id, 'LISTED'));
        setSelectedRows([]);
        message.success(`成功上架 ${pricedProducts.length} 个商品`);
      },
    });
  };

  const handleBatchSync = () => {
    if (selectedRows.length === 0) {
      message.warning('请先选择要同步的商品');
      return;
    }
    const listableProducts = selectedRows.filter(p => p.status === 'LISTED' || p.status === 'LIVE');
    if (listableProducts.length === 0) {
      message.warning('选中的商品中没有可同步的商品');
      return;
    }
    message.loading('正在批量同步...');
    setTimeout(() => {
      listableProducts.forEach(p => handleSync(p));
      setSelectedRows([]);
    }, 500);
  };

  const handleBatchUpdate = () => {
    if (selectedRows.length === 0) {
      message.warning('请先选择要更新的商品');
      return;
    }
    message.info(`批量更新功能：已选择 ${selectedRows.length} 个商品`);
    // 这里可以打开批量更新模态框，实现批量更新商品信息
  };

  const handleBatchExport = () => {
    if (selectedRows.length === 0) {
      message.warning('请先选择要导出的商品');
      return;
    }
    message.success(`成功导出 ${selectedRows.length} 个商品数据`);
    // 这里可以实现导出商品数据为Excel或CSV文件
  };

  const filteredProducts = products.filter(product => {
    if (filters.keyword) {
      const keywordLower = filters.keyword.toLowerCase();
      if (!product.name.toLowerCase().includes(keywordLower) && 
          !product.sku.toLowerCase().includes(keywordLower)) {
        return false;
      }
    }
    if (filters.status.length > 0 && !filters.status.includes(product.status)) {
      return false;
    }
    if (filters.category.length > 0 && !filters.category.includes(product.category)) {
      return false;
    }
    if (filters.shop.length > 0 && !filters.shop.includes(product.shopId)) {
      return false;
    }
    if (filters.priceRange) {
      const [min, max] = filters.priceRange;
      if (product.price < min || product.price > max) {
        return false;
      }
    }
    if (filters.stockRange) {
      const [min, max] = filters.stockRange;
      if (product.stock < min || product.stock > max) {
        return false;
      }
    }
    if (filters.roiRange) {
      const [min, max] = filters.roiRange;
      if (product.roi < min || product.roi > max) {
        return false;
      }
    }
    if (filters.minProfit !== null && product.profit < filters.minProfit) {
      return false;
    }
    if (filters.minStock !== null && product.stock < filters.minStock) {
      return false;
    }
    if (activePlatformTab !== 'all') {
      if (activePlatformTab === 'unpublished') {
        if (Object.keys(product.platformStatus).length > 0) {
          return false;
        }
      } else {
        if (!product.platformStatus[activePlatformTab]) {
          return false;
        }
      }
    }
    return true;
  });

  const platformStats = useMemo(() => {
    const stats: Record<string, { total: number; live: number; pending: number; failed: number }> = {
      all: { total: products.length, live: 0, pending: 0, failed: 0 },
      unpublished: { total: 0, live: 0, pending: 0, failed: 0 },
    };
    
    PLATFORMS.forEach(platform => {
      stats[platform] = { total: 0, live: 0, pending: 0, failed: 0 };
    });
    
    products.forEach(product => {
      const platforms = Object.keys(product.platformStatus);
      if (platforms.length === 0) {
        stats.unpublished.total++;
      }
      platforms.forEach(platform => {
        if (!stats[platform]) {
          stats[platform] = { total: 0, live: 0, pending: 0, failed: 0 };
        }
        stats[platform].total++;
        const status = product.platformStatus[platform];
        if (status === 'LIVE') {
          stats[platform].live++;
          stats.all.live++;
        } else if (status === 'PENDING' || status === 'SYNCING' || status === 'LISTED') {
          stats[platform].pending++;
          stats.all.pending++;
        } else if (status === 'FAILED' || status === 'SYNC_FAILED') {
          stats[platform].failed++;
          stats.all.failed++;
        }
      });
    });
    
    return stats;
  }, [products]);

  const sortedProducts = [...filteredProducts].sort((a, b) => {
    const field = sort.field as keyof Product;
    const aValue = a[field];
    const bValue = b[field];
    
    if (sort.order === 'ascend') {
      return aValue > bValue ? 1 : -1;
    } else {
      return aValue < bValue ? 1 : -1;
    }
  });

  const allColumns: ColumnsType<Product> = [
    {
      title: '商品信息',
      dataIndex: 'name',
      key: 'name',
      render: (text, record) => (
        <Space>
          <Image src={record.image} width={60} height={60} style={{ objectFit: 'cover' }} />
          <div>
            <div style={{ fontWeight: 500 }}>{text}</div>
            <div style={{ fontSize: 12, color: '#999' }}>SKU: {record.sku}</div>
            <div style={{ fontSize: 12, color: '#666' }}>{record.category}</div>
          </div>
        </Space>
      ),
      sorter: true,
    },
    {
      title: '售价',
      dataIndex: 'price',
      key: 'price',
      render: (value) => <Text strong>${value.toFixed(2)}</Text>,
      sorter: true,
    },
    {
      title: '成本',
      dataIndex: 'costPrice',
      key: 'costPrice',
      render: (value) => <Text type="secondary">${value.toFixed(2)}</Text>,
      sorter: true,
    },
    {
      title: '利润',
      dataIndex: 'profit',
      key: 'profit',
      render: (value) => <Text type="success">${value.toFixed(2)}</Text>,
      sorter: true,
    },
    {
      title: 'ROI',
      dataIndex: 'roi',
      key: 'roi',
      render: (value) => <Tag color="green">{value.toFixed(2)}%</Tag>,
      sorter: true,
    },
    {
      title: '库存',
      dataIndex: 'stock',
      key: 'stock',
      render: (value) => (
        <Badge 
          count={value} 
          style={{ backgroundColor: value > 50 ? '#52c41a' : value > 0 ? '#faad14' : '#ff4d4f' }}
        />
      ),
      sorter: true,
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status) => {
        const config = STATUS_CONFIG[status];
        return (
          <Tag color={config.color} icon={config.icon}>
            {config.text}
          </Tag>
        );
      },
      filters: Object.entries(STATUS_CONFIG).map(([key, config]) => ({
        text: config.text,
        value: key,
      })),
    },
    {
      title: '平台状态',
      key: 'platformStatus',
      render: (_, record) => (
        <Space size="small">
          {Object.entries(record.platformStatus).map(([platform, status]) => (
            <Tooltip key={platform} title={`${platform}: ${status}`}>
              <Tag 
                color={status === 'LIVE' ? 'success' : status === 'FAILED' ? 'error' : 'processing'}
              >
                {platform.charAt(0)}
              </Tag>
            </Tooltip>
          ))}
        </Space>
      ),
    },
    {
      title: '更新时间',
      dataIndex: 'updatedAt',
      key: 'updatedAt',
      sorter: true,
    },
    {
      title: '操作',
      key: 'action',
      fixed: 'right',
      width: 200,
      render: (_, record) => {
        const menu = (
          <Menu>
            <Menu.Item key="view" icon={<EyeOutlined />} onClick={() => handleViewProduct(record)}>
              查看详情
            </Menu.Item>
            <Menu.Item key="edit" icon={<EditOutlined />} onClick={() => handleEditProduct(record)}>
              编辑
            </Menu.Item>
            <Menu.Item key="duplicate" icon={<CopyOutlined />} onClick={() => handleDuplicateProduct(record)}>
              复制
            </Menu.Item>
            <Menu.Item key="pricing" icon={<DollarOutlined />} onClick={() => handlePricing(record)}>
              定价
            </Menu.Item>
            {record.status === 'PRICED' && (
              <Menu.Item key="publish" icon={<ShoppingOutlined />} onClick={() => handlePublish(record)}>
                上架
              </Menu.Item>
            )}
            {(record.status === 'LISTED' || record.status === 'LIVE') && (
              <Menu.Item 
                key="sync" 
                icon={<SyncOutlined spin={syncLoading[record.id]} />} 
                onClick={() => handleSync(record)}
                disabled={syncLoading[record.id]}
              >
                同步到平台
              </Menu.Item>
            )}
            {record.status === 'SYNC_FAILED' && (
              <Menu.Item key="retry" icon={<SyncOutlined />} onClick={() => handleRetrySync(record)}>
                重试同步
              </Menu.Item>
            )}
            {(record.status === 'LISTED' || record.status === 'LIVE') && (
              <Menu.Item key="offline" icon={<CloseCircleOutlined />} onClick={() => handleOffline(record)}>
                下架
              </Menu.Item>
            )}
            <Menu.Divider />
            <Menu.Item key="delete" icon={<DeleteOutlined />} danger onClick={() => handleDeleteProduct(record)}>
              删除
            </Menu.Item>
          </Menu>
        );

        return (
          <Space>
            <Button type="link" size="small" onClick={() => handleViewProduct(record)}>
              查看
            </Button>
            <Button type="link" size="small" onClick={() => handleEditProduct(record)}>
              编辑
            </Button>
            <Dropdown overlay={menu} placement="bottomRight">
              <Button type="link" size="small" icon={<MoreOutlined />}>
                更多
              </Button>
            </Dropdown>
          </Space>
        );
      },
    },
  ];

  const columns = columnOrder
    .filter(key => visibleColumns.includes(key))
    .map(key => allColumns.find(col => col.key === key))
    .filter(Boolean) as ColumnsType<Product>;

  const rowSelection = {
    selectedRowKeys: selectedRows.map(r => r.id),
    onChange: (selectedRowKeys: React.Key[], selectedRows: Product[]) => {
      setSelectedRows(selectedRows);
    },
  };

  return (
    <Card>
      <Alert
        message="商品管理流程说明"
        description={
          <div>
            <p>1. 新建商品：先保存到本地系统（草稿状态）</p>
            <p>2. 定价上架：完成定价后上架到本地（已上架状态）</p>
            <p>3. 平台同步：手动或自动同步到各销售平台（同步中 → 已在线）</p>
            <p>所有商品数据以本地系统为准，平台数据通过同步机制保持一致</p>
          </div>
        }
        type="info"
        showIcon
        style={{ marginBottom: 16 }}
      />
      
      <Tabs 
        activeKey={activePlatformTab} 
        onChange={setActivePlatformTab}
        tabBarExtraContent={
          <Space>
            <Button icon={<FilterOutlined />} onClick={() => setFilterVisible(true)}>
              筛选
            </Button>
            <Button icon={<SortAscendingOutlined />} onClick={() => setSortDrawerVisible(true)}>
              排序
            </Button>
            <Button icon={<AppstoreOutlined />} onClick={() => setColumnDrawerVisible(true)}>
              列设置
            </Button>
            <Button type="primary" icon={<PlusOutlined />} onClick={handleAddProduct}>
              新增商品
            </Button>
          </Space>
        }
      >
        <Tabs.TabPane
          tab={
            <span>
              <AppstoreOutlined />
              全部 ({platformStats.all?.total || 0})
            </span>
          }
          key="all"
        />
        {PLATFORMS.map(platform => {
          const config = PLATFORM_CONFIG[platform];
          const stat = platformStats[platform] || { total: 0, live: 0, pending: 0, failed: 0 };
          return (
            <Tabs.TabPane
              tab={
                <span>
                  {config.icon}
                  {platform} ({stat.total})
                  {stat.failed > 0 && (
                    <Badge count={stat.failed} size="small" style={{ marginLeft: 4 }} />
                  )}
                </span>
              }
              key={platform}
            />
          );
        })}
        <Tabs.TabPane
          tab={
            <span>
              <ExclamationCircleOutlined />
              未发布 ({platformStats.unpublished?.total || 0})
            </span>
          }
          key="unpublished"
        />
      </Tabs>
      
      {activePlatformTab !== 'all' && activePlatformTab !== 'unpublished' && (
        <Row gutter={16} style={{ marginBottom: 16 }}>
          <Col span={6}>
            <Card size="small">
              <Statistic 
                title="已在线" 
                value={platformStats[activePlatformTab]?.live || 0} 
                valueStyle={{ color: '#52c41a' }}
                prefix={<CheckCircleOutlined />}
              />
            </Card>
          </Col>
          <Col span={6}>
            <Card size="small">
              <Statistic 
                title="处理中" 
                value={platformStats[activePlatformTab]?.pending || 0} 
                valueStyle={{ color: '#1890ff' }}
                prefix={<SyncOutlined spin />}
              />
            </Card>
          </Col>
          <Col span={6}>
            <Card size="small">
              <Statistic 
                title="同步失败" 
                value={platformStats[activePlatformTab]?.failed || 0} 
                valueStyle={{ color: '#ff4d4f' }}
                prefix={<CloseCircleOutlined />}
              />
            </Card>
          </Col>
          <Col span={6}>
            <Card size="small">
              <Statistic 
                title="总计" 
                value={platformStats[activePlatformTab]?.total || 0} 
                prefix={<ShoppingOutlined />}
              />
            </Card>
          </Col>
        </Row>
      )}
      
      <Row gutter={[16, 16]} style={{ marginBottom: 16 }}>
        <Col span={24}>
          <Space style={{ display: 'flex', justifyContent: 'space-between' }}>
            <Space>
              <Title level={4} style={{ margin: 0 }}>
                {activePlatformTab === 'all' ? '全部商品' : 
                 activePlatformTab === 'unpublished' ? '未发布商品' : 
                 `${activePlatformTab} 商品`}
              </Title>
              <Badge count={sortedProducts.length} showZero style={{ backgroundColor: '#1890ff' }} />
            </Space>
          </Space>
        </Col>
        <Col span={24}>
          <Search
            placeholder="搜索商品名称或SKU"
            allowClear
            enterButton
            onSearch={handleSearch}
            style={{ maxWidth: 400 }}
          />
        </Col>
      </Row>

      {selectedRows.length > 0 && (
        <Alert
          message={`已选择 ${selectedRows.length} 项`}
          type="info"
          showIcon
          action={
            <Space>
              <Button size="small" onClick={handleBatchPricing}>
                批量定价
              </Button>
              <Button size="small" onClick={handleBatchPublish}>
                批量上架
              </Button>
              <Button size="small" onClick={handleBatchSync}>
                批量同步
              </Button>
              <Button size="small" onClick={handleBatchUpdate}>
                批量更新
              </Button>
              <Button size="small" onClick={handleBatchExport}>
                导出
              </Button>
              <Button size="small" danger onClick={handleBatchDelete}>
                批量删除
              </Button>
            </Space>
          }
          style={{ marginBottom: 16 }}
        />
      )}

      {loading ? (
        <LoadingState tip="正在加载商品数据..." />
      ) : sortedProducts.length === 0 ? (
        <EmptyState
          title="暂无商品"
          description="您还没有添加任何商品，点击下方按钮添加新商品"
          showAddButton={true}
          onAdd={handleAddProduct}
          showReloadButton={true}
          onReload={fetchProducts}
        />
      ) : (
        <Table
          rowSelection={rowSelection}
          columns={columns}
          dataSource={sortedProducts}
          rowKey="id"
          onChange={handleTableChange}
          scroll={{ x: 1200 }}
          pagination={{
            total: sortedProducts.length,
            pageSize: 10,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total) => `共 ${total} 条`,
          }}
        />
      )}

      <Drawer
        title="筛选条件"
        placement="right"
        onClose={() => setFilterVisible(false)}
        visible={filterVisible}
        width={400}
      >
        <Form layout="vertical">
          <Form.Item label="商品状态">
            <Select
              mode="multiple"
              placeholder="选择状态"
              value={filters.status}
              onChange={(value) => handleFilterChange('status', value)}
              style={{ width: '100%' }}
            >
              {Object.entries(STATUS_CONFIG).map(([key, config]) => (
                <Option key={key} value={key}>{config.text}</Option>
              ))}
            </Select>
          </Form.Item>
          <Form.Item label="商品类目">
            <Select
              mode="multiple"
              placeholder="选择类目"
              value={filters.category}
              onChange={(value) => handleFilterChange('category', value)}
              style={{ width: '100%' }}
            >
              {CATEGORIES.map(cat => (
                <Option key={cat} value={cat}>{cat}</Option>
              ))}
            </Select>
          </Form.Item>
          <Form.Item label="店铺">
            <Select
              mode="multiple"
              placeholder="选择店铺"
              value={filters.shop}
              onChange={(value) => handleFilterChange('shop', value)}
              style={{ width: '100%' }}
            >
              {SHOPS.map(shop => (
                <Option key={shop.id} value={shop.id}>
                  {shop.name} ({shop.platform})
                </Option>
              ))}
            </Select>
          </Form.Item>
          <Form.Item label="平台">
            <Select
              mode="multiple"
              placeholder="选择平台"
              value={filters.platform}
              onChange={(value) => handleFilterChange('platform', value)}
              style={{ width: '100%' }}
            >
              {PLATFORMS.map(platform => (
                <Option key={platform} value={platform}>{platform}</Option>
              ))}
            </Select>
          </Form.Item>
          <Form.Item label="价格范围">
            <Row gutter={8}>
              <Col span={11}>
                <InputNumber
                  min={0}
                  placeholder="最小"
                  value={filters.priceRange?.[0] || undefined}
                  onChange={(value) => {
                    handleFilterChange('priceRange', filters.priceRange ? [value || 0, filters.priceRange[1]] : [value || 0, 999999]);
                  }}
                  style={{ width: '100%' }}
                />
              </Col>
              <Col span={2} style={{ textAlign: 'center' }}>-
              </Col>
              <Col span={11}>
                <InputNumber
                  min={0}
                  placeholder="最大"
                  value={filters.priceRange?.[1] || undefined}
                  onChange={(value) => {
                    handleFilterChange('priceRange', filters.priceRange ? [filters.priceRange[0], value || 999999] : [0, value || 999999]);
                  }}
                  style={{ width: '100%' }}
                />
              </Col>
            </Row>
          </Form.Item>
          <Form.Item label="库存范围">
            <Row gutter={8}>
              <Col span={11}>
                <InputNumber
                  min={0}
                  placeholder="最小"
                  value={filters.stockRange?.[0] || undefined}
                  onChange={(value) => {
                    handleFilterChange('stockRange', filters.stockRange ? [value || 0, filters.stockRange[1]] : [value || 0, 999999]);
                  }}
                  style={{ width: '100%' }}
                />
              </Col>
              <Col span={2} style={{ textAlign: 'center' }}>-
              </Col>
              <Col span={11}>
                <InputNumber
                  min={0}
                  placeholder="最大"
                  value={filters.stockRange?.[1] || undefined}
                  onChange={(value) => {
                    handleFilterChange('stockRange', filters.stockRange ? [filters.stockRange[0], value || 999999] : [0, value || 999999]);
                  }}
                  style={{ width: '100%' }}
                />
              </Col>
            </Row>
          </Form.Item>
          <Form.Item label="ROI范围">
            <Row gutter={8}>
              <Col span={11}>
                <InputNumber
                  min={0}
                  placeholder="最小"
                  value={filters.roiRange?.[0] || undefined}
                  onChange={(value) => {
                    handleFilterChange('roiRange', filters.roiRange ? [value || 0, filters.roiRange[1]] : [value || 0, 999999]);
                  }}
                  style={{ width: '100%' }}
                />
              </Col>
              <Col span={2} style={{ textAlign: 'center' }}>-
              </Col>
              <Col span={11}>
                <InputNumber
                  min={0}
                  placeholder="最大"
                  value={filters.roiRange?.[1] || undefined}
                  onChange={(value) => {
                    handleFilterChange('roiRange', filters.roiRange ? [filters.roiRange[0], value || 999999] : [0, value || 999999]);
                  }}
                  style={{ width: '100%' }}
                />
              </Col>
            </Row>
          </Form.Item>
          <Form.Item label="最小利润">
            <InputNumber
              min={0}
              placeholder="输入最小利润"
              value={filters.minProfit}
              onChange={(value) => handleFilterChange('minProfit', value)}
              style={{ width: '100%' }}
            />
          </Form.Item>
          <Form.Item label="最小库存">
            <InputNumber
              min={0}
              placeholder="输入最小库存"
              value={filters.minStock}
              onChange={(value) => handleFilterChange('minStock', value)}
              style={{ width: '100%' }}
            />
          </Form.Item>
          <Form.Item label="更新时间">
            <RangePicker
              value={filters.dateRange}
              onChange={(dates) => handleFilterChange('dateRange', dates)}
              style={{ width: '100%' }}
            />
          </Form.Item>
          <Form.Item>
            <div style={{ display: 'flex', alignItems: 'center' }}>
              <input
                type="checkbox"
                checked={filters.searchInDescription}
                onChange={(e) => handleFilterChange('searchInDescription', e.target.checked)}
                style={{ marginRight: 8 }}
              />
              <label>在描述中搜索</label>
            </div>
          </Form.Item>
        </Form>
        <div style={{ position: 'absolute', bottom: 0, left: 0, right: 0, padding: 16, borderTop: '1px solid #f0f0f0', background: '#fff' }}>
          <Space style={{ display: 'flex', justifyContent: 'flex-end' }}>
            <Button onClick={handleResetFilters}>重置</Button>
            <Button type="primary" onClick={() => setFilterVisible(false)}>确定</Button>
          </Space>
        </div>
      </Drawer>

      <Drawer
        title="排序设置"
        placement="right"
        onClose={() => setSortDrawerVisible(false)}
        visible={sortDrawerVisible}
        width={300}
      >
        <Space direction="vertical" style={{ width: '100%' }}>
          {[
            { key: 'name', label: '商品名称' },
            { key: 'price', label: '售价' },
            { key: 'profit', label: '利润' },
            { key: 'roi', label: 'ROI' },
            { key: 'stock', label: '库存' },
            { key: 'updatedAt', label: '更新时间' },
          ].map(item => (
            <Card key={item.key} size="small" hoverable>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                <span>{item.label}</span>
                <Space>
                  <Button 
                    icon={<ArrowUpOutlined />}
                    type={sort.field === item.key && sort.order === 'ascend' ? 'primary' : 'default'}
                    onClick={() => handleSortChange(item.key, 'ascend')}
                  >
                    升序
                  </Button>
                  <Button 
                    icon={<ArrowDownOutlined />}
                    type={sort.field === item.key && sort.order === 'descend' ? 'primary' : 'default'}
                    onClick={() => handleSortChange(item.key, 'descend')}
                  >
                    降序
                  </Button>
                </Space>
              </div>
            </Card>
          ))}
        </Space>
      </Drawer>

      <Drawer
        title="列设置"
        placement="right"
        onClose={() => setColumnDrawerVisible(false)}
        visible={columnDrawerVisible}
        width={400}
      >
        <div style={{ marginBottom: 20 }}>
          <h3>显示列</h3>
        </div>
        <Space direction="vertical" style={{ width: '100%', marginBottom: 20 }}>
          {
            [
              { key: 'name', label: '商品信息' },
              { key: 'price', label: '售价' },
              { key: 'costPrice', label: '成本' },
              { key: 'profit', label: '利润' },
              { key: 'roi', label: 'ROI' },
              { key: 'stock', label: '库存' },
              { key: 'status', label: '状态' },
              { key: 'platformStatus', label: '平台状态' },
              { key: 'updatedAt', label: '更新时间' },
              { key: 'action', label: '操作' },
            ].map(item => (
              <div key={item.key} style={{ display: 'flex', alignItems: 'center', marginBottom: 12 }}>
                <input
                  type="checkbox"
                  checked={visibleColumns.includes(item.key)}
                  onChange={(e) => handleColumnVisibilityChange(item.key, e.target.checked)}
                  style={{ marginRight: 12 }}
                />
                <span>{item.label}</span>
              </div>
            ))
          }
        </Space>
        <div style={{ marginBottom: 20 }}>
          <h3>列顺序</h3>
          <p style={{ color: '#999', fontSize: 12 }}>拖拽调整列的显示顺序</p>
        </div>
        <div style={{ border: '1px dashed #d9d9d9', borderRadius: 4, padding: 16, minHeight: 200 }}>
          {columnOrder.map(key => {
            const columnInfo = [
              { key: 'name', label: '商品信息' },
              { key: 'price', label: '售价' },
              { key: 'costPrice', label: '成本' },
              { key: 'profit', label: '利润' },
              { key: 'roi', label: 'ROI' },
              { key: 'stock', label: '库存' },
              { key: 'status', label: '状态' },
              { key: 'platformStatus', label: '平台状态' },
              { key: 'updatedAt', label: '更新时间' },
              { key: 'action', label: '操作' },
            ].find(item => item.key === key);
            return (
              <div key={key} style={{ 
                padding: 8, 
                marginBottom: 8, 
                backgroundColor: '#f0f2f5', 
                borderRadius: 4, 
                cursor: 'move',
                display: 'flex',
                justifyContent: 'space-between',
                alignItems: 'center'
              }}>
                <span>{columnInfo?.label}</span>
                <Space size="small">
                  <Button 
                    size="small" 
                    icon={<ArrowUpOutlined />}
                    onClick={() => {
                      const currentIndex = columnOrder.indexOf(key);
                      if (currentIndex > 0) {
                        const newOrder = [...columnOrder];
                        [newOrder[currentIndex], newOrder[currentIndex - 1]] = [newOrder[currentIndex - 1], newOrder[currentIndex]];
                        handleColumnOrderChange(newOrder);
                      }
                    }}
                  />
                  <Button 
                    size="small" 
                    icon={<ArrowDownOutlined />}
                    onClick={() => {
                      const currentIndex = columnOrder.indexOf(key);
                      if (currentIndex < columnOrder.length - 1) {
                        const newOrder = [...columnOrder];
                        [newOrder[currentIndex], newOrder[currentIndex + 1]] = [newOrder[currentIndex + 1], newOrder[currentIndex]];
                        handleColumnOrderChange(newOrder);
                      }
                    }}
                  />
                </Space>
              </div>
            );
          })}
        </div>
        <div style={{ position: 'absolute', bottom: 0, left: 0, right: 0, padding: 16, borderTop: '1px solid #f0f0f0', background: '#fff' }}>
          <Space style={{ display: 'flex', justifyContent: 'flex-end' }}>
            <Button onClick={() => {
              setVisibleColumns(['name', 'price', 'costPrice', 'profit', 'roi', 'stock', 'status', 'platformStatus', 'updatedAt', 'action']);
              setColumnOrder(['name', 'price', 'costPrice', 'profit', 'roi', 'stock', 'status', 'platformStatus', 'updatedAt', 'action']);
              message.success('列设置已重置');
            }}>重置</Button>
            <Button type="primary" onClick={() => setColumnDrawerVisible(false)}>确定</Button>
          </Space>
        </div>
      </Drawer>

      <Modal
        title="商品定价"
        visible={pricingModalVisible}
        onCancel={() => setPricingModalVisible(false)}
        footer={null}
        width={600}
      >
        {currentProduct && (
          <Form layout="vertical">
            <Form.Item label="商品">
              <Text strong>{currentProduct.name}</Text>
            </Form.Item>
            <Form.Item label="当前售价">
              <Text>${currentProduct.price.toFixed(2)}</Text>
            </Form.Item>
            <Form.Item label="新售价">
              <InputNumber
                min={0}
                precision={2}
                style={{ width: '100%' }}
                placeholder="输入新售价"
              />
            </Form.Item>
            <Form.Item label="成本">
              <InputNumber
                min={0}
                precision={2}
                style={{ width: '100%' }}
                defaultValue={currentProduct.costPrice}
              />
            </Form.Item>
            <Form.Item>
              <Space>
                <Button type="primary">保存定价</Button>
                <Button onClick={() => setPricingModalVisible(false)}>取消</Button>
              </Space>
            </Form.Item>
          </Form>
        )}
      </Modal>
    </Card>
  );
};

export default ProductList;
