import {BaseListResult} from '@models';
import {useQuery} from '@tanstack/react-query';

type UseQueryDataInfoOptions<R, P extends unknown[]> = {
  queryFn: (...args: P) => BaseListResult<R>;
  params: P;
  enabled: boolean;
  extraKeys?: unknown[];
  label?: string;
};

// 获取详情不加signal 不然可能导致取消后重新进入报错
export function useQueryDataInfo<R, P extends unknown[]>({
  queryFn,
  params,
  enabled,
  extraKeys = [],
  label = '',
}: UseQueryDataInfoOptions<R, P>): R | undefined {
  const {data} = useQuery(
    [queryFn.name, ...params, ...extraKeys],
    async function () {
      const data = await queryFn(...params);

      if (data.msg === '200') {
        const {
          data: {list},
        } = data;

        if (list.length > 0) return list[0];

        throw new Error(`未获取到${label}信息`);
      }

      throw new Error(data.errMsg);
    },
    {suspense: true, enabled},
  );

  return data;
}
