<script setup>
import { computed } from 'vue';

const props = defineProps({
  total: { type: Number, default: 0 },
  page: { type: Number, default: 1 },
  pageSize: { type: Number, default: 20 },
  totalPages: { type: Number, default: 0 },
  sizes: { type: Array, default: () => [20, 50, 100] }
});
const emit = defineEmits(['update:page', 'update:pageSize']);
const pages = computed(() => props.totalPages || Math.max(1, Math.ceil(props.total / props.pageSize)));
const start = computed(() => props.total ? (props.page - 1) * props.pageSize + 1 : 0);
const end = computed(() => Math.min(props.total, props.page * props.pageSize));
const nearby = computed(() => [...new Set([1, props.page - 1, props.page, props.page + 1, pages.value])].filter(value => value >= 1 && value <= pages.value));
</script>

<template>
  <nav class="ledger-pagination" aria-label="列表分页">
    <span>第 {{ start }}—{{ end }} 条，共 {{ total }} 条</span>
    <div>
      <button type="button" :disabled="page <= 1" @click="emit('update:page', page - 1)">上一页</button>
      <template v-for="(value, index) in nearby" :key="value">
        <i v-if="index && value - nearby[index - 1] > 1">…</i>
        <button type="button" :class="{ active: value === page }" @click="emit('update:page', value)">{{ value }}</button>
      </template>
      <button type="button" :disabled="page >= pages" @click="emit('update:page', page + 1)">下一页</button>
      <label>每页
        <select :value="pageSize" @change="emit('update:pageSize', Number($event.target.value))">
          <option v-for="size in sizes" :key="size" :value="size">{{ size }}</option>
        </select>
        条
      </label>
    </div>
  </nav>
</template>
