import { computed, ref, watch } from "vue";
import useDebounce from '@/utils/useDebounce'

export default function usePageList(callback, options = {}) {
  const keyword = ref('')
  const list = ref([])
  const page = ref(1)
  const pageSize = ref(options.pageSize || 20)
  const pages = ref(0);
  const loading = ref(false)
  const total = ref(0)

  const hasMore = computed(() => page.value < pages.value)

  const handleKeywordChange = useDebounce(() => {
    getList()
  }, options.debounce || 1000)

  function changePage(p) {
    if (loading.value) return
    page.value = p
    getList()
  }

  function getList() {
    typeof callback === 'function' && callback()
  }

  watch(keyword, handleKeywordChange);

  return { total, page, pageSize, keyword, list, pages, changePage, loading, hasMore }

}
