import { reactive, ref } from "vue";

export function useInfiniteScroll<T = any>(
  pageSize: number,
  loadData: (page: number) => Promise<T[]>
) {
  const loading = ref(false);
  const page = ref(1);
  const hasNext = ref(false);
  const list = ref();

  const refresh = () => {
    if (loading.value) {
      return;
    }
    uni.showLoading({
      title: "加载中",
    });
    loading.value = true;
    return loadData(1)
      .then((res) => {
        uni.hideLoading();
        loading.value = false;
        page.value = 1;
        hasNext.value = res.length >= pageSize;
        list.value = res;
        uni.stopPullDownRefresh();
      })
      .catch(() => {
        uni.hideLoading();
        uni.stopPullDownRefresh();
        loading.value = false;
        list.value = [];
      });
  };

  const next = () => {
    if (hasNext.value) {
      if (loading.value) {
        return;
      }
      uni.showLoading({
        title: "加载中",
      });
      loading.value = true;
      return loadData(page.value + 1)
        .then((res) => {
          uni.hideLoading();
          loading.value = false;
          hasNext.value = res.length >= pageSize;
          if (!res || res.length <= 0) {
            return;
          }
          page.value = page.value + 1;
          res.forEach((item) => {
            list.value.push(item);
          });
        })
        .catch(() => {
          uni.hideLoading();
          hasNext.value = false;
          loading.value = false;
        });
    }
  };

  return reactive({
    page,
    loading,
    hasNext,
    list,
    refresh,
    next
  });
}
