/**
 * Table Pagination composable
 * 表格分页逻辑
 */

import { ref, computed } from 'vue'

export interface PaginationOptions {
  pageSize?: number
  initialPage?: number
}

export function useTablePage(options: PaginationOptions = {}) {
  const { pageSize = 10, initialPage = 1 } = options

  const currentPage = ref(initialPage)
  const currentPageSize = ref(pageSize)

  const canGoPrev = computed(() => currentPage.value > 1)
  const canGoNext = computed(() => currentPage.value * currentPageSize.value < totalItems.value)

  const totalItems = ref(0)
  const totalPages = computed(() => Math.ceil(totalItems.value / currentPageSize.value))

  const nextPage = () => {
    if (canGoNext.value) currentPage.value++
  }

  const prevPage = () => {
    if (canGoPrev.value) currentPage.value--
  }

  const goToPage = (page: number) => {
    if (page >= 1 && page <= totalPages.value) {
      currentPage.value = page
    }
  }

  const reset = () => {
    currentPage.value = initialPage
  }

  const setTotalItems = (total: number) => {
    totalItems.value = total
  }

  return {
    currentPage,
    currentPageSize,
    canGoPrev,
    canGoNext,
    totalItems,
    totalPages,
    nextPage,
    prevPage,
    goToPage,
    reset,
    setTotalItems
  }
}
