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

const { Title, Text } = Typography;

interface Job {
  id: string;
  type: string;
  status: 'pending' | 'running' | 'success' | 'failed';
  payload: any;
  result?: any;
  retryCount: number;
  merchantId?: string;
  createdAt: number;
  updatedAt: number;
}

const statusColorMap: Record<string, string> = {
  pending: 'orange',
  running: 'blue',
  success: 'green',
  failed: 'red'
};

const statusTextMap: Record<string, string> = {
  pending: '待处理',
  running: '处理中',
  success: '已完成',
  failed: '失败'
};

const jobTypeMap: Record<string, string> = {
  AI_OPTIMIZE_PRODUCT: 'AI优化商品',
  SYNC_INVENTORY: '同步库存',
  RUN_ADS: '运行广告',
  CALCULATE_PROFIT: '计算利润',
  GENERATE_BILL: '生成账单',
  UPDATE_AD_BUDGET: '更新广告预算',
  STOP_AD: '停止广告'
};

export default function TaskCenter() {
  const [jobs, setJobs] = useState<Job[]>([]);
  const [loading, setLoading] = useState(true);
  const [ws, setWs] = useState<WebSocket | null>(null);

  // 获取任务列表
  const { run: fetchJobs } = useRequest(async () => {
    try {
      const response = await fetch('/api/jobs');
      const data = await response.json();
      setJobs(data.list || []);
    } catch (error) {
      console.error('Error fetching jobs:', 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 === 'JOB_UPDATED' || data.type === 'JOB_COMPLETED' || data.type === 'JOB_FAILED') {
          fetchJobs();
        }
        
        // 处理AI任务完成事件
        if (data.type === 'AI_TASK_COMPLETED') {
          fetchJobs();
        }
      } 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();
    };
  }, [fetchJobs]);

  // 初始加载任务列表
  useEffect(() => {
    fetchJobs();
  }, [fetchJobs]);

  // 列定义
  const columns = [
    {
      title: '任务ID',
      dataIndex: 'id',
      key: 'id',
      ellipsis: true,
    },
    {
      title: '任务类型',
      dataIndex: 'type',
      key: 'type',
      render: (type: string) => jobTypeMap[type] || type,
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status: string) => (
        <Tag color={statusColorMap[status]}>
          {statusTextMap[status]}
        </Tag>
      ),
    },
    {
      title: '重试次数',
      dataIndex: 'retryCount',
      key: 'retryCount',
    },
    {
      title: '创建时间',
      dataIndex: 'createdAt',
      key: 'createdAt',
      render: (timestamp: number) => new Date(timestamp).toLocaleString(),
    },
    {
      title: '更新时间',
      dataIndex: 'updatedAt',
      key: 'updatedAt',
      render: (timestamp: number) => new Date(timestamp).toLocaleString(),
    },
    {
      title: '操作',
      key: 'action',
      render: (_: any, record: Job) => (
        <Text
          onClick={() => {
            // 查看任务详情
            console.log('Job details:', record);
          }}
          style={{ color: '#1890ff', cursor: 'pointer' }}
        >
          查看详情
        </Text>
      ),
    },
  ];

  // 统计数据
  const stats = {
    total: jobs.length,
    pending: jobs.filter(job => job.status === 'pending').length,
    running: jobs.filter(job => job.status === 'running').length,
    success: jobs.filter(job => job.status === 'success').length,
    failed: jobs.filter(job => job.status === 'failed').length,
  };

  return (
    <div style={{ padding: '24px' }}>
      <Title level={2}>任务中心</Title>
      
      <Row gutter={[16, 16]} style={{ marginBottom: '24px' }}>
        <Col span={6}>
          <Card>
            <Text strong>总任务数</Text>
            <div style={{ fontSize: '24px', marginTop: '8px' }}>{stats.total}</div>
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Text strong>待处理</Text>
            <div style={{ fontSize: '24px', marginTop: '8px', color: statusColorMap.pending }}>{stats.pending}</div>
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Text strong>处理中</Text>
            <div style={{ fontSize: '24px', marginTop: '8px', color: statusColorMap.running }}>{stats.running}</div>
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Text strong>已完成</Text>
            <div style={{ fontSize: '24px', marginTop: '8px', color: statusColorMap.success }}>{stats.success}</div>
          </Card>
        </Col>
      </Row>
      
      {loading ? (
        <div style={{ textAlign: 'center', padding: '48px' }}>
          <Spin size="large" />
        </div>
      ) : jobs.length === 0 ? (
        <Alert message="暂无任务" type="info" />
      ) : (
        <Table
          rowKey="id"
          columns={columns}
          dataSource={jobs}
          pagination={{
            pageSize: 10,
            showSizeChanger: true,
            showQuickJumper: true,
          }}
          scroll={{ x: 1000 }}
        />
      )}
    </div>
  );
}
