import React, { useState, useEffect } from 'react';
import {
  Card,
  Row,
  Col,
  Button,
  Tabs,
  Table,
  DatePicker,
  Select,
  Space,
  Statistic,
  Progress,
  message,
  Modal,
  Form,
  Input,
  Radio,
  Tooltip,
  Badge,
  Dropdown,
  Menu,
  Alert,
  Descriptions,
  Tag,
  Timeline,
  List,
  Avatar,
  Divider,
  Empty,
  Spin,
  Switch,
  Slider,
  Checkbox,
  Collapse,
  Steps,
  Drawer,
  Popover,
} from 'antd';
import {
  BarChartOutlined,
  LineChartOutlined,
  PieChartOutlined,
  DollarOutlined,
  TrendingUpOutlined,
  TrendingDownOutlined,
  DownloadOutlined,
  SearchOutlined,
  FilterOutlined,
  ReloadOutlined,
  FileTextOutlined,
  SettingOutlined,
  ShareAltOutlined,
  CalendarOutlined,
  ShopOutlined,
  ProductOutlined,
  OrderedListOutlined,
  RiseOutlined,
  FallOutlined,
  EyeOutlined,
  EditOutlined,
  DeleteOutlined,
  PlusOutlined,
  AreaChartOutlined,
  FundOutlined,
  DashboardOutlined,
  GlobalOutlined,
  TeamOutlined,
  ShoppingCartOutlined,
  InboxOutlined,
  CheckCircleOutlined,
  WarningOutlined,
  InfoCircleOutlined,
  ArrowUpOutlined,
  ArrowDownOutlined,
  MoreOutlined,
  ExportOutlined,
  PrinterOutlined,
  MailOutlined,
  BellOutlined,
  ClockCircleOutlined,
} from '@ant-design/icons';
import type { ColumnsType } from 'antd/es/table';
import { analyticsDataSource, MetricData, ChartData, ProductAnalytics, OrderAnalytics, ProfitAnalytics, RealtimeMetrics, AlertRule, Dashboard } from '@/services/analyticsDataSource';

const { TabPane } = Tabs;
const { RangePicker } = DatePicker;
const { Option } = Select;
const { Panel } = Collapse;
const { Step } = Steps;

// 图表数据类型 (本地使用)
interface LocalChartData {
  date: string;
  sales: number;
  orders: number;
  visitors: number;
  conversion: number;
}

// 组件内部使用的MetricData，icon转为ReactNode
interface LocalMetricData {
  key: string;
  label: string;
  value: number;
  unit: string;
  change: number;
  changeType: 'up' | 'down' | 'neutral';
  icon: React.ReactNode;
  color: string;
}

// Widget类型
interface Widget {
  id: string;
  type: 'metric' | 'chart' | 'table' | 'alert';
  title: string;
  config: any;
  position: { x: number; y: number; w: number; h: number };
}

// 状态映射
const PLATFORM_MAP: Record<string, { color: string; text: string }> = {
  AMAZON: { color: 'orange', text: 'Amazon' },
  EBAY: { color: 'blue', text: 'eBay' },
  SHOPIFY: { color: 'green', text: 'Shopify' },
  SHOPEE: { color: 'red', text: 'Shopee' },
  LAZADA: { color: 'purple', text: 'Lazada' },
};

const ORDER_STATUS_MAP: Record<string, { color: string; text: string }> = {
  PENDING: { color: 'default', text: '待处理' },
  CONFIRMED: { color: 'blue', text: '已确认' },
  SHIPPED: { color: 'processing', text: '已发货' },
  DELIVERED: { color: 'cyan', text: '已送达' },
  COMPLETED: { color: 'success', text: '已完成' },
  CANCELLED: { color: 'error', text: '已取消' },
};

const TREND_MAP: Record<string, { color: string; icon: React.ReactNode }> = {
  up: { color: '#52c41a', icon: <RiseOutlined /> },
  down: { color: '#ff4d4f', icon: <FallOutlined /> },
  stable: { color: '#faad14', icon: <LineChartOutlined /> },
};

export const Analytics: React.FC = () => {
  const [loading, setLoading] = useState(false);
  const [activeTab, setActiveTab] = useState('overview');
  const [dateRange, setDateRange] = useState<[string, string] | null>(null);
  const [selectedShop, setSelectedShop] = useState<string>('');
  const [selectedPlatform, setSelectedPlatform] = useState<string>('');
  
  // 模拟用户角色和权限（实际项目中应该从登录状态或API获取）
  const userRole = 'OPERATOR'; // 可替换为 ADMIN, MANAGER, OPERATOR 等
  
  // 定义各角色可访问的Tab页
  const roleTabPermissions: Record<string, string[]> = {
    ADMIN: ['overview', 'products', 'orders', 'profit', 'alerts'],
    MANAGER: ['overview', 'products', 'orders', 'profit'],
    OPERATOR: ['overview', 'products', 'orders'],
  };
  
  // 获取当前用户可访问的Tab页
  const accessibleTabs = roleTabPermissions[userRole] || ['overview'];
  
  // 数据状态
  const [metrics, setMetrics] = useState<LocalMetricData[]>([]);
  const [chartData, setChartData] = useState<LocalChartData[]>([]);
  const [productAnalytics, setProductAnalytics] = useState<ProductAnalytics[]>([]);
  const [orderAnalytics, setOrderAnalytics] = useState<OrderAnalytics[]>([]);
  const [profitAnalytics, setProfitAnalytics] = useState<ProfitAnalytics[]>([]);
  const [realtimeMetrics, setRealtimeMetrics] = useState<RealtimeMetrics[]>([]);
  const [alertRules, setAlertRules] = useState<AlertRule[]>([]);
  const [dashboards, setDashboards] = useState<Dashboard[]>([]);
  
  // 模态框状态
  const [alertModalVisible, setAlertModalVisible] = useState(false);
  const [dashboardModalVisible, setDashboardModalVisible] = useState(false);
  const [exportModalVisible, setExportModalVisible] = useState(false);
  const [detailDrawerVisible, setDetailDrawerVisible] = useState(false);
  const [selectedItem, setSelectedItem] = useState<any>(null);
  
  const [alertForm] = Form.useForm();
  const [dashboardForm] = Form.useForm();

  // 初始化数据
  useEffect(() => {
    fetchAllData();
    // 实时数据刷新
    const interval = setInterval(fetchRealtimeData, 30000);
    return () => clearInterval(interval);
  }, []);

  // Icon映射表
  const iconMap: Record<string, React.ReactNode> = {
    DollarOutlined: <DollarOutlined />,
    ShoppingCartOutlined: <ShoppingCartOutlined />,
    TeamOutlined: <TeamOutlined />,
    FundOutlined: <FundOutlined />,
    BarChartOutlined: <BarChartOutlined />,
    LineChartOutlined: <LineChartOutlined />,
  };

  const fetchAllData = async () => {
    setLoading(true);
    try {
      const data = await analyticsDataSource.fetchAllData();
      
      // 转换metrics的icon
      const localMetrics: LocalMetricData[] = data.metrics.map(m => ({
        ...m,
        icon: iconMap[m.icon] || <BarChartOutlined />,
      }));
      
      setMetrics(localMetrics);
      setChartData(data.chartData);
      setProductAnalytics(data.productAnalytics);
      setOrderAnalytics(data.orderAnalytics);
      setProfitAnalytics(data.profitAnalytics);
      setRealtimeMetrics(data.realtimeMetrics);
      setAlertRules(data.alertRules);
      setDashboards(data.dashboards);
    } catch (error) {
      message.error('加载数据失败');
    } finally {
      setLoading(false);
    }
  };

  const fetchMetrics = async () => {
    try {
      const data = await analyticsDataSource.fetchMetrics();
      const localMetrics: LocalMetricData[] = data.map(m => ({
        ...m,
        icon: iconMap[m.icon] || <BarChartOutlined />,
      }));
      setMetrics(localMetrics);
    } catch (error) {
      message.error('加载指标数据失败');
    }
  };

  const fetchChartData = async () => {
    try {
      const data = await analyticsDataSource.fetchChartData();
      setChartData(data);
    } catch (error) {
      message.error('加载图表数据失败');
    }
  };

  const fetchProductAnalytics = async () => {
    try {
      const data = await analyticsDataSource.fetchProductAnalytics();
      setProductAnalytics(data);
    } catch (error) {
      message.error('加载商品分析失败');
    }
  };

  const fetchOrderAnalytics = async () => {
    try {
      const data = await analyticsDataSource.fetchOrderAnalytics();
      setOrderAnalytics(data);
    } catch (error) {
      message.error('加载订单分析失败');
    }
  };

  const fetchProfitAnalytics = async () => {
    try {
      const data = await analyticsDataSource.fetchProfitAnalytics();
      setProfitAnalytics(data);
    } catch (error) {
      message.error('加载利润分析失败');
    }
  };

  const fetchRealtimeData = async () => {
    try {
      const data = await analyticsDataSource.fetchRealtimeData();
      setRealtimeMetrics(data);
    } catch (error) {
      console.error('加载实时数据失败', error);
    }
  };

  const fetchAlertRules = async () => {
    try {
      const data = await analyticsDataSource.fetchAlertRules();
      setAlertRules(data);
    } catch (error) {
      message.error('加载告警规则失败');
    }
  };

  const fetchDashboards = async () => {
    try {
      const data = await analyticsDataSource.fetchDashboards();
      setDashboards(data);
    } catch (error) {
      message.error('加载看板数据失败');
    }
  };

  // 处理函数
  const handleRefresh = () => {
    fetchAllData();
    message.success('数据已刷新');
  };

  const handleExport = () => {
    setExportModalVisible(true);
  };

  const handleCreateAlert = () => {
    alertForm.resetFields();
    setAlertModalVisible(true);
  };

  const handleSaveAlert = async () => {
    try {
      const values = await alertForm.validateFields();
      console.log('Creating alert rule:', values);
      message.success('告警规则已创建');
      setAlertModalVisible(false);
      fetchAlertRules();
    } catch (error) {
      message.error('创建失败');
    }
  };

  const handleToggleAlert = (id: string, enabled: boolean) => {
    setAlertRules(prev => prev.map(rule => 
      rule.id === id ? { ...rule, enabled } : rule
    ));
    message.success(`告警规则已${enabled ? '启用' : '禁用'}`);
  };

  const handleDeleteAlert = (id: string) => {
    setAlertRules(prev => prev.filter(rule => rule.id !== id));
    message.success('告警规则已删除');
  };

  const handleViewDetail = (item: any, type: string) => {
    setSelectedItem({ ...item, type });
    setDetailDrawerVisible(true);
  };

  // 表格列定义
  const productColumns: ColumnsType<ProductAnalytics> = [
    {
      title: '商品信息',
      dataIndex: 'name',
      key: 'name',
      render: (text, record) => (
        <Space>
          <Avatar src={record.image} shape="square" size={48} />
          <div>
            <div style={{ fontWeight: 500 }}>{text}</div>
            <div style={{ fontSize: 12, color: '#999' }}>{record.productId}</div>
            <Tag size="small">{record.category}</Tag>
          </div>
        </Space>
      ),
    },
    { title: '销量', dataIndex: 'sales', key: 'sales', sorter: (a, b) => a.sales - b.sales },
    { title: '销售额', dataIndex: 'revenue', key: 'revenue', render: (v) => `¥${v.toLocaleString()}`, sorter: (a, b) => a.revenue - b.revenue },
    { title: '利润', dataIndex: 'profit', key: 'profit', render: (v) => `¥${v.toLocaleString()}`, sorter: (a, b) => a.profit - b.profit },
    { title: '利润率', dataIndex: 'profitMargin', key: 'profitMargin', render: (v) => `${v}%`, sorter: (a, b) => a.profitMargin - b.profitMargin },
    { title: '浏览量', dataIndex: 'views', key: 'views', sorter: (a, b) => a.views - b.views },
    { title: '转化率', dataIndex: 'conversionRate', key: 'conversionRate', render: (v) => `${v}%`, sorter: (a, b) => a.conversionRate - b.conversionRate },
    { title: '退货率', dataIndex: 'returnRate', key: 'returnRate', render: (v) => <Tag color={v > 5 ? 'error' : 'success'}>{v}%</Tag>, sorter: (a, b) => a.returnRate - b.returnRate },
    {
      title: '趋势',
      dataIndex: 'trend',
      key: 'trend',
      render: (trend) => (
        <Tag icon={TREND_MAP[trend].icon} color={TREND_MAP[trend].color}>
          {trend === 'up' ? '上升' : trend === 'down' ? '下降' : '平稳'}
        </Tag>
      ),
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Button type="link" icon={<EyeOutlined />} onClick={() => handleViewDetail(record, 'product')}>
          详情
        </Button>
      ),
    },
  ];

  const orderColumns: ColumnsType<OrderAnalytics> = [
    { title: '订单号', dataIndex: 'orderId', key: 'orderId' },
    { title: '平台', dataIndex: 'platform', key: 'platform', render: (p) => <Tag color={PLATFORM_MAP[p]?.color}>{PLATFORM_MAP[p]?.text}</Tag> },
    { title: '状态', dataIndex: 'status', key: 'status', render: (s) => <Tag color={ORDER_STATUS_MAP[s]?.color}>{ORDER_STATUS_MAP[s]?.text}</Tag> },
    { title: '金额', dataIndex: 'amount', key: 'amount', render: (v) => `¥${v.toFixed(2)}` },
    { title: '利润', dataIndex: 'profit', key: 'profit', render: (v) => `¥${v.toFixed(2)}` },
    { title: '客户类型', dataIndex: 'customerType', key: 'customerType', render: (t) => <Tag color={t === 'new' ? 'blue' : 'green'}>{t === 'new' ? '新客户' : '回头客'}</Tag> },
    { title: '物流成本', dataIndex: 'shippingCost', key: 'shippingCost', render: (v) => `¥${v.toFixed(2)}` },
    { title: '平台费用', dataIndex: 'platformFee', key: 'platformFee', render: (v) => `¥${v.toFixed(2)}` },
    { title: '创建时间', dataIndex: 'createdAt', key: 'createdAt' },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Button type="link" icon={<EyeOutlined />} onClick={() => handleViewDetail(record, 'order')}>
          详情
        </Button>
      ),
    },
  ];

  const profitColumns: ColumnsType<ProfitAnalytics> = [
    { title: '日期', dataIndex: 'period', key: 'period' },
    { title: '收入', dataIndex: 'revenue', key: 'revenue', render: (v) => `¥${v.toLocaleString()}` },
    { title: '成本', dataIndex: 'cost', key: 'cost', render: (v) => `¥${v.toLocaleString()}` },
    { title: '毛利润', dataIndex: 'grossProfit', key: 'grossProfit', render: (v) => `¥${v.toLocaleString()}` },
    { title: '净利润', dataIndex: 'netProfit', key: 'netProfit', render: (v) => <span style={{ color: '#52c41a', fontWeight: 500 }}>¥{v.toLocaleString()}</span> },
    { title: '利润率', dataIndex: 'margin', key: 'margin', render: (v) => `${v}%` },
    { title: '平台费', dataIndex: 'platformFees', key: 'platformFees', render: (v) => `¥${v.toLocaleString()}` },
    { title: '物流费', dataIndex: 'shippingCost', key: 'shippingCost', render: (v) => `¥${v.toLocaleString()}` },
    { title: '广告费', dataIndex: 'adSpend', key: 'adSpend', render: (v) => `¥${v.toLocaleString()}` },
  ];

  const alertColumns: ColumnsType<AlertRule> = [
    { title: '规则名称', dataIndex: 'name', key: 'name' },
    { title: '指标', dataIndex: 'metric', key: 'metric' },
    { title: '条件', dataIndex: 'condition', key: 'condition', render: (c) => `${c}` },
    { title: '阈值', dataIndex: 'threshold', key: 'threshold' },
    { title: '通知渠道', dataIndex: 'notifyChannels', key: 'notifyChannels', render: (channels) => channels.map((c: string) => <Tag key={c}>{c}</Tag>) },
    { title: '最后触发', dataIndex: 'lastTriggered', key: 'lastTriggered', render: (v) => v || '-' },
    {
      title: '状态',
      dataIndex: 'enabled',
      key: 'enabled',
      render: (enabled, record) => (
        <Switch checked={enabled} onChange={(checked) => handleToggleAlert(record.id, checked)} />
      ),
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Space>
          <Button type="link" icon={<EditOutlined />}>编辑</Button>
          <Button type="link" danger icon={<DeleteOutlined />} onClick={() => handleDeleteAlert(record.id)}>删除</Button>
        </Space>
      ),
    },
  ];

  return (
    <div className="analytics-page">
      <Card
        title={<Space><BarChartOutlined /> 数据中心</Space>}
        extra={
          <Space>
            <Select
              placeholder="选择店铺"
              value={selectedShop}
              onChange={setSelectedShop}
              allowClear
              style={{ width: 150 }}
            >
              <Option value="shop1">Amazon US Store</Option>
              <Option value="shop2">eBay Outlet</Option>
              <Option value="shop3">Shopify Brand</Option>
            </Select>
            <Select
              placeholder="选择平台"
              value={selectedPlatform}
              onChange={setSelectedPlatform}
              allowClear
              style={{ width: 120 }}
            >
              {Object.keys(PLATFORM_MAP).map(key => (
                <Option key={key} value={key}>{PLATFORM_MAP[key].text}</Option>
              ))}
            </Select>
            <RangePicker onChange={(dates) => setDateRange(dates as any)} />
            <Button icon={<ReloadOutlined />} onClick={handleRefresh}>刷新</Button>
            <Button type="primary" icon={<DownloadOutlined />} onClick={handleExport}>导出</Button>
          </Space>
        }
      >
        <Tabs activeKey={activeTab} onChange={setActiveTab}>
          {accessibleTabs.includes('overview') && (
            <TabPane tab={<span><DashboardOutlined />数据概览</span>} key="overview">
              <Spin spinning={loading}>
                {/* 核心指标卡片 */}
                <Row gutter={[16, 16]} style={{ marginBottom: 24 }}>
                  {metrics.map(metric => (
                    <Col span={4} key={metric.key}>
                      <Card hoverable>
                        <Statistic
                          title={metric.label}
                          value={metric.value}
                          prefix={metric.icon}
                          suffix={metric.unit}
                          valueStyle={{ color: metric.color }}
                        />
                        <div style={{ marginTop: 8 }}>
                          {metric.changeType === 'up' ? (
                            <span style={{ color: '#52c41a' }}><ArrowUpOutlined /> {metric.change}%</span>
                          ) : metric.changeType === 'down' ? (
                            <span style={{ color: '#ff4d4f' }}><ArrowDownOutlined /> {Math.abs(metric.change)}%</span>
                          ) : (
                            <span style={{ color: '#faad14' }}>-</span>
                          )}
                          <span style={{ color: '#999', marginLeft: 8 }}>环比</span>
                        </div>
                      </Card>
                    </Col>
                  ))}
                </Row>

                {/* 实时数据 */}
                <Card title="实时监控" style={{ marginBottom: 24 }}>
                  <Row gutter={16}>
                    <Col span={6}>
                      <Statistic
                        title="当前在线用户"
                        value={realtimeMetrics[0]?.activeUsers || 0}
                        prefix={<TeamOutlined />}
                        valueStyle={{ color: '#1890ff' }}
                      />
                    </Col>
                    <Col span={6}>
                      <Statistic
                        title="每分钟订单"
                        value={realtimeMetrics[0]?.ordersPerMinute || 0}
                        prefix={<ShoppingCartOutlined />}
                        valueStyle={{ color: '#52c41a' }}
                      />
                    </Col>
                    <Col span={6}>
                      <Statistic
                        title="每分钟收入"
                        value={realtimeMetrics[0]?.revenuePerMinute || 0}
                        prefix={<DollarOutlined />}
                        suffix="¥"
                        valueStyle={{ color: '#fa8c16' }}
                      />
                    </Col>
                    <Col span={6}>
                      <Statistic
                        title="实时转化率"
                        value={realtimeMetrics[0]?.conversionRate || 0}
                        prefix={<FundOutlined />}
                        suffix="%"
                        valueStyle={{ color: '#722ed1' }}
                      />
                    </Col>
                  </Row>
                </Card>

                {/* 趋势图表占位 */}
                <Row gutter={16}>
                  <Col span={12}>
                    <Card title="销售趋势" extra={<BarChartOutlined />}>
                      <div style={{ height: 300, display: 'flex', alignItems: 'center', justifyContent: 'center', background: '#f5f5f5', borderRadius: 4 }}>
                        <Empty description="图表组件待集成" />
                      </div>
                    </Card>
                  </Col>
                  <Col span={12}>
                    <Card title="订单趋势" extra={<LineChartOutlined />}>
                      <div style={{ height: 300, display: 'flex', alignItems: 'center', justifyContent: 'center', background: '#f5f5f5', borderRadius: 4 }}>
                        <Empty description="图表组件待集成" />
                      </div>
                    </Card>
                  </Col>
                </Row>
              </Spin>
            </TabPane>
          )}

          {accessibleTabs.includes('products') && (
            <TabPane tab={<span><ProductOutlined />商品分析</span>} key="products">
              <Table
                columns={productColumns}
                dataSource={productAnalytics}
                rowKey="id"
                pagination={{ pageSize: 10 }}
                scroll={{ x: 1200 }}
              />
            </TabPane>
          )}

          {accessibleTabs.includes('orders') && (
            <TabPane tab={<span><OrderedListOutlined />订单分析</span>} key="orders">
              <Table
                columns={orderColumns}
                dataSource={orderAnalytics}
                rowKey="id"
                pagination={{ pageSize: 10 }}
              />
            </TabPane>
          )}

          {accessibleTabs.includes('profit') && (
            <TabPane tab={<span><DollarOutlined />利润分析</span>} key="profit">
              <Table
                columns={profitColumns}
                dataSource={profitAnalytics}
                rowKey="id"
                pagination={{ pageSize: 10 }}
              />
            </TabPane>
          )}

          {accessibleTabs.includes('alerts') && (
            <TabPane tab={<span><BellOutlined />告警规则</span>} key="alerts">
              <Card
                extra={
                  <Button type="primary" icon={<PlusOutlined />} onClick={handleCreateAlert}>
                    新建告警
                  </Button>
                }
              >
                <Table
                  columns={alertColumns}
                  dataSource={alertRules}
                  rowKey="id"
                  pagination={{ pageSize: 10 }}
                />
              </Card>
            </TabPane>
          )}
        </Tabs>
      </Card>

      {/* 告警规则模态框 */}
      <Modal
        title="新建告警规则"
        open={alertModalVisible}
        onOk={handleSaveAlert}
        onCancel={() => setAlertModalVisible(false)}
        width={600}
      >
        <Form form={alertForm} layout="vertical">
          <Form.Item name="name" label="规则名称" rules={[{ required: true }]}>
            <Input placeholder="输入规则名称" />
          </Form.Item>
          <Form.Item name="metric" label="监控指标" rules={[{ required: true }]}>
            <Select placeholder="选择监控指标">
              <Option value="daily_revenue">日销售额</Option>
              <Option value="conversion_rate">转化率</Option>
              <Option value="inventory_level">库存水平</Option>
              <Option value="return_rate">退货率</Option>
              <Option value="order_count">订单数量</Option>
            </Select>
          </Form.Item>
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item name="condition" label="条件" rules={[{ required: true }]}>
                <Select placeholder="选择条件">
                  <Option value=">">大于</Option>
                  <Option value="<">小于</Option>
                  <Option value="=">等于</Option>
                  <Option value=">=">大于等于</Option>
                  <Option value="<=">小于等于</Option>
                </Select>
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item name="threshold" label="阈值" rules={[{ required: true }]}>
                <Input type="number" placeholder="输入阈值" />
              </Form.Item>
            </Col>
          </Row>
          <Form.Item name="notifyChannels" label="通知渠道" rules={[{ required: true }]}>
            <Checkbox.Group options={[
              { label: '邮件', value: 'email' },
              { label: '短信', value: 'sms' },
              { label: '应用内', value: 'app' },
            ]} />
          </Form.Item>
        </Form>
      </Modal>

      {/* 导出模态框 */}
      <Modal
        title="导出数据"
        open={exportModalVisible}
        onCancel={() => setExportModalVisible(false)}
        footer={[
          <Button key="cancel" onClick={() => setExportModalVisible(false)}>取消</Button>,
          <Button key="export" type="primary" icon={<ExportOutlined />}>导出</Button>,
        ]}
      >
        <Form layout="vertical">
          <Form.Item label="导出范围">
            <Radio.Group defaultValue="current">
              <Radio value="current">当前筛选结果</Radio>
              <Radio value="all">全部数据</Radio>
            </Radio.Group>
          </Form.Item>
          <Form.Item label="导出格式">
            <Radio.Group defaultValue="excel">
              <Radio value="excel">Excel (.xlsx)</Radio>
              <Radio value="csv">CSV (.csv)</Radio>
              <Radio value="pdf">PDF (.pdf)</Radio>
            </Radio.Group>
          </Form.Item>
        </Form>
      </Modal>

      {/* 详情抽屉 */}
      <Drawer
        title="详细信息"
        placement="right"
        width={600}
        onClose={() => setDetailDrawerVisible(false)}
        open={detailDrawerVisible}
      >
        {selectedItem && (
          <Descriptions bordered column={1}>
            {Object.entries(selectedItem).map(([key, value]) => (
              <Descriptions.Item key={key} label={key}>
                {typeof value === 'object' ? JSON.stringify(value) : String(value)}
              </Descriptions.Item>
            ))}
          </Descriptions>
        )}
      </Drawer>
    </div>
  );
};

export default Analytics;
