/**
 * 下载中心弹窗组件
 * - 展示异步导出任务列表
 * - 自动轮询刷新（每5秒）
 * - 已完成任务可下载
 */

import { useState, useEffect, useCallback } from 'react';
import {
  Modal,
  Table,
  Button,
  Tag,
  Progress,
  Message,
  Space,
} from '@arco-design/web-react';
import { IconDownload, IconRefresh } from '@arco-design/web-react/icon';
import { api } from '@/api/request';

/** 下载任务类型 */
interface DownloadTask {
  id: number;
  task_type: string;
  status: number;
  status_text: string;
  file_name: string | null;
  progress: number;
  error_message: string | null;
  created_at: string | null;
  completed_at: string | null;
}

/** 状态标签颜色映射 */
const STATUS_COLOR: Record<number, string> = {
  0: 'gray',
  1: 'blue',
  2: 'green',
  3: 'red',
};

interface DownloadCenterProps {
  visible: boolean;
  onClose: () => void;
}

export default function DownloadCenter({ visible, onClose }: DownloadCenterProps) {
  const [tasks, setTasks] = useState<DownloadTask[]>([]);
  const [total, setTotal] = useState(0);
  const [loading, setLoading] = useState(false);
  const [page, setPage] = useState(1);
  const pageSize = 10;

  /** 获取下载任务列表 */
  const fetchTasks = useCallback(async () => {
    setLoading(true);
    try {
      const res = await api.get<{
        list: DownloadTask[];
        total: number;
      }>(`/downloads?page=${page}&page_size=${pageSize}`);
      setTasks(res.data.list || []);
      setTotal(res.data.total || 0);
    } catch {
      /* 静默处理 */
    } finally {
      setLoading(false);
    }
  }, [page]);

  /** 弹窗打开时加载数据 */
  useEffect(() => {
    if (visible) {
      fetchTasks();
    }
  }, [visible, fetchTasks]);

  /** 自动轮询（有进行中的任务时） */
  useEffect(() => {
    if (!visible) return;
    const hasActive = tasks.some((t) => t.status === 0 || t.status === 1);
    if (!hasActive) return;

    const timer = setInterval(fetchTasks, 5000);
    return () => clearInterval(timer);
  }, [visible, tasks, fetchTasks]);

  /** 点击下载 */
  const handleDownload = async (taskId: number) => {
    try {
      const res = await api.get<{ download_url: string }>(
        `/downloads/${taskId}`
      );
      if (res.data.download_url) {
        window.open(res.data.download_url, '_blank');
      }
    } catch {
      Message.error('获取下载链接失败');
    }
  };

  /** 手动清理过期文件 */
  const handleCleanup = async () => {
    try {
      await api.post('/downloads/cleanup', { retain_days: 7 });
      Message.success('清理完成');
      fetchTasks();
    } catch {
      Message.error('清理失败');
    }
  };

  /** 状态标签 */
  const renderStatus = (status: number) => (
    <Tag color={STATUS_COLOR[status] || 'gray'}>{statusText(status)}</Tag>
  );

  /** 进度列 */
  const renderProgress = (progress: number, record: DownloadTask) => {
    if (record.status === 0) return <span>等待中</span>;
    if (record.status === 3) return <span style={{ color: 'red' }}>失败</span>;
    return <Progress percent={progress} size="small" />;
  };

  /** 操作列 */
  const renderAction = (_: unknown, record: DownloadTask) => {
    if (record.status === 2) {
      return (
        <Button
          type="primary"
          size="small"
          icon={<IconDownload />}
          onClick={() => handleDownload(record.id)}
        >
          下载
        </Button>
      );
    }
    if (record.status === 3) {
      return <span style={{ color: 'red', fontSize: 12 }}>{record.error_message || '失败'}</span>;
    }
    return <span style={{ color: '#999' }}>等待...</span>;
  };

  const columns = [
    { title: '文件名', dataIndex: 'file_name', width: 240 },
    { title: '状态', dataIndex: 'status', width: 90, render: renderStatus },
    { title: '进度', dataIndex: 'progress', width: 150, render: renderProgress },
    { title: '创建时间', dataIndex: 'created_at', width: 170 },
    { title: '操作', dataIndex: 'action', width: 120, render: renderAction },
  ];

  return (
    <Modal
      title="下载中心"
      visible={visible}
      onCancel={onClose}
      footer={null}
      style={{ width: 800 }}
    >
      <Space style={{ marginBottom: 12 }}>
        <Button icon={<IconRefresh />} onClick={fetchTasks} loading={loading}>
          刷新
        </Button>
        <Button onClick={handleCleanup}>清理过期文件</Button>
      </Space>
      <Table
        rowKey="id"
        columns={columns}
        data={tasks}
        loading={loading}
        pagination={{
          current: page,
          total,
          pageSize,
          onChange: setPage,
        }}
        size="small"
      />
    </Modal>
  );
}

/** 状态码文本 */
function statusText(status: number): string {
  switch (status) {
    case 0: return '排队中';
    case 1: return '处理中';
    case 2: return '已完成';
    case 3: return '失败';
    default: return '未知';
  }
}
