<template>
  <div class="flex items-center justify-center space-x-2 my-4">
    <!-- 上一页按钮 -->
    <button 
      @click="handlePageChange(currentPage - 1)"
      :disabled="currentPage === 1"
      :class="[
        'px-3 py-1 rounded-md',
        currentPage === 1 
          ? 'bg-gray-100 text-gray-400 cursor-not-allowed'
          : 'bg-white text-gray-700 hover:bg-gray-50'
      ]"
    >
      上一页
    </button>

    <!-- 页码按钮 -->
    <template v-for="page in displayedPages" :key="page">
      <!-- 省略号 -->
      <span v-if="page === '...'" class="px-3 py-1">...</span>
      
      <!-- 页码按钮 -->
      <button
        v-else
        @click="handlePageChange(page)"
        :class="[
          'px-3 py-1 rounded-md',
          currentPage === page
            ? 'bg-blue-500 text-white'
            : 'bg-white text-gray-700 hover:bg-gray-50'
        ]"
      >
        {{ page }}
      </button>
    </template>

    <!-- 下一页按钮 -->
    <button 
      @click="handlePageChange(currentPage + 1)"
      :disabled="currentPage === totalPages"
      :class="[
        'px-3 py-1 rounded-md',
        currentPage === totalPages
          ? 'bg-gray-100 text-gray-400 cursor-not-allowed'
          : 'bg-white text-gray-700 hover:bg-gray-50'
      ]"
    >
      下一页
    </button>
  </div>
</template>

<script>
import { computed } from 'vue'

export default {
  name: 'Pagination',
  props: {
    currentPage: {
      type: Number,
      required: true
    },
    totalPages: {
      type: Number,
      required: true
    },
    maxDisplayPages: {
      type: Number,
      default: 7
    }
  },

  emits: ['page-change'],

  setup(props, { emit }) {
    const displayedPages = computed(() => {
      const { currentPage, totalPages, maxDisplayPages } = props
      
      if (totalPages <= maxDisplayPages) {
        return Array.from({ length: totalPages }, (_, i) => i + 1)
      }

      const pages = []
      const sidePages = Math.floor((maxDisplayPages - 3) / 2) // 两边显示的页数
      
      // 添加开始的页码
      if (currentPage <= sidePages + 3) {
        for (let i = 1; i <= sidePages + 3; i++) {
          pages.push(i)
        }
        pages.push('...')
        pages.push(totalPages)
      }
      // 添加结束的页码
      else if (currentPage >= totalPages - (sidePages + 2)) {
        pages.push(1)
        pages.push('...')
        for (let i = totalPages - (sidePages + 2); i <= totalPages; i++) {
          pages.push(i)
        }
      }
      // 添加中间的页码
      else {
        pages.push(1)
        pages.push('...')
        for (let i = currentPage - sidePages; i <= currentPage + sidePages; i++) {
          pages.push(i)
        }
        pages.push('...')
        pages.push(totalPages)
      }

      return pages
    })

    const handlePageChange = (page) => {
      if (page >= 1 && page <= props.totalPages && page !== props.currentPage) {
        emit('page-change', page)
      }
    }

    return {
      displayedPages,
      handlePageChange
    }
  }
}
</script>
