import useSWRInfinite from "swr/infinite";

export type TResponseData<D> = {
  data: D
  nextId?: string
  totalCount?: null | number
  pageIndex?: number
  pageSize?: number
}

export const createKey = (query: string, pageSize: number = 10, extra: Record<string, any> = []) => {
  return (pageIndex: number, previousPageData) => {
    if (pageIndex === 0)
      return [
        query,
        { nextId: undefined, pageSize },
        extra,
      ];
      // 如果是以 pageIndex 作为分页依据
    if (previousPageData && previousPageData.pageIndex) {
      return [
        query,
        { pageSize, pageIndex: previousPageData.pageIndex+1 },
        extra,
      ];
    }
    if (previousPageData && previousPageData.nextId) {
      return [
        query,
        { pageSize, nextId: previousPageData.nextId },
        extra,
      ];
    }
    return null;
  };
}
export const useLoadMoreInfinite = <T>(getKey, fetcher, params = {}) => {
  const { data, setSize, size, mutate } = useSWRInfinite<{
    data: T
    nextId?: string
    totalCount?: null | number
    pageIndex?: number
    pageSize?: number
  }>(getKey, fetcher, {
    ...params,
    revalidateIfStale: false,
    revalidateFirstPage: false,
    onErrorRetry(err, key, config, revalidate, revalidateOpts) {
      if (err.status === 404) return
      if (err.status === 401) return
      if (revalidateOpts.retryCount >= 3) return
    },
  });

  // 扁平化后的数据列表
  const list = (data?.flatMap((page) => page?.data || []) || []) as T;
  // 原分页数据二维数组
  const pages = data
  const pageIndex = size


  const loadMore = () => {
    setSize((size) => size + 1);
  }
  return {
    list,
    pageIndex,
    pages,
    mutate,
    setSize,
    loadMore
  }
}