<template>
  <div class="flex items-center justify-center w-full py-2 leading-[1]">
    <!-- 分页数量选择 -->
    <div class="flex items-center space-x-2 text-[#68A1FF] mr-[26px]">
      <span>每页</span>
      <select v-model="currentPageSize" class="border rounded pl-[8px] py-[2px] border-[#68A1FF] bg-[#001C38] w-[65px]">
        <option v-for="size in pageSizes" :key="size" :value="size">{{ size }}</option>
      </select>
      <span>条</span>
    </div>
    <!-- 页码 -->
    <div class="flex items-center text-[#68A1FF]">
      <button
        class="px-2 bg-transparent text-[28px] leading-[1.8]"
        :disabled="isFirstPage"
        @click="prev"
      >‹</button>
      <template v-for="page in pageList" :key="page">
        <button
          class="px-2 rounded text-[17px] bg-transparent h-[28px]"
          :class="page === currentPage ? ' text-white' : ''"
          @click="changePage(page)"
        >{{ page }}</button>
      </template>
      <button
        class="px-2 bg-transparent text-[28px] leading-[1.8]"
        :disabled="isLastPage"
        @click="next"
      >›</button>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { computed, ref, watch, toRef } from 'vue';
import { useOffsetPagination } from '@vueuse/core';

const props = defineProps<{
  total: number,
  modelValue: number,
  pageSize?: number,
  pageSizes?: number[]
}>();

const emit = defineEmits(['update:modelValue', 'update:pageSize', 'change']);

const fetchData = ({ currentPage, currentPageSize }: { currentPage: number, currentPageSize: number }) => {
  emit('update:modelValue', currentPage);
  emit('update:pageSize', currentPageSize);
  emit('change', currentPage, currentPageSize);
};

// Create local, writable refs for page and pageSize
const page = ref(props.modelValue);
const pageSize = ref(props.pageSize || 10);

// Sync local state with props when they are changed from outside
watch(() => props.modelValue, (v) => page.value = v);
watch(() => props.pageSize, (v) => pageSize.value = v || 10);

const {
  currentPage,
  currentPageSize,
  pageCount,
  isFirstPage,
  isLastPage,
  prev,
  next,
} = useOffsetPagination({
  total: toRef(props, 'total'),
  page: page,
  pageSize: pageSize,
  onPageChange: fetchData,
  onPageSizeChange: fetchData,
});

const pageSizes = computed(() => props.pageSizes || [10, 20, 50, 100]);

const PAGE_BLOCK_SIZE = 5;

const pageList = computed(() => {
  const pages = [];
  if (pageCount.value <= PAGE_BLOCK_SIZE) {
    for (let i = 1; i <= pageCount.value; i++) pages.push(i);
    return pages;
  }

  let start = currentPage.value - Math.floor(PAGE_BLOCK_SIZE / 2);
  start = Math.max(1, start);
  start = Math.min(start, pageCount.value - PAGE_BLOCK_SIZE + 1);

  for (let i = start; i < start + PAGE_BLOCK_SIZE; i++) {
    pages.push(i);
  }
  return pages;
});

function changePage(p: number) {
  currentPage.value = p;
}
</script>
