import type { Pagination, BasicTableProps } from '@/types/table'
import { computed, unref, ref, ComputedRef, watch } from 'vue'
import { isBoolean } from '@/utils/is'
import { PAGE_SIZE, PAGE_SIZE_OPTIONS } from '../src/const'

export function usePagination(refProps: ComputedRef<BasicTableProps>) {
  const configRef = ref<Pagination>({})
  const show = ref(true)

  watch(
    () => unref(refProps).pagination,
    (pagination) => {
      if (!isBoolean(pagination) && pagination) {
        configRef.value = {
          ...unref(configRef),
          ...(pagination ?? {})
        }
      }
    }
  )

  //获取分页配置
  const getPaginationInfo = computed((): Pagination | false => {
    const { pagination } = unref(refProps)

    if (!unref(show) || (isBoolean(pagination) && !pagination)) {
      return false
    }

    return Object.assign(
      {
        currentPage: 1,
        pageSize: PAGE_SIZE,
        defaultPageSize: PAGE_SIZE,
        pageSizes: PAGE_SIZE_OPTIONS,
        total: 0,
        layout: 'total, sizes, prev, pager, next, jumper',
        hideOnSinglePage: false
      },
      { ...unref(configRef) }
    )
  })

  //设置分页
  const setPagination = (info: Partial<Pagination>) => {
    const paginationInfo = unref(getPaginationInfo)
    configRef.value = {
      ...(!isBoolean(paginationInfo) ? paginationInfo : {}),
      ...info
    }
  }

  //对外暴露
  function getPagination() {
    return unref(getPaginationInfo)
  }

  //对外暴露是否展分页
  function getShowPagination() {
    return unref(show)
  }

  async function setShowPagination(flag: boolean) {
    show.value = flag
  }

  return { getPagination, getPaginationInfo, setShowPagination, getShowPagination, setPagination }
}
