import { useRealtime } from './useRealtime'
import { reactive, watch, isProxy, Ref, isRef } from 'vue'
import { useActive } from './useActive'

import type { PageRequest, PageResult } from '@/api'

export function usePaging<P extends {}, A>(
  fetch: (p: PageRequest<P>) => Promise<PageResult<A>>,
  initial: P | Ref<P>,
  setting?: { pageSize?: number; auto?: boolean }
) {
  const pagination = reactive({
    current: 1,
    total: 0,
    showSizeChanger: false,
    pageSize: setting?.pageSize || 10,
    onChange: (current: number) => {
      pagination.current = current
      updateList()
    }
  })

  const [list, updateList] = useRealtime(async () => {
    const result = await fetch({
      ...(isRef(initial) ? initial.value : initial),
      pageNum: pagination.current,
      pageSize: pagination.pageSize
    })
    pagination.total = result.total
    return result.list
  }, [])

  if (!setting || !('auto' in setting) || setting?.auto) {
    const active = useActive()
    if (isRef(initial) || isProxy(initial)) {
      watch(initial, () => active.value && updateList())
    }
  }

  return { list, pagination, updateList }
}
