/**
 * [FE-SHOP-REP001] 多店铺报表聚合页面
 * 支持销售报表、利润报表、库存报表、流量报表、转化报表
 * AI注意: 此页面用于多店铺报表统一展示和分析
 */

import React, { useState, useEffect, useCallback } from 'react';
import {
  Card,
  Tabs,
  Row,
  Col,
  Statistic,
  Table,
  Tag,
  Space,
  Button,
  DatePicker,
  Select,
  Typography,
  Progress,
  List,
  Avatar,
  Spin,
  message,
  Dropdown,
  Menu,
  Tooltip,
  Badge,
} from 'antd';
import {
  DollarOutlined,
  ShoppingCartOutlined,
  RiseOutlined,
  FallOutlined,
  DownloadOutlined,
  ShopOutlined,
  StockOutlined,
  EyeOutlined,
  PercentageOutlined,
  AlertOutlined,
  ArrowUpOutlined,
  ArrowDownOutlined,
} from '@ant-design/icons';
import { Line, Column, Pie, Area, Funnel } from '@ant-design/charts';
import moment from 'moment';
import HierarchySelector from '../../components/HierarchySelector';

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

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

// Mock数据 - 销售报表
const MOCK_SALES_REPORT = {
  totalSales: 568900.50,
  totalOrders: 2856,
  totalProducts: 8920,
  avgOrderValue: 199.33,
  salesGrowth: 18.5,
  orderGrowth: 12.3,
  byShop: [
    { shopId: 'shop-001', shopName: '上海旗舰店', platform: 'TikTok', sales: 198000, orders: 980, growth: 22.5, contribution: 34.8 },
    { shopId: 'shop-002', shopName: '杭州分店', platform: 'Shopee', sales: 156000, orders: 820, growth: 15.2, contribution: 27.4 },
    { shopId: 'shop-003', shopName: '广州店', platform: 'Lazada', sales: 125000, orders: 610, growth: 8.5, contribution: 22.0 },
    { shopId: 'shop-004', shopName: '深圳店', platform: 'Amazon', sales: 89900.50, orders: 446, growth: 28.1, contribution: 15.8 },
  ],
  byPlatform: [
    { platform: 'TikTok', sales: 198000, orders: 980, growth: 22.5 },
    { platform: 'Shopee', sales: 156000, orders: 820, growth: 15.2 },
    { platform: 'Lazada', sales: 125000, orders: 610, growth: 8.5 },
    { platform: 'Amazon', sales: 89900.50, orders: 446, growth: 28.1 },
  ],
  byCategory: [
    { categoryId: 'cat-001', categoryName: '电子产品', sales: 199115.18, quantity: 3122 },
    { categoryId: 'cat-002', categoryName: '服装配饰', sales: 142225.13, quantity: 2230 },
    { categoryId: 'cat-003', categoryName: '家居用品', sales: 113780.10, quantity: 1784 },
    { categoryId: 'cat-004', categoryName: '美妆护肤', sales: 85335.08, quantity: 1338 },
    { categoryId: 'cat-005', categoryName: '其他', sales: 28445.01, quantity: 446 },
  ],
  trend: Array.from({ length: 30 }, (_, i) => ({
    date: moment().subtract(29 - i, 'days').format('YYYY-MM-DD'),
    sales: Math.floor(Math.random() * 30000) + 15000,
    orders: Math.floor(Math.random() * 150) + 80,
  })),
};

// Mock数据 - 利润报表
const MOCK_PROFIT_REPORT = {
  totalRevenue: 568900.50,
  totalCost: 398230.35,
  totalProfit: 170670.15,
  profitMargin: 30.0,
  roi: 42.9,
  byShop: [
    { shopId: 'shop-001', shopName: '上海旗舰店', revenue: 198000, cost: 138600, profit: 59400, margin: 30.0 },
    { shopId: 'shop-002', shopName: '杭州分店', revenue: 156000, cost: 109200, profit: 46800, margin: 30.0 },
    { shopId: 'shop-003', shopName: '广州店', revenue: 125000, cost: 87500, profit: 37500, margin: 30.0 },
    { shopId: 'shop-004', shopName: '深圳店', revenue: 89900.50, cost: 62930.35, profit: 26970.15, margin: 30.0 },
  ],
  byPlatform: [
    { platform: 'TikTok', revenue: 198000, cost: 138600, profit: 59400, margin: 30.0 },
    { platform: 'Shopee', revenue: 156000, cost: 109200, profit: 46800, margin: 30.0 },
    { platform: 'Lazada', revenue: 125000, cost: 87500, profit: 37500, margin: 30.0 },
    { platform: 'Amazon', revenue: 89900.50, cost: 62930.35, profit: 26970.15, margin: 30.0 },
  ],
  costBreakdown: {
    productCost: 219026.69,
    shippingCost: 59734.55,
    platformFee: 47787.64,
    advertisingCost: 39823.04,
    otherCost: 31858.43,
  },
  trend: Array.from({ length: 30 }, (_, i) => ({
    date: moment().subtract(29 - i, 'days').format('YYYY-MM-DD'),
    revenue: Math.floor(Math.random() * 25000) + 15000,
    cost: Math.floor(Math.random() * 15000) + 10000,
    profit: Math.floor(Math.random() * 10000) + 5000,
  })),
};

// Mock数据 - 库存报表
const MOCK_INVENTORY_REPORT = {
  totalStock: 45680,
  totalValue: 1289500.00,
  lowStockCount: 23,
  overStockCount: 15,
  turnoverRate: 3.8,
  byShop: [
    { shopId: 'shop-001', shopName: '上海旗舰店', stock: 15680, value: 456000, turnoverRate: 4.2, lowStockItems: 8 },
    { shopId: 'shop-002', shopName: '杭州分店', stock: 12500, value: 356000, turnoverRate: 3.5, lowStockItems: 6 },
    { shopId: 'shop-003', shopName: '广州店', stock: 10500, value: 289000, turnoverRate: 3.8, lowStockItems: 5 },
    { shopId: 'shop-004', shopName: '深圳店', stock: 7000, value: 188500, turnoverRate: 4.0, lowStockItems: 4 },
  ],
  topSelling: [
    { productId: 'P001', productName: '智能手表Pro', stock: 580, soldQuantity: 1250, turnoverDays: 12 },
    { productId: 'P002', productName: '无线耳机', stock: 420, soldQuantity: 980, turnoverDays: 15 },
    { productId: 'P003', productName: '手机壳套装', stock: 890, soldQuantity: 890, turnoverDays: 18 },
    { productId: 'P004', productName: '运动鞋', stock: 320, soldQuantity: 780, turnoverDays: 20 },
    { productId: 'P005', productName: 'T恤', stock: 560, soldQuantity: 720, turnoverDays: 22 },
  ],
  lowStockAlerts: [
    { productId: 'P010', productName: '蓝牙音箱', shopName: '上海旗舰店', currentStock: 5, minStock: 20, daysUntilOut: 3 },
    { productId: 'P011', productName: '充电宝', shopName: '杭州分店', currentStock: 8, minStock: 25, daysUntilOut: 5 },
    { productId: 'P012', productName: '数据线', shopName: '广州店', currentStock: 12, minStock: 30, daysUntilOut: 7 },
  ],
};

// Mock数据 - 流量报表
const MOCK_TRAFFIC_REPORT = {
  totalViews: 856000,
  totalVisitors: 599200,
  avgTimeOnSite: 4.2,
  bounceRate: 35.5,
  byShop: [
    { shopId: 'shop-001', shopName: '上海旗舰店', views: 299600, visitors: 209720, avgTime: 4.5, bounceRate: 32.5 },
    { shopId: 'shop-002', shopName: '杭州分店', views: 242000, visitors: 169400, avgTime: 4.0, bounceRate: 36.0 },
    { shopId: 'shop-003', shopName: '广州店', views: 185600, visitors: 129920, avgTime: 4.2, bounceRate: 37.5 },
    { shopId: 'shop-004', shopName: '深圳店', views: 128800, visitors: 90160, avgTime: 4.0, bounceRate: 38.0 },
  ],
  bySource: [
    { source: '自然搜索', views: 299600, visitors: 209720, conversionRate: 3.2 },
    { source: '付费广告', views: 214000, visitors: 149800, conversionRate: 4.5 },
    { source: '社交媒体', views: 171200, visitors: 119840, conversionRate: 2.8 },
    { source: '直接访问', views: 128400, visitors: 89880, conversionRate: 5.1 },
    { source: '其他', views: 42800, visitors: 29960, conversionRate: 1.5 },
  ],
  trend: Array.from({ length: 30 }, (_, i) => ({
    date: moment().subtract(29 - i, 'days').format('YYYY-MM-DD'),
    views: Math.floor(Math.random() * 35000) + 25000,
    visitors: Math.floor(Math.random() * 25000) + 17500,
  })),
};

// Mock数据 - 转化报表
const MOCK_CONVERSION_REPORT = {
  totalConversions: 2856,
  conversionRate: 4.76,
  avgCartValue: 199.33,
  cartAbandonRate: 45.2,
  byShop: [
    { shopId: 'shop-001', shopName: '上海旗舰店', conversions: 980, rate: 4.67, avgValue: 202.04 },
    { shopId: 'shop-002', shopName: '杭州分店', conversions: 820, rate: 4.84, avgValue: 190.24 },
    { shopId: 'shop-003', shopName: '广州店', conversions: 610, rate: 4.70, avgValue: 204.92 },
    { shopId: 'shop-004', shopName: '深圳店', conversions: 446, rate: 4.95, avgValue: 201.57 },
  ],
  byFunnel: [
    { stage: '访问', count: 100000, dropoff: 0 },
    { stage: '浏览商品', count: 60000, dropoff: 40 },
    { stage: '加入购物车', count: 15000, dropoff: 75 },
    { stage: '开始结账', count: 8000, dropoff: 47 },
    { stage: '完成购买', count: 4760, dropoff: 41 },
  ],
  trend: Array.from({ length: 30 }, (_, i) => ({
    date: moment().subtract(29 - i, 'days').format('YYYY-MM-DD'),
    conversions: Math.floor(Math.random() * 150) + 80,
    rate: Math.random() * 2 + 3.5,
  })),
};

const MultiShopReport: React.FC = () => {
  const [loading, setLoading] = useState(false);
  const [activeTab, setActiveTab] = useState('sales');
  const [salesReport, setSalesReport] = useState<any>(null);
  const [profitReport, setProfitReport] = useState<any>(null);
  const [inventoryReport, setInventoryReport] = useState<any>(null);
  const [trafficReport, setTrafficReport] = useState<any>(null);
  const [conversionReport, setConversionReport] = useState<any>(null);
  const [dateRange, setDateRange] = useState<any>([
    moment().subtract(29, 'days'),
    moment(),
  ]);
  const [hierarchySelection, setHierarchySelection] = useState<any>(null);

  // 加载数据
  const fetchData = useCallback(async () => {
    setLoading(true);
    try {
      await new Promise(resolve => setTimeout(resolve, 500));
      setSalesReport(MOCK_SALES_REPORT);
      setProfitReport(MOCK_PROFIT_REPORT);
      setInventoryReport(MOCK_INVENTORY_REPORT);
      setTrafficReport(MOCK_TRAFFIC_REPORT);
      setConversionReport(MOCK_CONVERSION_REPORT);
    } catch (error) {
      message.error('加载数据失败');
    } finally {
      setLoading(false);
    }
  }, [activeTab, dateRange]);

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

  // 导出报表
  const handleExport = (format: string) => {
    message.success(`正在导出${activeTab === 'sales' ? '销售' : activeTab === 'profit' ? '利润' : activeTab === 'inventory' ? '库存' : activeTab === 'traffic' ? '流量' : '转化'}报表 (${format})`);
  };

  // 导出菜单
  const exportMenu = (
    <Menu>
      <Menu.Item key="csv" onClick={() => handleExport('CSV')}>
        导出 CSV
      </Menu.Item>
      <Menu.Item key="excel" onClick={() => handleExport('EXCEL')}>
        导出 Excel
      </Menu.Item>
      <Menu.Item key="pdf" onClick={() => handleExport('PDF')}>
        导出 PDF
      </Menu.Item>
    </Menu>
  );

  // 销售报表内容
  const renderSalesReport = () => {
    if (!salesReport) return null;

    const salesTrendConfig = {
      data: salesReport.trend,
      xField: 'date',
      yField: 'sales',
      smooth: true,
      point: { size: 3 },
    };

    const shopColumnConfig = {
      data: salesReport.byShop,
      xField: 'shopName',
      yField: 'sales',
      label: { position: 'top' },
      color: '#1890ff',
    };

    const categoryPieConfig = {
      data: salesReport.byCategory.map((c: any) => ({ type: c.categoryName, value: c.sales })),
      angleField: 'value',
      colorField: 'type',
      radius: 0.8,
      label: { type: 'outer', content: '{name} {percentage}' },
    };

    return (
      <>
        <Row gutter={16} style={{ marginBottom: 24 }}>
          <Col span={4}>
            <Card>
              <Statistic
                title="总销售额"
                value={salesReport.totalSales}
                precision={2}
                prefix={<DollarOutlined />}
                suffix="元"
              />
            </Card>
          </Col>
          <Col span={4}>
            <Card>
              <Statistic
                title="总订单数"
                value={salesReport.totalOrders}
                prefix={<ShoppingCartOutlined />}
              />
            </Card>
          </Col>
          <Col span={4}>
            <Card>
              <Statistic
                title="客单价"
                value={salesReport.avgOrderValue}
                precision={2}
                prefix="¥"
              />
            </Card>
          </Col>
          <Col span={4}>
            <Card>
              <Statistic
                title="销售增长"
                value={salesReport.salesGrowth}
                precision={1}
                suffix="%"
                valueStyle={{ color: salesReport.salesGrowth >= 0 ? '#3f8600' : '#cf1322' }}
                prefix={salesReport.salesGrowth >= 0 ? <ArrowUpOutlined /> : <ArrowDownOutlined />}
              />
            </Card>
          </Col>
          <Col span={4}>
            <Card>
              <Statistic
                title="订单增长"
                value={salesReport.orderGrowth}
                precision={1}
                suffix="%"
                valueStyle={{ color: salesReport.orderGrowth >= 0 ? '#3f8600' : '#cf1322' }}
                prefix={salesReport.orderGrowth >= 0 ? <ArrowUpOutlined /> : <ArrowDownOutlined />}
              />
            </Card>
          </Col>
          <Col span={4}>
            <Card>
              <Statistic
                title="商品销量"
                value={salesReport.totalProducts}
              />
            </Card>
          </Col>
        </Row>

        <Row gutter={16} style={{ marginBottom: 24 }}>
          <Col span={16}>
            <Card title="销售趋势">
              <Line {...salesTrendConfig} />
            </Card>
          </Col>
          <Col span={8}>
            <Card title="品类分布">
              <Pie {...categoryPieConfig} />
            </Card>
          </Col>
        </Row>

        <Card title="店铺销售排行">
          <Table
            dataSource={salesReport.byShop}
            rowKey="shopId"
            pagination={false}
            columns={[
              { title: '店铺', dataIndex: 'shopName', key: 'shopName', render: (name, record: any) => (
                <Space>
                  <ShopOutlined />
                  <span>{name}</span>
                  <Tag color={PLATFORM_COLORS[record.platform] || 'default'}>{record.platform}</Tag>
                </Space>
              )},
              { title: '销售额', dataIndex: 'sales', key: 'sales', align: 'right', render: (v: number) => `¥${v.toLocaleString()}` },
              { title: '订单数', dataIndex: 'orders', key: 'orders', align: 'center' },
              { title: '贡献率', dataIndex: 'contribution', key: 'contribution', align: 'center', render: (v: number) => (
                <Progress percent={v} size="small" />
              )},
              { title: '增长率', dataIndex: 'growth', key: 'growth', align: 'center', render: (v: number) => (
                <Text style={{ color: v >= 0 ? '#3f8600' : '#cf1322' }}>
                  {v >= 0 ? <RiseOutlined /> : <FallOutlined />} {Math.abs(v)}%
                </Text>
              )},
            ]}
          />
        </Card>
      </>
    );
  };

  // 利润报表内容
  const renderProfitReport = () => {
    if (!profitReport) return null;

    const profitTrendConfig = {
      data: [
        ...profitReport.trend.map((d: any) => ({ ...d, type: '收入', value: d.revenue })),
        ...profitReport.trend.map((d: any) => ({ ...d, type: '成本', value: d.cost })),
        ...profitReport.trend.map((d: any) => ({ ...d, type: '利润', value: d.profit })),
      ],
      xField: 'date',
      yField: 'value',
      seriesField: 'type',
      smooth: true,
    };

    const costBreakdownConfig = {
      data: [
        { type: '商品成本', value: profitReport.costBreakdown.productCost },
        { type: '物流成本', value: profitReport.costBreakdown.shippingCost },
        { type: '平台费用', value: profitReport.costBreakdown.platformFee },
        { type: '广告成本', value: profitReport.costBreakdown.advertisingCost },
        { type: '其他成本', value: profitReport.costBreakdown.otherCost },
      ],
      angleField: 'value',
      colorField: 'type',
      radius: 0.8,
      label: { type: 'outer', content: '{name} {percentage}' },
    };

    return (
      <>
        <Row gutter={16} style={{ marginBottom: 24 }}>
          <Col span={4}>
            <Card>
              <Statistic
                title="总收入"
                value={profitReport.totalRevenue}
                precision={2}
                prefix="¥"
              />
            </Card>
          </Col>
          <Col span={4}>
            <Card>
              <Statistic
                title="总成本"
                value={profitReport.totalCost}
                precision={2}
                prefix="¥"
                valueStyle={{ color: '#cf1322' }}
              />
            </Card>
          </Col>
          <Col span={4}>
            <Card>
              <Statistic
                title="总利润"
                value={profitReport.totalProfit}
                precision={2}
                prefix="¥"
                valueStyle={{ color: '#3f8600' }}
              />
            </Card>
          </Col>
          <Col span={4}>
            <Card>
              <Statistic
                title="利润率"
                value={profitReport.profitMargin}
                precision={1}
                suffix="%"
              />
            </Card>
          </Col>
          <Col span={4}>
            <Card>
              <Statistic
                title="ROI"
                value={profitReport.roi}
                precision={1}
                suffix="%"
                valueStyle={{ color: '#3f8600' }}
              />
            </Card>
          </Col>
          <Col span={4}>
            <Card>
              <Statistic
                title="利润增长"
                value={18.5}
                precision={1}
                suffix="%"
                valueStyle={{ color: '#3f8600' }}
                prefix={<RiseOutlined />}
              />
            </Card>
          </Col>
        </Row>

        <Row gutter={16} style={{ marginBottom: 24 }}>
          <Col span={16}>
            <Card title="利润趋势">
              <Area {...profitTrendConfig} />
            </Card>
          </Col>
          <Col span={8}>
            <Card title="成本构成">
              <Pie {...costBreakdownConfig} />
            </Card>
          </Col>
        </Row>

        <Card title="店铺利润排行">
          <Table
            dataSource={profitReport.byShop}
            rowKey="shopId"
            pagination={false}
            columns={[
              { title: '店铺', dataIndex: 'shopName', key: 'shopName' },
              { title: '收入', dataIndex: 'revenue', key: 'revenue', align: 'right', render: (v: number) => `¥${v.toLocaleString()}` },
              { title: '成本', dataIndex: 'cost', key: 'cost', align: 'right', render: (v: number) => `¥${v.toLocaleString()}` },
              { title: '利润', dataIndex: 'profit', key: 'profit', align: 'right', render: (v: number) => (
                <Text strong style={{ color: '#3f8600' }}>¥{v.toLocaleString()}</Text>
              )},
              { title: '利润率', dataIndex: 'margin', key: 'margin', align: 'center', render: (v: number) => (
                <Tag color={v >= 30 ? 'success' : v >= 20 ? 'warning' : 'error'}>{v.toFixed(1)}%</Tag>
              )},
            ]}
          />
        </Card>
      </>
    );
  };

  // 库存报表内容
  const renderInventoryReport = () => {
    if (!inventoryReport) return null;

    return (
      <>
        <Row gutter={16} style={{ marginBottom: 24 }}>
          <Col span={4}>
            <Card>
              <Statistic
                title="总库存"
                value={inventoryReport.totalStock}
                prefix={<StockOutlined />}
              />
            </Card>
          </Col>
          <Col span={4}>
            <Card>
              <Statistic
                title="库存价值"
                value={inventoryReport.totalValue}
                precision={2}
                prefix="¥"
              />
            </Card>
          </Col>
          <Col span={4}>
            <Card>
              <Statistic
                title="周转率"
                value={inventoryReport.turnoverRate}
                precision={1}
                suffix="次/月"
              />
            </Card>
          </Col>
          <Col span={4}>
            <Card>
              <Statistic
                title="低库存预警"
                value={inventoryReport.lowStockCount}
                valueStyle={{ color: '#faad14' }}
                prefix={<AlertOutlined />}
              />
            </Card>
          </Col>
          <Col span={4}>
            <Card>
              <Statistic
                title="高库存商品"
                value={inventoryReport.overStockCount}
              />
            </Card>
          </Col>
          <Col span={4}>
            <Card>
              <Statistic
                title="平均周转天数"
                value={12}
                suffix="天"
              />
            </Card>
          </Col>
        </Row>

        <Row gutter={16} style={{ marginBottom: 24 }}>
          <Col span={12}>
            <Card title="店铺库存分布">
              <Table
                dataSource={inventoryReport.byShop}
                rowKey="shopId"
                pagination={false}
                size="small"
                columns={[
                  { title: '店铺', dataIndex: 'shopName', key: 'shopName' },
                  { title: '库存', dataIndex: 'stock', key: 'stock', align: 'right' },
                  { title: '价值', dataIndex: 'value', key: 'value', align: 'right', render: (v: number) => `¥${v.toLocaleString()}` },
                  { title: '周转率', dataIndex: 'turnoverRate', key: 'turnoverRate', align: 'center', render: (v: number) => `${v.toFixed(1)}次` },
                  { title: '低库存', dataIndex: 'lowStockItems', key: 'lowStockItems', align: 'center', render: (v: number) => (
                    <Badge count={v} showZero color={v > 0 ? '#faad14' : '#52c41a'} />
                  )},
                ]}
              />
            </Card>
          </Col>
          <Col span={12}>
            <Card title="低库存预警" extra={<Tag color="warning">{inventoryReport.lowStockAlerts.length} 项</Tag>}>
              <List
                dataSource={inventoryReport.lowStockAlerts}
                renderItem={(item: any) => (
                  <List.Item>
                    <List.Item.Meta
                      avatar={<Avatar style={{ backgroundColor: '#faad14' }}><AlertOutlined /></Avatar>}
                      title={item.productName}
                      description={`${item.shopName} | 当前: ${item.currentStock} | 最低: ${item.minStock}`}
                    />
                    <Tag color="error">{item.daysUntilOut}天后缺货</Tag>
                  </List.Item>
                )}
              />
            </Card>
          </Col>
        </Row>

        <Card title="热销商品TOP5">
          <Table
            dataSource={inventoryReport.topSelling}
            rowKey="productId"
            pagination={false}
            columns={[
              { title: '商品', dataIndex: 'productName', key: 'productName' },
              { title: '当前库存', dataIndex: 'stock', key: 'stock', align: 'center' },
              { title: '已售数量', dataIndex: 'soldQuantity', key: 'soldQuantity', align: 'center' },
              { title: '周转天数', dataIndex: 'turnoverDays', key: 'turnoverDays', align: 'center', render: (v: number) => `${v}天` },
              { title: '状态', key: 'status', render: () => <Tag color="success">热销</Tag> },
            ]}
          />
        </Card>
      </>
    );
  };

  // 流量报表内容
  const renderTrafficReport = () => {
    if (!trafficReport) return null;

    const trafficTrendConfig = {
      data: [
        ...trafficReport.trend.map((d: any) => ({ ...d, type: '浏览量', value: d.views })),
        ...trafficReport.trend.map((d: any) => ({ ...d, type: '访客数', value: d.visitors })),
      ],
      xField: 'date',
      yField: 'value',
      seriesField: 'type',
      smooth: true,
    };

    const sourceColumnConfig = {
      data: trafficReport.bySource,
      xField: 'source',
      yField: 'views',
      label: { position: 'top' },
      color: '#1890ff',
    };

    return (
      <>
        <Row gutter={16} style={{ marginBottom: 24 }}>
          <Col span={4}>
            <Card>
              <Statistic
                title="总浏览量"
                value={trafficReport.totalViews}
                prefix={<EyeOutlined />}
              />
            </Card>
          </Col>
          <Col span={4}>
            <Card>
              <Statistic
                title="总访客数"
                value={trafficReport.totalVisitors}
              />
            </Card>
          </Col>
          <Col span={4}>
            <Card>
              <Statistic
                title="平均停留时间"
                value={trafficReport.avgTimeOnSite}
                precision={1}
                suffix="分钟"
              />
            </Card>
          </Col>
          <Col span={4}>
            <Card>
              <Statistic
                title="跳出率"
                value={trafficReport.bounceRate}
                precision={1}
                suffix="%"
              />
            </Card>
          </Col>
          <Col span={4}>
            <Card>
              <Statistic
                title="人均浏览"
                value={trafficReport.totalViews / trafficReport.totalVisitors}
                precision={1}
                suffix="页"
              />
            </Card>
          </Col>
          <Col span={4}>
            <Card>
              <Statistic
                title="流量增长"
                value={15.8}
                precision={1}
                suffix="%"
                valueStyle={{ color: '#3f8600' }}
                prefix={<RiseOutlined />}
              />
            </Card>
          </Col>
        </Row>

        <Row gutter={16} style={{ marginBottom: 24 }}>
          <Col span={16}>
            <Card title="流量趋势">
              <Line {...trafficTrendConfig} />
            </Card>
          </Col>
          <Col span={8}>
            <Card title="流量来源">
              <Column {...sourceColumnConfig} />
            </Card>
          </Col>
        </Row>

        <Card title="店铺流量分布">
          <Table
            dataSource={trafficReport.byShop}
            rowKey="shopId"
            pagination={false}
            columns={[
              { title: '店铺', dataIndex: 'shopName', key: 'shopName' },
              { title: '浏览量', dataIndex: 'views', key: 'views', align: 'right' },
              { title: '访客数', dataIndex: 'visitors', key: 'visitors', align: 'right' },
              { title: '平均停留', dataIndex: 'avgTime', key: 'avgTime', align: 'center', render: (v: number) => `${v.toFixed(1)}分钟` },
              { title: '跳出率', dataIndex: 'bounceRate', key: 'bounceRate', align: 'center', render: (v: number) => (
                <Progress percent={v} size="small" status={v > 40 ? 'exception' : 'normal'} />
              )},
            ]}
          />
        </Card>
      </>
    );
  };

  // 转化报表内容
  const renderConversionReport = () => {
    if (!conversionReport) return null;

    const funnelConfig = {
      data: conversionReport.byFunnel.map((d: any) => ({ ...d, value: d.count })),
      xField: 'count',
      yField: 'stage',
      legend: false,
    };

    const conversionTrendConfig = {
      data: conversionReport.trend,
      xField: 'date',
      yField: 'conversions',
      smooth: true,
    };

    return (
      <>
        <Row gutter={16} style={{ marginBottom: 24 }}>
          <Col span={4}>
            <Card>
              <Statistic
                title="总转化数"
                value={conversionReport.totalConversions}
                prefix={<PercentageOutlined />}
              />
            </Card>
          </Col>
          <Col span={4}>
            <Card>
              <Statistic
                title="转化率"
                value={conversionReport.conversionRate}
                precision={2}
                suffix="%"
              />
            </Card>
          </Col>
          <Col span={4}>
            <Card>
              <Statistic
                title="平均客单价"
                value={conversionReport.avgCartValue}
                precision={2}
                prefix="¥"
              />
            </Card>
          </Col>
          <Col span={4}>
            <Card>
              <Statistic
                title="购物车放弃率"
                value={conversionReport.cartAbandonRate}
                precision={1}
                suffix="%"
                valueStyle={{ color: '#cf1322' }}
              />
            </Card>
          </Col>
          <Col span={4}>
            <Card>
              <Statistic
                title="转化增长"
                value={12.5}
                precision={1}
                suffix="%"
                valueStyle={{ color: '#3f8600' }}
                prefix={<RiseOutlined />}
              />
            </Card>
          </Col>
          <Col span={4}>
            <Card>
              <Statistic
                title="转化价值"
                value={conversionReport.totalConversions * conversionReport.avgCartValue}
                precision={2}
                prefix="¥"
              />
            </Card>
          </Col>
        </Row>

        <Row gutter={16} style={{ marginBottom: 24 }}>
          <Col span={12}>
            <Card title="转化漏斗">
              <Funnel {...funnelConfig} />
            </Card>
          </Col>
          <Col span={12}>
            <Card title="转化趋势">
              <Line {...conversionTrendConfig} />
            </Card>
          </Col>
        </Row>

        <Card title="店铺转化分析">
          <Table
            dataSource={conversionReport.byShop}
            rowKey="shopId"
            pagination={false}
            columns={[
              { title: '店铺', dataIndex: 'shopName', key: 'shopName' },
              { title: '转化数', dataIndex: 'conversions', key: 'conversions', align: 'center' },
              { title: '转化率', dataIndex: 'rate', key: 'rate', align: 'center', render: (v: number) => (
                <Tag color={v >= 5 ? 'success' : v >= 3 ? 'warning' : 'error'}>{v.toFixed(2)}%</Tag>
              )},
              { title: '平均客单价', dataIndex: 'avgValue', key: 'avgValue', align: 'right', render: (v: number) => `¥${v.toFixed(2)}` },
              { title: '转化价值', key: 'totalValue', align: 'right', render: (_: any, record: any) => `¥${(record.conversions * record.avgValue).toFixed(2)}` },
            ]}
          />
        </Card>
      </>
    );
  };

  return (
    <div style={{ padding: 24 }}>
      <Row justify="space-between" align="middle" style={{ marginBottom: 16 }}>
        <Col>
          <Title level={2}>多店铺报表聚合</Title>
          <Text type="secondary">统一查看多店铺销售、利润、库存、流量、转化报表</Text>
        </Col>
        <Col>
          <Space>
            <Dropdown overlay={exportMenu}>
              <Button icon={<DownloadOutlined />}>导出报表</Button>
            </Dropdown>
          </Space>
        </Col>
      </Row>

      {/* 筛选区域 */}
      <Card style={{ marginBottom: 24 }}>
        <Row gutter={16} align="middle">
          <Col span={8}>
            <Space>
              <Text strong>选择范围：</Text>
              <HierarchySelector
                mode="cascader"
                maxLevel="SHOP"
                onChange={setHierarchySelection}
                placeholder="选择部门/店铺"
                style={{ width: 280 }}
              />
            </Space>
          </Col>
          <Col span={8}>
            <Space>
              <Text strong>时间范围：</Text>
              <RangePicker
                value={dateRange}
                onChange={setDateRange}
                allowClear={false}
              />
            </Space>
          </Col>
          <Col span={8} style={{ textAlign: 'right' }}>
            <Button type="primary" onClick={fetchData} loading={loading}>
              查询
            </Button>
          </Col>
        </Row>
      </Card>

      {/* 报表内容 */}
      <Spin spinning={loading}>
        <Tabs activeKey={activeTab} onChange={setActiveTab} size="large">
          <TabPane
            tab={<span><DollarOutlined /> 销售报表</span>}
            key="sales"
          >
            {renderSalesReport()}
          </TabPane>
          <TabPane
            tab={<span><RiseOutlined /> 利润报表</span>}
            key="profit"
          >
            {renderProfitReport()}
          </TabPane>
          <TabPane
            tab={<span><StockOutlined /> 库存报表</span>}
            key="inventory"
          >
            {renderInventoryReport()}
          </TabPane>
          <TabPane
            tab={<span><EyeOutlined /> 流量报表</span>}
            key="traffic"
          >
            {renderTrafficReport()}
          </TabPane>
          <TabPane
            tab={<span><PercentageOutlined /> 转化报表</span>}
            key="conversion"
          >
            {renderConversionReport()}
          </TabPane>
        </Tabs>
      </Spin>
    </div>
  );
};

export default MultiShopReport;
