export const usePaging = (options = {}) => {
  const { formatResult = (r) => r } = options
  const { query: enterQuery } = toRefs(options)
  const { apiFn } = options
  const paging = ref(null)
  const dataList = ref([])
  const dataTotal = ref(0)
  const query = ref({})

  watchEffect(() => {
    if (enterQuery) {
      query.value = {
        ...query.value,
        ...enterQuery.value
      }
    } else {
      query.value = {}
    }
  })

  const queryHandler = async (pageNum = 1, pageSize = 10, from, enterQuery) => {
    const params = enterQuery || query.value
    const { error, result } = await apiFn({
      pageNum,
      pageSize,
      ...params
    })
    if (error) {
      paging.value.complete(false)
    } else {
      const { rows, total } = result
      const list = formatResult(rows)
      paging.value.complete(list)
      dataTotal.value = total
    }
  }

  const clearHandler = () => {
    clear()
    reload()
  }

  const enterHandler = () => {
    clearHandler()
  }

  const reload = () => {
    paging.value.reload()
  }

  const clear = () => {
    paging.value.clear()
  }

  const scrollToTop = () => {
    paging.value.scrollToTop()
  }

  return {
    paging,
    query,
    dataList,
    dataTotal,
    queryHandler,
    clearHandler,
    enterHandler,
    reload,
    clear,
    scrollToTop
  }
}
