/**
 * 筛选任务轮询Hook
 * 用于获取和轮询筛选任务进度
 */

import { useQuery } from '@tanstack/react-query';
import { aslApi } from '../api';

interface UseScreeningTaskOptions {
  projectId: string;
  enabled?: boolean;
  pollingInterval?: number; // 轮询间隔（毫秒），默认1000
}

/**
 * 使用筛选任务Hook
 */
export function useScreeningTask({
  projectId,
  enabled = true,
  pollingInterval = 1000,
}: UseScreeningTaskOptions) {
  const { data, isLoading, error, refetch } = useQuery({
    queryKey: ['screening-task', projectId],
    queryFn: () => aslApi.getScreeningTask(projectId),
    enabled: enabled && !!projectId,
    refetchInterval: (query) => {
      const task = query.state.data?.data;
      // 如果任务已完成或失败，停止轮询
      if (task?.status === 'completed' || task?.status === 'failed') {
        return false;
      }
      return pollingInterval;
    },
    staleTime: 0, // 始终视为过时，确保轮询生效
  });

  const task = data?.data;

  // 计算进度百分比
  const progress = task
    ? Math.round((task.processedItems / task.totalItems) * 100)
    : 0;

  // 判断是否正在运行
  const isRunning = task?.status === 'running' || task?.status === 'pending';

  // 判断是否已完成
  const isCompleted = task?.status === 'completed';

  // 判断是否失败
  const isFailed = task?.status === 'failed';

  return {
    task,
    progress,
    isRunning,
    isCompleted,
    isFailed,
    isLoading,
    error,
    refetch,
  };
}




