import { useState } from "react";
import useSWR from "swr";

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

export const useLoadMore = <T>({url, fetcher, startId, pageIndex=1,  pageSize = 10, params = [], } : {
  url: string,
  fetcher: any,
  startId?: number, // nextId
  pageIndex?: number,
  pageSize?: number,
  params?: any[]

}) => {
  const [page, setPage]  = useState(pageIndex)
  const [nextId, setNextId]  = useState(startId)
  console.log(url, nextId, page, pageSize)
  // 使用 useSWR
  const { data, error, isLoading, mutate } = useSWR<TResponseData<T>>(
    // key 数组，当这些值变化时会重新请求
    [url, nextId, page, pageSize, ...params],
    fetcher,
    {
      onErrorRetry(err, key, config, revalidate, revalidateOpts) {
        if(err.status === 404) return 
        if(err.status === 401) return
        if(revalidateOpts.retryCount >=3 )return
      },
    }
  )

  
  // 多页加载 可能返回的数据结构
  // nextId?: string
  // totalCount?: null|number
  // pageIndex?: number
  // pageSize?: number
  const hasNextPage = ()=> {
    if(data?.totalCount  === null || data?.totalCount === undefined){
      return false
    }
    if(data?.totalCount <= 0){
      return false
    }
    // 如果返回的是 nextId 则没有 pageIndex 和 pageSize
    if(data?.pageIndex === undefined){
      return false
    }
    if(data?.pageSize === undefined){
      return false
    }
    if(data.totalCount > (data.pageSize * data.pageIndex)){
      return true
    }
  }
  
  // 加载更多数据
  const loadMore = () => {
    // console.log(data?.nextId, data?.totalCount, data.pageSize * data.pageIndex)
    // data.totalCount 可能为 null , 
    // data.pageIndex 可能为 undefined
    // null > NaN === false
    
    if (data?.nextId || hasNextPage()) {
      //@ts-ignore
      setNextId(data.nextId);
      setPage(prev => prev + 1);
      // 这里可以选择是否立即 mutate，通常 setPage/setNextId 后 useSWR 会自动请求
    }
  }

  const refetch = async () => {
    setPage(1);
    setNextId(undefined)
    mutate(undefined, true); // 重新请求数据
  }

  return {
    page,
    setPage,
    data,
    error,
    isLoading,
    mutate,
    loadMore,
    refetch,
  }
}