/**
 * [FE-ORDER-MS002] 订单聚合组件
 * 用于展示多店铺订单聚合数据的小组件
 * AI注意: 此组件可嵌入到其他页面中展示订单聚合信息
 */

import React, { useState, useEffect, useCallback } from 'react';
import {
  Card,
  Row,
  Col,
  Statistic,
  Progress,
  Tag,
  Space,
  List,
  Avatar,
  Typography,
  Spin,
  Button,
  Tooltip,
} from 'antd';
import {
  ShoppingCartOutlined,
  DollarOutlined,
  ShopOutlined,
  SyncOutlined,
  CheckCircleOutlined,
  ClockCircleOutlined,
  CloseCircleOutlined,
  RiseOutlined,
  FallOutlined,
} from '@ant-design/icons';

const { Text, Title } = Typography;

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

// 组件属性
export interface OrderAggregateProps {
  tenantId?: string;
  departmentId?: string;
  shopIds?: string[];
  showSync?: boolean;
  showTrend?: boolean;
  compact?: boolean;
  onSync?: () => void;
  style?: React.CSSProperties;
  className?: string;
}

// Mock数据
const MOCK_AGGREGATE = {
  totalOrders: 1256,
  todayOrders: 77,
  totalAmount: 256890.50,
  todayAmount: 15800.00,
  pendingOrders: 165,
  processingOrders: 85,
  completedOrders: 720,
  cancelledOrders: 56,
  completionRate: 57.3,
  todayGrowth: 12.5,
  amountGrowth: 8.3,
  topShops: [
    { id: 'shop-001', name: '上海旗舰店', platform: 'TikTok', orders: 420, amount: 89000.00, growth: 15.2 },
    { id: 'shop-002', name: '杭州分店', platform: 'Shopee', orders: 380, amount: 72000.00, growth: 8.5 },
    { id: 'shop-003', name: '广州店', platform: 'Lazada', orders: 256, amount: 45000.00, growth: -2.3 },
    { id: 'shop-004', name: '深圳店', platform: 'Amazon', orders: 200, amount: 50890.50, growth: 22.1 },
  ],
  recentOrders: [
    { id: 'ORD-001', shop: '上海旗舰店', amount: 299.99, status: 'DELIVERED', time: '10分钟前' },
    { id: 'ORD-002', shop: '杭州分店', amount: 189.50, status: 'PROCESSING', time: '25分钟前' },
    { id: 'ORD-003', shop: '广州店', amount: 459.00, status: 'PAID', time: '1小时前' },
    { id: 'ORD-004', shop: '深圳店', amount: 199.00, status: 'PENDING', time: '2小时前' },
  ],
};

const OrderAggregate: React.FC<OrderAggregateProps> = ({
  tenantId,
  departmentId,
  shopIds,
  showSync = true,
  showTrend = true,
  compact = false,
  onSync,
  style,
  className,
}) => {
  const [loading, setLoading] = useState(false);
  const [syncing, setSyncing] = useState(false);
  const [data, setData] = useState<any>(null);

  // 加载数据
  const fetchData = useCallback(async () => {
    setLoading(true);
    try {
      await new Promise(resolve => setTimeout(resolve, 500));
      setData(MOCK_AGGREGATE);
    } catch (error) {
      console.error('加载订单聚合数据失败:', error);
    } finally {
      setLoading(false);
    }
  }, [tenantId, departmentId, shopIds]);

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

  // 同步
  const handleSync = async () => {
    setSyncing(true);
    try {
      await new Promise(resolve => setTimeout(resolve, 1000));
      onSync?.();
      fetchData();
    } finally {
      setSyncing(false);
    }
  };

  if (loading) {
    return (
      <Card style={style} className={className}>
        <div style={{ textAlign: 'center', padding: 24 }}>
          <Spin tip="加载中..." />
        </div>
      </Card>
    );
  }

  if (!data) {
    return null;
  }

  // 紧凑模式
  if (compact) {
    return (
      <Card size="small" style={style} className={className}>
        <Row gutter={16}>
          <Col span={8}>
            <Statistic
              title="今日订单"
              value={data.todayOrders}
              prefix={<ShoppingCartOutlined />}
              valueStyle={{ fontSize: 18 }}
            />
          </Col>
          <Col span={8}>
            <Statistic
              title="今日金额"
              value={data.todayAmount}
              precision={2}
              prefix="¥"
              valueStyle={{ fontSize: 18 }}
            />
          </Col>
          <Col span={8}>
            <Statistic
              title="待处理"
              value={data.pendingOrders}
              valueStyle={{ fontSize: 18, color: '#faad14' }}
            />
          </Col>
        </Row>
      </Card>
    );
  }

  return (
    <Card
      style={style}
      className={className}
      title={
        <Space>
          <ShoppingCartOutlined />
          <span>订单聚合</span>
        </Space>
      }
      extra={
        showSync && (
          <Button
            type="link"
            icon={<SyncOutlined spin={syncing} />}
            onClick={handleSync}
            loading={syncing}
          >
            同步
          </Button>
        )
      }
    >
      {/* 核心指标 */}
      <Row gutter={[16, 16]}>
        <Col span={6}>
          <Card size="small" bordered={false} style={{ background: '#f5f5f5' }}>
            <Statistic
              title="今日订单"
              value={data.todayOrders}
              prefix={<ShoppingCartOutlined />}
              suffix={
                showTrend && (
                  <Text style={{ fontSize: 12, color: data.todayGrowth >= 0 ? '#52c41a' : '#f5222d' }}>
                    {data.todayGrowth >= 0 ? <RiseOutlined /> : <FallOutlined />}
                    {Math.abs(data.todayGrowth)}%
                  </Text>
                )
              }
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card size="small" bordered={false} style={{ background: '#f5f5f5' }}>
            <Statistic
              title="今日金额"
              value={data.todayAmount}
              precision={2}
              prefix={<DollarOutlined />}
              suffix={
                showTrend && (
                  <Text style={{ fontSize: 12, color: data.amountGrowth >= 0 ? '#52c41a' : '#f5222d' }}>
                    {data.amountGrowth >= 0 ? <RiseOutlined /> : <FallOutlined />}
                    {Math.abs(data.amountGrowth)}%
                  </Text>
                )
              }
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card size="small" bordered={false} style={{ background: '#f5f5f5' }}>
            <Statistic
              title="待处理"
              value={data.pendingOrders}
              valueStyle={{ color: '#faad14' }}
              prefix={<ClockCircleOutlined />}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card size="small" bordered={false} style={{ background: '#f5f5f5' }}>
            <Statistic
              title="完成率"
              value={data.completionRate}
              suffix="%"
              valueStyle={{ color: '#52c41a' }}
              prefix={<CheckCircleOutlined />}
            />
          </Card>
        </Col>
      </Row>

      {/* 完成进度 */}
      <div style={{ marginTop: 16, marginBottom: 16 }}>
        <Text type="secondary">订单完成进度</Text>
        <Progress
          percent={data.completionRate}
          status="active"
          strokeColor={{
            '0%': '#108ee9',
            '100%': '#87d068',
          }}
        />
      </div>

      {/* 状态分布 */}
      <Row gutter={16} style={{ marginBottom: 16 }}>
        <Col span={6}>
          <Space>
            <ClockCircleOutlined style={{ color: '#faad14' }} />
            <Text>待处理: {data.pendingOrders}</Text>
          </Space>
        </Col>
        <Col span={6}>
          <Space>
            <ClockCircleOutlined style={{ color: '#1890ff' }} />
            <Text>处理中: {data.processingOrders}</Text>
          </Space>
        </Col>
        <Col span={6}>
          <Space>
            <CheckCircleOutlined style={{ color: '#52c41a' }} />
            <Text>已完成: {data.completedOrders}</Text>
          </Space>
        </Col>
        <Col span={6}>
          <Space>
            <CloseCircleOutlined style={{ color: '#f5222d' }} />
            <Text>已取消: {data.cancelledOrders}</Text>
          </Space>
        </Col>
      </Row>

      {/* 店铺排行 */}
      <Card size="small" title="店铺排行" style={{ marginBottom: 16 }}>
        <List
          dataSource={data.topShops}
          renderItem={(shop: any, index: number) => (
            <List.Item>
              <List.Item.Meta
                avatar={
                  <Avatar style={{ backgroundColor: index < 3 ? '#faad14' : '#1890ff' }}>
                    {index + 1}
                  </Avatar>
                }
                title={
                  <Space>
                    <ShopOutlined />
                    <span>{shop.name}</span>
                    <Tag color={PLATFORM_COLORS[shop.platform] || 'default'}>
                      {shop.platform}
                    </Tag>
                  </Space>
                }
                description={
                  <Space split={<Text type="secondary">|</Text>}>
                    <Text>订单: {shop.orders}</Text>
                    <Text>金额: ¥{shop.amount.toFixed(2)}</Text>
                    <Text style={{ color: shop.growth >= 0 ? '#52c41a' : '#f5222d' }}>
                      {shop.growth >= 0 ? <RiseOutlined /> : <FallOutlined />}
                      {Math.abs(shop.growth)}%
                    </Text>
                  </Space>
                }
              />
            </List.Item>
          )}
        />
      </Card>

      {/* 最近订单 */}
      <Card size="small" title="最近订单">
        <List
          size="small"
          dataSource={data.recentOrders}
          renderItem={(order: any) => (
            <List.Item>
              <List.Item.Meta
                avatar={<Avatar icon={<ShoppingCartOutlined />} />}
                title={
                  <Space>
                    <Text>{order.id}</Text>
                    <Text type="secondary">{order.shop}</Text>
                  </Space>
                }
                description={
                  <Space>
                    <Text strong style={{ color: '#f5222d' }}>¥{order.amount.toFixed(2)}</Text>
                    <Tag color={order.status === 'DELIVERED' ? 'success' : order.status === 'PROCESSING' ? 'processing' : 'default'}>
                      {order.status}
                    </Tag>
                    <Text type="secondary">{order.time}</Text>
                  </Space>
                }
              />
            </List.Item>
          )}
        />
      </Card>
    </Card>
  );
};

export default OrderAggregate;
