/**
 * [FE-ORDER-MS001] 订单多店铺管理页面
 * 支持多店铺订单聚合展示、统计、同步等功能
 * AI注意: 此页面用于多店铺订单统一管理
 */

import React, { useState, useEffect, useCallback } from 'react';
import {
  Card,
  Table,
  Tag,
  Space,
  Button,
  DatePicker,
  Select,
  Input,
  Row,
  Col,
  Statistic,
  Tooltip,
  Drawer,
  Descriptions,
  Badge,
  Spin,
  message,
  Typography,
  Tabs,
  Progress,
  List,
  Avatar,
  Divider,
} from 'antd';
import {
  SearchOutlined,
  ReloadOutlined,
  SyncOutlined,
  ShopOutlined,
  DollarOutlined,
  ShoppingCartOutlined,
  CheckCircleOutlined,
  ClockCircleOutlined,
  CloseCircleOutlined,
  LineChartOutlined,
  PieChartOutlined,
} from '@ant-design/icons';
import { Line, Pie, Column } from '@ant-design/charts';
import moment from 'moment';
import HierarchySelector from '../../components/HierarchySelector';

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

// 订单状态
const ORDER_STATUS = {
  PENDING: { label: '待付款', color: 'default', icon: <ClockCircleOutlined /> },
  PAID: { label: '已付款', color: 'processing', icon: <CheckCircleOutlined /> },
  PROCESSING: { label: '处理中', color: 'blue', icon: <ClockCircleOutlined /> },
  SHIPPED: { label: '已发货', color: 'cyan', icon: <CheckCircleOutlined /> },
  DELIVERED: { label: '已完成', color: 'success', icon: <CheckCircleOutlined /> },
  CANCELLED: { label: '已取消', color: 'error', icon: <CloseCircleOutlined /> },
  REFUNDED: { label: '已退款', color: 'warning', icon: <CloseCircleOutlined /> },
};

// 平台颜色
const PLATFORM_COLORS: Record<string, string> = {
  TikTok: 'pink',
  Shopee: 'orange',
  Lazada: 'blue',
  Amazon: 'cyan',
  eBay: 'yellow',
  '1688': 'red',
};

// Mock数据 - 聚合统计
const MOCK_STATS = {
  totalOrders: 1256,
  totalAmount: 256890.50,
  totalProducts: 3890,
  byStatus: {
    PENDING: { count: 45, amount: 8900.00 },
    PAID: { count: 120, amount: 25600.00 },
    PROCESSING: { count: 85, amount: 18900.00 },
    SHIPPED: { count: 230, amount: 52000.00 },
    DELIVERED: { count: 720, amount: 145000.00 },
    CANCELLED: { count: 35, amount: 5200.00 },
    REFUNDED: { count: 21, amount: 1290.50 },
  },
  byShop: {
    'shop-001': { count: 420, amount: 89000.00, shopName: '上海旗舰店' },
    'shop-002': { count: 380, amount: 72000.00, shopName: '杭州分店' },
    'shop-003': { count: 256, amount: 45000.00, shopName: '广州店' },
    'shop-004': { count: 200, amount: 50890.50, shopName: '深圳店' },
  },
  byPlatform: {
    TikTok: { count: 520, amount: 108000.00 },
    Shopee: { count: 380, amount: 78000.00 },
    Lazada: { count: 256, amount: 52000.00 },
    Amazon: { count: 100, amount: 18890.50 },
  },
  pendingOrders: 165,
  processingOrders: 85,
  completedOrders: 720,
  cancelledOrders: 56,
};

// Mock数据 - 店铺概览
const MOCK_SHOP_OVERVIEWS = [
  {
    shopId: 'shop-001',
    shopName: '上海旗舰店',
    platform: 'TikTok',
    totalOrders: 420,
    todayOrders: 28,
    pendingOrders: 15,
    processingOrders: 12,
    completedOrders: 380,
    totalAmount: 89000.00,
    todayAmount: 5600.00,
    avgOrderValue: 211.90,
    topProducts: [
      { productId: 'P001', productName: '智能手表', quantity: 156, amount: 23400.00 },
      { productId: 'P002', productName: '无线耳机', quantity: 120, amount: 18000.00 },
      { productId: 'P003', productName: '手机壳', quantity: 89, amount: 4450.00 },
    ],
  },
  {
    shopId: 'shop-002',
    shopName: '杭州分店',
    platform: 'Shopee',
    totalOrders: 380,
    todayOrders: 22,
    pendingOrders: 18,
    processingOrders: 10,
    completedOrders: 340,
    totalAmount: 72000.00,
    todayAmount: 4200.00,
    avgOrderValue: 189.47,
    topProducts: [
      { productId: 'P004', productName: '运动鞋', quantity: 98, amount: 19600.00 },
      { productId: 'P005', productName: 'T恤', quantity: 145, amount: 14500.00 },
    ],
  },
  {
    shopId: 'shop-003',
    shopName: '广州店',
    platform: 'Lazada',
    totalOrders: 256,
    todayOrders: 15,
    pendingOrders: 12,
    processingOrders: 8,
    completedOrders: 230,
    totalAmount: 45000.00,
    todayAmount: 2800.00,
    avgOrderValue: 175.78,
    topProducts: [
      { productId: 'P006', productName: '背包', quantity: 78, amount: 12480.00 },
    ],
  },
  {
    shopId: 'shop-004',
    shopName: '深圳店',
    platform: 'Amazon',
    totalOrders: 200,
    todayOrders: 12,
    pendingOrders: 10,
    processingOrders: 6,
    completedOrders: 178,
    totalAmount: 50890.50,
    todayAmount: 3200.00,
    avgOrderValue: 254.45,
    topProducts: [
      { productId: 'P007', productName: '电子产品', quantity: 45, amount: 22500.00 },
    ],
  },
];

// Mock数据 - 订单列表
const MOCK_ORDERS = [
  {
    id: 'ORD-001',
    platform_order_id: 'TK-20260321001',
    shop_id: 'shop-001',
    shop_name: '上海旗舰店',
    platform: 'TikTok',
    status: 'DELIVERED',
    total_amount: 299.99,
    product_count: 2,
    customer_name: '张三',
    created_at: '2026-03-21T10:00:00Z',
  },
  {
    id: 'ORD-002',
    platform_order_id: 'SP-20260321002',
    shop_id: 'shop-002',
    shop_name: '杭州分店',
    platform: 'Shopee',
    status: 'PROCESSING',
    total_amount: 189.50,
    product_count: 1,
    customer_name: '李四',
    created_at: '2026-03-21T09:30:00Z',
  },
  {
    id: 'ORD-003',
    platform_order_id: 'LZ-20260321003',
    shop_id: 'shop-003',
    shop_name: '广州店',
    platform: 'Lazada',
    status: 'PAID',
    total_amount: 459.00,
    product_count: 3,
    customer_name: '王五',
    created_at: '2026-03-21T09:00:00Z',
  },
];

// Mock数据 - 趋势
const MOCK_TREND = [
  { date: '2026-03-15', count: 120, amount: 24000 },
  { date: '2026-03-16', count: 145, amount: 29000 },
  { date: '2026-03-17', count: 132, amount: 26400 },
  { date: '2026-03-18', count: 168, amount: 33600 },
  { date: '2026-03-19', count: 155, amount: 31000 },
  { date: '2026-03-20', count: 180, amount: 36000 },
  { date: '2026-03-21', count: 142, amount: 28400 },
];

const OrderMultiShopList: React.FC = () => {
  const [loading, setLoading] = useState(false);
  const [syncing, setSyncing] = useState(false);
  const [stats, setStats] = useState<any>(null);
  const [shopOverviews, setShopOverviews] = useState<any[]>([]);
  const [orders, setOrders] = useState<any[]>([]);
  const [trend, setTrend] = useState<any[]>([]);
  const [selectedShop, setSelectedShop] = useState<any>(null);
  const [detailVisible, setDetailVisible] = useState(false);
  const [filters, setFilters] = useState({
    platforms: [],
    status: [],
    dateRange: null,
    search: '',
  });
  const [hierarchySelection, setHierarchySelection] = useState<any>(null);
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0,
  });

  // 加载数据
  const fetchData = useCallback(async () => {
    setLoading(true);
    try {
      await new Promise(resolve => setTimeout(resolve, 500));
      setStats(MOCK_STATS);
      setShopOverviews(MOCK_SHOP_OVERVIEWS);
      setOrders(MOCK_ORDERS);
      setTrend(MOCK_TREND);
      setPagination(prev => ({ ...prev, total: 100 }));
    } catch (error) {
      message.error('加载数据失败');
    } finally {
      setLoading(false);
    }
  }, []);

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

  // 同步订单
  const handleSync = async () => {
    setSyncing(true);
    try {
      await new Promise(resolve => setTimeout(resolve, 2000));
      message.success('订单同步成功');
      fetchData();
    } catch (error) {
      message.error('订单同步失败');
    } finally {
      setSyncing(false);
    }
  };

  // 表格列
  const columns = [
    {
      title: '订单号',
      dataIndex: 'platform_order_id',
      key: 'platform_order_id',
      width: 150,
      render: (id: string, record: any) => (
        <Space direction="vertical" size={0}>
          <Text copyable>{id}</Text>
          <Text type="secondary" style={{ fontSize: 12 }}>{record.id}</Text>
        </Space>
      ),
    },
    {
      title: '店铺',
      dataIndex: 'shop_name',
      key: 'shop_name',
      width: 150,
      render: (name: string, record: any) => (
        <Space>
          <ShopOutlined />
          <span>{name}</span>
          <Tag color={PLATFORM_COLORS[record.platform] || 'default'}>
            {record.platform}
          </Tag>
        </Space>
      ),
    },
    {
      title: '客户',
      dataIndex: 'customer_name',
      key: 'customer_name',
      width: 100,
    },
    {
      title: '商品数',
      dataIndex: 'product_count',
      key: 'product_count',
      width: 80,
      align: 'center',
    },
    {
      title: '金额',
      dataIndex: 'total_amount',
      key: 'total_amount',
      width: 120,
      align: 'right',
      render: (amount: number) => (
        <Text strong style={{ color: '#f5222d' }}>
          ¥{amount.toFixed(2)}
        </Text>
      ),
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: 100,
      render: (status: keyof typeof ORDER_STATUS) => {
        const config = ORDER_STATUS[status];
        return (
          <Tag icon={config.icon} color={config.color}>
            {config.label}
          </Tag>
        );
      },
    },
    {
      title: '下单时间',
      dataIndex: 'created_at',
      key: 'created_at',
      width: 180,
      render: (time: string) => moment(time).format('YYYY-MM-DD HH:mm:ss'),
    },
    {
      title: '操作',
      key: 'action',
      width: 100,
      fixed: 'right',
      render: (_: any, record: any) => (
        <Button
          type="link"
          size="small"
          onClick={() => {
            setSelectedShop(record);
            setDetailVisible(true);
          }}
        >
          详情
        </Button>
      ),
    },
  ];

  // 趋势图配置
  const trendConfig = {
    data: trend,
    xField: 'date',
    yField: 'count',
    seriesField: 'type',
    smooth: true,
    point: { size: 4, shape: 'circle' },
  };

  // 金额趋势图配置
  const amountTrendConfig = {
    data: trend,
    xField: 'date',
    yField: 'amount',
    seriesField: 'type',
    smooth: true,
    point: { size: 4, shape: 'circle' },
  };

  // 平台分布图配置
  const platformPieConfig = {
    data: stats ? Object.entries(stats.byPlatform).map(([platform, data]: [string, any]) => ({
      type: platform,
      value: data.count,
    })) : [],
    angleField: 'value',
    colorField: 'type',
    radius: 0.8,
    label: { type: 'outer', content: '{name} {percentage}' },
  };

  // 店铺分布图配置
  const shopColumnConfig = {
    data: shopOverviews,
    xField: 'shopName',
    yField: 'totalAmount',
    label: { position: 'top' },
    color: '#1890ff',
  };

  return (
    <div style={{ padding: 24 }}>
      <Title level={2}>订单多店铺管理</Title>
      <Text type="secondary">统一管理多店铺订单，支持聚合统计、订单同步、趋势分析</Text>

      {/* 层级选择器 */}
      <Card style={{ marginTop: 16, marginBottom: 16 }}>
        <Row gutter={16} align="middle">
          <Col span={12}>
            <Space>
              <Text strong>选择范围：</Text>
              <HierarchySelector
                mode="cascader"
                maxLevel="SHOP"
                onChange={setHierarchySelection}
                placeholder="选择部门/店铺"
                style={{ width: 300 }}
              />
            </Space>
          </Col>
          <Col span={12} style={{ textAlign: 'right' }}>
            <Button
              type="primary"
              icon={<SyncOutlined spin={syncing} />}
              onClick={handleSync}
              loading={syncing}
            >
              同步订单
            </Button>
          </Col>
        </Row>
      </Card>

      {/* 统计卡片 */}
      <Row gutter={16} style={{ marginBottom: 24 }}>
        <Col span={4}>
          <Card>
            <Statistic
              title="总订单数"
              value={stats?.totalOrders || 0}
              prefix={<ShoppingCartOutlined />}
            />
          </Card>
        </Col>
        <Col span={4}>
          <Card>
            <Statistic
              title="总金额"
              value={stats?.totalAmount || 0}
              precision={2}
              prefix={<DollarOutlined />}
              suffix="元"
            />
          </Card>
        </Col>
        <Col span={4}>
          <Card>
            <Statistic
              title="待处理"
              value={stats?.pendingOrders || 0}
              valueStyle={{ color: '#faad14' }}
              prefix={<ClockCircleOutlined />}
            />
          </Card>
        </Col>
        <Col span={4}>
          <Card>
            <Statistic
              title="处理中"
              value={stats?.processingOrders || 0}
              valueStyle={{ color: '#1890ff' }}
              prefix={<ClockCircleOutlined />}
            />
          </Card>
        </Col>
        <Col span={4}>
          <Card>
            <Statistic
              title="已完成"
              value={stats?.completedOrders || 0}
              valueStyle={{ color: '#52c41a' }}
              prefix={<CheckCircleOutlined />}
            />
          </Card>
        </Col>
        <Col span={4}>
          <Card>
            <Statistic
              title="已取消"
              value={stats?.cancelledOrders || 0}
              valueStyle={{ color: '#f5222d' }}
              prefix={<CloseCircleOutlined />}
            />
          </Card>
        </Col>
      </Row>

      {/* 图表区域 */}
      <Row gutter={16} style={{ marginBottom: 24 }}>
        <Col span={12}>
          <Card title="订单趋势" extra={<LineChartOutlined />}>
            {trend.length > 0 && <Line {...trendConfig} />}
          </Card>
        </Col>
        <Col span={12}>
          <Card title="金额趋势" extra={<LineChartOutlined />}>
            {trend.length > 0 && <Line {...amountTrendConfig} />}
          </Card>
        </Col>
      </Row>

      <Row gutter={16} style={{ marginBottom: 24 }}>
        <Col span={12}>
          <Card title="平台分布" extra={<PieChartOutlined />}>
            {stats && <Pie {...platformPieConfig} />}
          </Card>
        </Col>
        <Col span={12}>
          <Card title="店铺销售额" extra={<ShopOutlined />}>
            {shopOverviews.length > 0 && <Column {...shopColumnConfig} />}
          </Card>
        </Col>
      </Row>

      {/* 店铺概览 */}
      <Card title="店铺概览" style={{ marginBottom: 24 }}>
        <Row gutter={[16, 16]}>
          {shopOverviews.map(shop => (
            <Col span={6} key={shop.shopId}>
              <Card
                size="small"
                hoverable
                onClick={() => {
                  setSelectedShop(shop);
                  setDetailVisible(true);
                }}
              >
                <Space direction="vertical" style={{ width: '100%' }}>
                  <Space>
                    <ShopOutlined />
                    <Text strong>{shop.shopName}</Text>
                    <Tag color={PLATFORM_COLORS[shop.platform] || 'default'}>
                      {shop.platform}
                    </Tag>
                  </Space>
                  <Row gutter={8}>
                    <Col span={12}>
                      <Statistic
                        title="今日订单"
                        value={shop.todayOrders}
                        valueStyle={{ fontSize: 16 }}
                      />
                    </Col>
                    <Col span={12}>
                      <Statistic
                        title="今日金额"
                        value={shop.todayAmount}
                        precision={2}
                        prefix="¥"
                        valueStyle={{ fontSize: 16 }}
                      />
                    </Col>
                  </Row>
                  <Progress
                    percent={Math.round((shop.completedOrders / shop.totalOrders) * 100)}
                    size="small"
                    status="active"
                    format={() => `完成率 ${Math.round((shop.completedOrders / shop.totalOrders) * 100)}%`}
                  />
                </Space>
              </Card>
            </Col>
          ))}
        </Row>
      </Card>

      {/* 筛选区域 */}
      <Card style={{ marginBottom: 24 }}>
        <Space wrap>
          <Select
            mode="multiple"
            placeholder="平台"
            style={{ width: 200 }}
            allowClear
            value={filters.platforms}
            onChange={value => setFilters(prev => ({ ...prev, platforms: value }))}
          >
            <Option value="TikTok">TikTok</Option>
            <Option value="Shopee">Shopee</Option>
            <Option value="Lazada">Lazada</Option>
            <Option value="Amazon">Amazon</Option>
            <Option value="eBay">eBay</Option>
            <Option value="1688">1688</Option>
          </Select>
          <Select
            mode="multiple"
            placeholder="状态"
            style={{ width: 200 }}
            allowClear
            value={filters.status}
            onChange={value => setFilters(prev => ({ ...prev, status: value }))}
          >
            {Object.entries(ORDER_STATUS).map(([key, config]) => (
              <Option key={key} value={key}>{config.label}</Option>
            ))}
          </Select>
          <RangePicker
            value={filters.dateRange}
            onChange={dates => setFilters(prev => ({ ...prev, dateRange: dates }))}
          />
          <Search
            placeholder="搜索订单号/客户名"
            style={{ width: 200 }}
            value={filters.search}
            onChange={e => setFilters(prev => ({ ...prev, search: e.target.value }))}
          />
          <Button type="primary" icon={<SearchOutlined />} onClick={fetchData}>
            查询
          </Button>
          <Button icon={<ReloadOutlined />} onClick={fetchData}>
            刷新
          </Button>
        </Space>
      </Card>

      {/* 订单表格 */}
      <Card>
        <Table
          columns={columns}
          dataSource={orders}
          rowKey="id"
          loading={loading}
          pagination={{
            ...pagination,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: total => `共 ${total} 条记录`,
          }}
          onChange={setPagination}
          scroll={{ x: 1200 }}
        />
      </Card>

      {/* 详情抽屉 */}
      <Drawer
        title="订单详情"
        width={600}
        visible={detailVisible}
        onClose={() => setDetailVisible(false)}
      >
        {selectedShop && (
          <Tabs defaultActiveKey="info">
            <TabPane tab="基本信息" key="info">
              <Descriptions bordered column={2}>
                <Descriptions.Item label="订单号">{selectedShop.platform_order_id || selectedShop.shopId}</Descriptions.Item>
                <Descriptions.Item label="店铺">{selectedShop.shop_name || selectedShop.shopName}</Descriptions.Item>
                <Descriptions.Item label="平台">
                  <Tag color={PLATFORM_COLORS[selectedShop.platform] || 'default'}>
                    {selectedShop.platform}
                  </Tag>
                </Descriptions.Item>
                <Descriptions.Item label="状态">
                  {selectedShop.status && ORDER_STATUS[selectedShop.status] && (
                    <Tag color={ORDER_STATUS[selectedShop.status].color}>
                      {ORDER_STATUS[selectedShop.status].label}
                    </Tag>
                  )}
                </Descriptions.Item>
                <Descriptions.Item label="总订单数">{selectedShop.totalOrders}</Descriptions.Item>
                <Descriptions.Item label="今日订单">{selectedShop.todayOrders}</Descriptions.Item>
                <Descriptions.Item label="总金额">¥{(selectedShop.totalAmount || 0).toFixed(2)}</Descriptions.Item>
                <Descriptions.Item label="今日金额">¥{(selectedShop.todayAmount || 0).toFixed(2)}</Descriptions.Item>
                <Descriptions.Item label="客单价">¥{(selectedShop.avgOrderValue || 0).toFixed(2)}</Descriptions.Item>
                <Descriptions.Item label="待处理订单">{selectedShop.pendingOrders}</Descriptions.Item>
              </Descriptions>

              {selectedShop.topProducts && (
                <>
                  <Divider>热销商品</Divider>
                  <List
                    dataSource={selectedShop.topProducts}
                    renderItem={(item: any) => (
                      <List.Item>
                        <List.Item.Meta
                          avatar={<Avatar style={{ backgroundColor: '#1890ff' }}>{item.productName[0]}</Avatar>}
                          title={item.productName}
                          description={`销量: ${item.quantity} | 金额: ¥${item.amount.toFixed(2)}`}
                        />
                      </List.Item>
                    )}
                  />
                </>
              )}
            </TabPane>
            <TabPane tab="订单统计" key="stats">
              <Row gutter={[16, 16]}>
                <Col span={12}>
                  <Card size="small">
                    <Statistic title="待处理" value={selectedShop.pendingOrders || 0} />
                  </Card>
                </Col>
                <Col span={12}>
                  <Card size="small">
                    <Statistic title="处理中" value={selectedShop.processingOrders || 0} />
                  </Card>
                </Col>
                <Col span={12}>
                  <Card size="small">
                    <Statistic title="已完成" value={selectedShop.completedOrders || 0} />
                  </Card>
                </Col>
                <Col span={12}>
                  <Card size="small">
                    <Statistic title="完成率" value={Math.round((selectedShop.completedOrders / selectedShop.totalOrders) * 100)} suffix="%" />
                  </Card>
                </Col>
              </Row>
            </TabPane>
          </Tabs>
        )}
      </Drawer>
    </div>
  );
};

export default OrderMultiShopList;
