import React, { useState, useEffect } from 'react';
import { Table, Input, Button, Select, DatePicker, message, Card, Typography, Tag } from 'antd';
import { SearchOutlined, EyeOutlined, ReloadOutlined } from '@ant-design/icons';
import { merchantDataSource, MerchantOrder } from '@/services/merchantDataSource';

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

const MerchantOrderManage: React.FC = () => {
  const [orders, setOrders] = useState<Order[]>([]);
  const [merchants, setMerchants] = useState<{ id: string; companyName: string }[]>([]);
  const [loading, setLoading] = useState(false);
  const [searchText, setSearchText] = useState('');
  const [merchantFilter, setMerchantFilter] = useState<string>('');
  const [platformFilter, setPlatformFilter] = useState<string>('');
  const [statusFilter, setStatusFilter] = useState<string>('');
  const [dateRange, setDateRange] = useState<[string, string] | null>(null);

  const fetchOrders = async () => {
    setLoading(true);
    try {
      const response = await getMerchantOrders();
      setOrders(response.data);
    } catch (error) {
      message.error('获取订单列表失败');
      console.error('获取订单列表失败:', error);
    } finally {
      setLoading(false);
    }
  };

  const fetchMerchants = async () => {
    try {
      // 实际项目中应该调用获取商户列表的API
      // 这里模拟数据
      setMerchants([
        { id: '1', companyName: '商户A' },
        { id: '2', companyName: '商户B' },
        { id: '3', companyName: '商户C' },
      ]);
    } catch (error) {
      console.error('获取商户列表失败:', error);
    }
  };

  useEffect(() => {
    fetchMerchants();
    fetchOrders();
  }, []);

  const handleSearch = (value: string) => {
    setSearchText(value);
  };

  const handleMerchantFilter = (value: string) => {
    setMerchantFilter(value);
  };

  const handlePlatformFilter = (value: string) => {
    setPlatformFilter(value);
  };

  const handleStatusFilter = (value: string) => {
    setStatusFilter(value);
  };

  const handleDateRangeChange = (dates: any) => {
    if (dates) {
      setDateRange([dates[0].format('YYYY-MM-DD'), dates[1].format('YYYY-MM-DD')]);
    } else {
      setDateRange(null);
    }
  };

  const filteredOrders = orders.filter(order => {
    const matchesSearch = order.orderId.includes(searchText) ||
                        order.merchantName.toLowerCase().includes(searchText.toLowerCase());
    const matchesMerchant = merchantFilter ? order.merchantId === merchantFilter : true;
    const matchesPlatform = platformFilter ? order.platform === platformFilter : true;
    const matchesStatus = statusFilter ? order.status === statusFilter : true;
    return matchesSearch && matchesMerchant && matchesPlatform && matchesStatus;
  });

  const handleView = (order: Order) => {
    // 跳转到订单详情页面
    message.info(`查看订单详情: ${order.orderId}`);
  };

  const handleStatusUpdate = (order: Order, newStatus: Order['status']) => {
    // 调用API更新订单状态
    message.info(`更新订单 ${order.orderId} 状态为: ${newStatus}`);
  };

  const handleRefresh = () => {
    fetchOrders();
  };

  const getStatusTag = (status: string) => {
    const statusConfig: Record<string, { color: string; text: string }> = {
      PENDING: { color: 'blue', text: '待处理' },
      PROCESSING: { color: 'orange', text: '处理中' },
      SHIPPED: { color: 'purple', text: '已发货' },
      DELIVERED: { color: 'green', text: '已送达' },
      CANCELLED: { color: 'gray', text: '已取消' },
      REFUNDED: { color: 'red', text: '已退款' },
    };
    const config = statusConfig[status] || { color: 'default', text: status };
    return <Tag color={config.color}>{config.text}</Tag>;
  };

  const columns = [
    {
      title: '订单ID',
      dataIndex: 'id',
      key: 'id',
      ellipsis: true,
    },
    {
      title: '平台订单号',
      dataIndex: 'orderId',
      key: 'orderId',
      ellipsis: true,
    },
    {
      title: '商户',
      dataIndex: 'merchantName',
      key: 'merchantName',
      ellipsis: true,
    },
    {
      title: '平台',
      dataIndex: 'platform',
      key: 'platform',
      ellipsis: true,
    },
    {
      title: '总金额',
      dataIndex: 'totalAmount',
      key: 'totalAmount',
      render: (amount: number) => <Text>${amount.toFixed(2)}</Text>,
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status: string) => getStatusTag(status),
    },
    {
      title: '创建时间',
      dataIndex: 'createdAt',
      key: 'createdAt',
      ellipsis: true,
    },
    {
      title: '操作',
      key: 'action',
      render: (_: any, order: Order) => (
        <div>
          <Button 
            icon={<EyeOutlined />} 
            size="small" 
            style={{ marginRight: 8 }}
            onClick={() => handleView(order)}
          >
            查看
          </Button>
          <Select
            defaultValue={order.status}
            style={{ width: 120 }}
            onChange={(value) => handleStatusUpdate(order, value)}
          >
            <Option value="PENDING">待处理</Option>
            <Option value="PROCESSING">处理中</Option>
            <Option value="SHIPPED">已发货</Option>
            <Option value="DELIVERED">已送达</Option>
            <Option value="CANCELLED">已取消</Option>
            <Option value="REFUNDED">已退款</Option>
          </Select>
        </div>
      ),
    },
  ];

  return (
    <Card>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 24 }}>
        <Title level={4}>多商户订单管理</Title>
        <Button 
          icon={<ReloadOutlined />}
          onClick={handleRefresh}
        >
          刷新
        </Button>
      </div>

      <div style={{ display: 'flex', marginBottom: 16, gap: 16, flexWrap: 'wrap' }}>
        <Input
          placeholder="搜索订单号或商户名称"
          prefix={<SearchOutlined />}
          style={{ width: 300 }}
          onChange={(e) => handleSearch(e.target.value)}
        />
        <Select
          placeholder="筛选商户"
          style={{ width: 200 }}
          onChange={handleMerchantFilter}
          allowClear
        >
          {merchants.map(merchant => (
            <Option key={merchant.id} value={merchant.id}>
              {merchant.companyName}
            </Option>
          ))}
        </Select>
        <Select
          placeholder="筛选平台"
          style={{ width: 120 }}
          onChange={handlePlatformFilter}
          allowClear
        >
          <Option value="Amazon">Amazon</Option>
          <Option value="eBay">eBay</Option>
          <Option value="Shopee">Shopee</Option>
          <Option value="TikTok">TikTok</Option>
        </Select>
        <Select
          placeholder="筛选状态"
          style={{ width: 120 }}
          onChange={handleStatusFilter}
          allowClear
        >
          <Option value="PENDING">待处理</Option>
          <Option value="PROCESSING">处理中</Option>
          <Option value="SHIPPED">已发货</Option>
          <Option value="DELIVERED">已送达</Option>
          <Option value="CANCELLED">已取消</Option>
          <Option value="REFUNDED">已退款</Option>
        </Select>
        <RangePicker
          placeholder={['开始日期', '结束日期']}
          onChange={handleDateRangeChange}
        />
      </div>

      <Table
        columns={columns}
        dataSource={filteredOrders}
        rowKey="id"
        loading={loading}
        pagination={{
          showSizeChanger: true,
          pageSizeOptions: ['10', '20', '50'],
          defaultPageSize: 10,
        }}
      />
    </Card>
  );
};

export default MerchantOrderManage;