<script setup lang="ts">
import { computed } from 'vue'

interface Props {
  currentPage: number
  pageSize: number
  total: number
  loading?: boolean
}

interface Emits {
  (e: 'update:currentPage', value: number): void
  (e: 'update:pageSize', value: number): void
  (e: 'pageChange'): void
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()

const totalPages = computed(() => Math.max(1, Math.ceil(props.total / props.pageSize)))
const currentCount = computed(() => {
  if (!props.total) return 0
  const start = (props.currentPage - 1) * props.pageSize
  return Math.min(props.pageSize, props.total - start)
})

function handleSizeChange(size: number) {
  emit('update:pageSize', size)
  emit('update:currentPage', 1)
  emit('pageChange')
}

function prevPage() {
  if (props.currentPage <= 1) return
  emit('update:currentPage', props.currentPage - 1)
  emit('pageChange')
}

function nextPage() {
  if (props.currentPage >= totalPages.value) return
  emit('update:currentPage', props.currentPage + 1)
  emit('pageChange')
}
</script>

<template>
  <div class="table-pagination">
    <span class="pagination-summary">当前页 {{ currentCount }} 条，共 {{ total }} 条</span>
    <div class="pagination-controls">
      <span class="pagination-size-label">每页</span>
      <el-select
        :model-value="pageSize"
        class="page-size-select"
        size="small"
        @update:model-value="handleSizeChange"
      >
        <el-option :value="10" label="10条" />
        <el-option :value="20" label="20条" />
        <el-option :value="50" label="50条" />
        <el-option :value="100" label="100条" />
      </el-select>
      <span class="pagination-page">{{ currentPage }}/{{ totalPages }}页</span>
      <el-button size="small" :disabled="currentPage <= 1 || loading" @click="prevPage"
        >上页</el-button
      >
      <el-button size="small" :disabled="currentPage >= totalPages || loading" @click="nextPage"
        >下页</el-button
      >
    </div>
  </div>
</template>
