import React, { useEffect, useState } from 'react';
import { Table, Tag, Spin, Alert, Typography, Card } from 'antd';
import { useRequest } from 'umi';

const { Title, Text } = Typography;

interface Event {
  id: string;
  type: string;
  payload: any;
  timestamp: number;
  source: string;
  merchantId?: string;
}

const eventTypeMap: Record<string, string> = {
  PRODUCT_CREATED: '商品创建',
  PRODUCT_UPDATED: '商品更新',
  ORDER_CREATED: '订单创建',
  ORDER_PAID: '订单支付',
  ORDER_COMPLETED: '订单完成',
  INVENTORY_LOW: '库存不足',
  INVENTORY_UPDATED: '库存更新',
  FEATURE_ENABLED: '功能启用',
  FEATURE_DISABLED: '功能禁用',
  AI_TASK_CREATED: 'AI任务创建',
  AI_TASK_COMPLETED: 'AI任务完成',
  AD_STARTED: '广告开始',
  AD_PERFORMANCE_UPDATED: '广告性能更新',
  JOB_CREATED: '任务创建',
  JOB_UPDATED: '任务更新',
  JOB_COMPLETED: '任务完成',
  JOB_FAILED: '任务失败',
  BILLING_GENERATED: '账单生成'
};

export default function EventLog() {
  const [events, setEvents] = useState<Event[]>([]);
  const [loading, setLoading] = useState(true);
  const [ws, setWs] = useState<WebSocket | null>(null);

  // 获取事件日志
  const { run: fetchEvents } = useRequest(async () => {
    try {
      const response = await fetch('/api/events');
      const data = await response.json();
      setEvents(data.list || []);
    } catch (error) {
      console.error('Error fetching events:', error);
    } finally {
      setLoading(false);
    }
  }, {
    manual: true
  });

  // 初始化WebSocket连接
  useEffect(() => {
    // 从本地存储获取merchantId（实际应用中应该从认证信息中获取）
    const merchantId = localStorage.getItem('merchantId') || 'anonymous';
    
    // 建立WebSocket连接
    const socket = new WebSocket(`ws://localhost:8080?merchantId=${merchantId}`);
    
    socket.onopen = () => {
      console.log('WebSocket connected');
    };
    
    socket.onmessage = (event) => {
      try {
        const data = JSON.parse(event.data);
        
        // 处理任何事件，刷新事件列表
        if (data.type !== 'CONNECTION_SUCCESS') {
          fetchEvents();
        }
      } catch (error) {
        console.error('Error processing WebSocket message:', error);
      }
    };
    
    socket.onclose = () => {
      console.log('WebSocket disconnected');
    };
    
    socket.onerror = (error) => {
      console.error('WebSocket error:', error);
    };
    
    setWs(socket);
    
    // 组件卸载时关闭WebSocket连接
    return () => {
      socket.close();
    };
  }, [fetchEvents]);

  // 初始加载事件列表
  useEffect(() => {
    fetchEvents();
  }, [fetchEvents]);

  // 列定义
  const columns = [
    {
      title: '事件类型',
      dataIndex: 'type',
      key: 'type',
      render: (type: string) => eventTypeMap[type] || type,
    },
    {
      title: '来源',
      dataIndex: 'source',
      key: 'source',
    },
    {
      title: '时间',
      dataIndex: 'timestamp',
      key: 'timestamp',
      render: (timestamp: number) => new Date(timestamp).toLocaleString(),
      sorter: (a: Event, b: Event) => a.timestamp - b.timestamp,
      defaultSortOrder: 'descend',
    },
    {
      title: '商户ID',
      dataIndex: 'merchantId',
      key: 'merchantId',
      render: (merchantId: string) => merchantId || '-',
    },
    {
      title: '详情',
      key: 'details',
      render: (_: any, record: Event) => (
        <Text
          onClick={() => {
            // 查看事件详情
            console.log('Event details:', record);
          }}
          style={{ color: '#1890ff', cursor: 'pointer' }}
        >
          查看详情
        </Text>
      ),
    },
  ];

  return (
    <div style={{ padding: '24px' }}>
      <Title level={2}>事件日志</Title>
      
      <Card style={{ marginBottom: '24px' }}>
        <Text>系统事件日志记录了系统的所有关键操作和状态变化，帮助您了解系统的运行情况。</Text>
      </Card>
      
      {loading ? (
        <div style={{ textAlign: 'center', padding: '48px' }}>
          <Spin size="large" />
        </div>
      ) : events.length === 0 ? (
        <Alert message="暂无事件日志" type="info" />
      ) : (
        <Table
          rowKey="id"
          columns={columns}
          dataSource={events}
          pagination={{
            pageSize: 10,
            showSizeChanger: true,
            showQuickJumper: true,
          }}
          scroll={{ x: 800 }}
        />
      )}
    </div>
  );
}
