/**
 * 筛选结果列表Hook
 * 用于获取和管理筛选结果列表（支持分页和筛选）
 */

import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { message } from 'antd';
import { aslApi } from '../api';

interface UseScreeningResultsOptions {
  projectId: string;
  page?: number;
  pageSize?: number;
  filter?: 'all' | 'conflict' | 'included' | 'excluded' | 'reviewed';
  enabled?: boolean;
}

/**
 * 使用筛选结果Hook
 */
export function useScreeningResults({
  projectId,
  page = 1,
  pageSize = 50,
  filter = 'all',
  enabled = true,
}: UseScreeningResultsOptions) {
  const queryClient = useQueryClient();

  // 查询筛选结果列表
  const { data, isLoading, error, refetch } = useQuery({
    queryKey: ['screening-results', projectId, page, pageSize, filter],
    queryFn: () => aslApi.getScreeningResultsList(projectId, { page, pageSize, filter }),
    enabled: enabled && !!projectId,
    staleTime: 1000 * 30, // 30秒内认为数据是新鲜的
    keepPreviousData: true, // 切换页面时保留上一页数据，避免闪烁
  });

  const results = data?.data?.items || [];
  const total = data?.data?.total || 0;
  const totalPages = data?.data?.totalPages || 0;

  // 人工复核Mutation
  const reviewMutation = useMutation({
    mutationFn: ({ resultId, decision, note }: {
      resultId: string;
      decision: 'include' | 'exclude';
      note?: string;
    }) => aslApi.reviewScreeningResult(resultId, { decision, note }),
    onSuccess: () => {
      // 刷新列表
      queryClient.invalidateQueries({ queryKey: ['screening-results', projectId] });
      message.success('复核提交成功');
    },
    onError: (error: any) => {
      message.error(`复核失败: ${error.message}`);
    },
  });

  return {
    results,
    total,
    totalPages,
    page,
    pageSize,
    isLoading,
    error,
    refetch,
    // 人工复核方法
    review: reviewMutation.mutate,
    isReviewing: reviewMutation.isPending,
  };
}





