<template>
  <!-- 分页组件 -->
  <div class="pagination">
    <!-- 上一页按钮 -->
    <div
      :class="[
        'page-button',
        currentPage > 1 ? 'enable' : ''
      ]"
      :tabindex="currentPage > 1 ? 1 : undefined"
      @click="goToPage(currentPage - 1)"
    >
      &lt;
    </div>

    <!-- 页码按钮 -->
    <div
      v-for="page in visiblePages"
      :key="page"
      class="page-button enable"
      :class="{ active: page === currentPage }"
      :tabindex="page === currentPage ? undefined : 1"
      @click="goToPage(page)"
    >
      {{ page }}
    </div>

    <!-- 下一页按钮 -->
    <div
      :class="[
        'page-button',
        currentPage < totalPages ? 'enable' : ''
      ]"
      :tabindex="currentPage < totalPages ? 1 : undefined"
      @click="goToPage(currentPage + 1)"
    >
      &gt;
    </div>
  </div>
</template>

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

const props = defineProps({
  /**
   * 当前页码
   */
  currentPage: {
    type: Number,
    required: true,
  },
  /**
   * 总页数
   */
  totalPages: {
    type: Number,
    required: true,
  },
});

const emit = defineEmits(["update:currentPage"]);

// 计算显示的页码范围
const visiblePages = computed(() => {
  const pages = [];
  const maxPagesToShow = 10; // 最多显示 10 个页码
  const halfMax = Math.floor(maxPagesToShow / 2);

  // 计算起始页码
  let startPage = Math.max(1, props.currentPage - halfMax);
  let endPage = startPage + maxPagesToShow - 1;

  // 如果超出总页数，调整起始页码
  if (endPage > props.totalPages) {
    endPage = props.totalPages;
    startPage = Math.max(1, endPage - maxPagesToShow + 1);
  }

  for (let i = startPage; i <= endPage; i++) {
    pages.push(i);
  }

  return pages;
});

// 跳转到指定页码
const goToPage = (page: number) => {
  if (page >= 1 && page <= props.totalPages) {
    emit("update:currentPage", page);
  }
};
</script>

<style lang="scss" scoped>
.pagination {
  display: flex;
  justify-content: center;
  gap: 5px;
  margin-top: 15px;
}
.page-button {
  width: 1.5rem;
  height: 1.5rem;
  font-size: 0.9rem;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: var(--color-light-bg);
  border: 2px solid var(--color-primary);
  border-radius: 4px;
  color: var(--color-text);
  cursor: pointer;
  opacity: 0.4;

  &:focus {
    outline: 2px solid var(--color-primary2);
    transform: scale(1.05);
  }
  &.enable {
    opacity: 1;
  }
}
.page-button.active {
  background-color: var(--color-primary2);
  color: var(--color-text-light);
  border-color: var(--color-primary2);
}
</style>