import React, { useEffect, useState } from 'react';
import { Drawer, List, Tag, Typography, Spin, Space, Pagination } from 'antd';
import { getRunningSyncs, getSyncStatus } from '../service';
import { RunningSyncDTO, RepositorySyncStatusDTO } from '../types';
import dayjs from 'dayjs';
import { SyncOutlined, CheckCircleOutlined, CloseCircleOutlined } from '@ant-design/icons';

const { Text } = Typography;

interface SyncStatusDrawerProps {
  visible: boolean;
  onClose: () => void;
  autoRefresh?: boolean;
}

const PAGE_SIZE = 5;  // 每页显示的数量

const SyncStatusDrawer: React.FC<SyncStatusDrawerProps> = ({ 
  visible, 
  onClose,
  autoRefresh = false 
}) => {
  const [runningSyncs, setRunningSyncs] = useState<RunningSyncDTO[]>([]);
  const [syncStatuses, setSyncStatuses] = useState<Record<number, RepositorySyncStatusDTO>>({});
  const [loading, setLoading] = useState(false);
  const [currentPage, setCurrentPage] = useState(1);

  const fetchRunningSyncs = async () => {
    try {
      const response = await getRunningSyncs();
      setRunningSyncs(response || []);
      
      // 只为正在运行的任务获取最新状态
      response?.forEach(async (sync) => {
        if (sync.status === 'RUNNING') {
          const status = await getSyncStatus(sync.historyId);
          setSyncStatuses(prev => ({
            ...prev,
            [sync.historyId]: status
          }));
        }
      });
    } catch (error) {
      console.error('获取同步任务失败:', error);
    }
  };

  useEffect(() => {
    // 只在抽屉可见时才获取数据
    if (visible) {
      setLoading(true);
      fetchRunningSyncs().finally(() => setLoading(false));
      
      // 只在抽屉可见时启动定时刷新
      const timer = setInterval(fetchRunningSyncs, 5000);
      return () => clearInterval(timer);
    }
  }, [visible]);  // 移除 autoRefresh 依赖

  // 计算当前页的数据
  const getCurrentPageData = () => {
    const startIndex = (currentPage - 1) * PAGE_SIZE;
    return runningSyncs.slice(startIndex, startIndex + PAGE_SIZE);
  };

  const handlePageChange = (page: number) => {
    setCurrentPage(page);
  };

  const renderSyncType = (type: string) => {
    const colorMap: Record<string, string> = {
      GROUP: 'blue',
      PROJECT: 'green',
      BRANCH: 'orange',
    };
    return <Tag color={colorMap[type] || 'default'}>{type}</Tag>;
  };

  const renderStatus = (item: RunningSyncDTO) => {
    // 如果状态是 RUNNING，需要检查是否真正在运行
    if (item.status === 'RUNNING') {
      return item.actuallyRunning ? (
        <Tag icon={<SyncOutlined spin />} color="processing">同步中</Tag>
      ) : (
        <Tag icon={<CloseCircleOutlined />} color="error">异常终止</Tag>
      );
    }
    
    // 其他状态正常显示
    switch (item.status) {
      case 'SUCCESS':
        return <Tag icon={<CheckCircleOutlined />} color="success">成功</Tag>;
      case 'FAILED':
        return <Tag icon={<CloseCircleOutlined />} color="error">失败</Tag>;
      default:
        return <Tag>未知状态</Tag>;
    }
  };

  const renderErrorMessage = (item: RunningSyncDTO) => {
    // 优先使用实时错误信息，如果没有则使用历史记录中的错误信息
    const errorMessage = syncStatuses[item.historyId]?.errorMessage || item.errorMessage;
    if (errorMessage) {
      return (
        <div style={{ color: '#ff4d4f', fontSize: '12px', marginTop: '4px' }}>
          错误信息: {errorMessage}
        </div>
      );
    }
    return null;
  };

  const renderTip = () => {
    if (!visible && autoRefresh) {
      return (
        <div style={{ marginTop: 8, color: '#666' }}>
          同步任务正在后台运行，您可以随时打开此抽屉查看进度
        </div>
      );
    }
    return null;
  };

  return (
    <>
      <Drawer
        title="历史同步记录"
        placement="right"
        onClose={onClose}
        open={visible}
        width={400}
      >
        <div style={{ 
          display: 'flex', 
          flexDirection: 'column', 
          height: '100%' 
        }}>
          <Spin spinning={loading}>
            {runningSyncs.length === 0 ? (
              <Text>当前没有正在进行的同步任务</Text>
            ) : (
              <>
                <List
                  dataSource={getCurrentPageData()}
                  renderItem={(item) => (
                    <List.Item>
                      <List.Item.Meta
                        title={
                          <Space>
                            {item.repositoryName}
                            {renderStatus(item)}
                          </Space>
                        }
                        description={
                          <>
                            <div>同步类型: {renderSyncType(item.syncType)}</div>
                            <div>开始时间: {dayjs(item.startTime).format('YYYY-MM-DD HH:mm:ss')}</div>
                            {syncStatuses[item.historyId]?.endTime && (
                              <div>结束时间: {dayjs(syncStatuses[item.historyId].endTime).format('YYYY-MM-DD HH:mm:ss')}</div>
                            )}
                            {renderErrorMessage(item)}
                          </>
                        }
                      />
                    </List.Item>
                  )}
                />
                <div style={{ 
                  marginTop: 16,
                  padding: '10px 0',
                  borderTop: '1px solid #f0f0f0',
                  textAlign: 'right'
                }}>
                  <Pagination
                    current={currentPage}
                    total={runningSyncs.length}
                    pageSize={PAGE_SIZE}
                    onChange={handlePageChange}
                    size="small"
                    showSizeChanger={false}
                    showTotal={(total) => `共 ${total} 条`}
                  />
                </div>
              </>
            )}
            {renderTip()}
          </Spin>
        </div>
      </Drawer>
    </>
  );
};

export default SyncStatusDrawer; 