/**
 * 分页管理 Composable
 */

import { reactive, computed } from 'vue'

export interface PaginationOptions {
  initialPage?: number
  initialPageSize?: number
  pageSizes?: number[]
  layout?: string
}

export function usePagination(options: PaginationOptions = {}) {
  const {
    initialPage = 1,
    initialPageSize = 20,
    pageSizes = [10, 20, 50, 100],
    layout = 'total, sizes, prev, pager, next, jumper'
  } = options

  // 分页状态
  const pagination = reactive({
    current: initialPage,
    size: initialPageSize,
    total: 0,
    pageSizes,
    layout
  })

  // 当前页码（别名）
  const currentPage = computed({
    get: () => pagination.current,
    set: (val) => (pagination.current = val)
  })

  // 每页数量（别名）
  const pageSize = computed({
    get: () => pagination.size,
    set: (val) => (pagination.size = val)
  })

  // 总页数
  const totalPages = computed(() => {
    return Math.ceil(pagination.total / pagination.size)
  })

  // 是否有上一页
  const hasPrev = computed(() => pagination.current > 1)

  // 是否有下一页
  const hasNext = computed(() => pagination.current < totalPages.value)

  // 重置分页
  const reset = () => {
    pagination.current = initialPage
    pagination.size = initialPageSize
    pagination.total = 0
  }

  // 设置总数
  const setTotal = (total: number) => {
    pagination.total = total
  }

  // 处理页码变化
  const handleCurrentChange = (page: number) => {
    pagination.current = page
  }

  // 处理每页数量变化
  const handleSizeChange = (size: number) => {
    pagination.size = size
    pagination.current = 1 // 改变每页数量时重置到第一页
  }

  // 跳转到第一页
  const toFirstPage = () => {
    pagination.current = 1
  }

  // 跳转到最后一页
  const toLastPage = () => {
    pagination.current = totalPages.value
  }

  // 上一页
  const prevPage = () => {
    if (hasPrev.value) {
      pagination.current--
    }
  }

  // 下一页
  const nextPage = () => {
    if (hasNext.value) {
      pagination.current++
    }
  }

  return {
    pagination,
    currentPage,
    pageSize,
    totalPages,
    hasPrev,
    hasNext,
    reset,
    setTotal,
    handleCurrentChange,
    handleSizeChange,
    toFirstPage,
    toLastPage,
    prevPage,
    nextPage
  }
}
