<template>
  <div class="custom-pagination">
    <el-pagination
      size="medium"
      background
      :layout="pageLayout"
      v-model:current-page="localPageNum"
      hide-on-single-page="true"
      @current-change="handlePageChange"
      :page-size="pageSize"
      :page-count="totalPages"
      class="mt-4"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue';

// 定义组件的属性
const props = defineProps<{
  pageNum: number;
  pageSize: number;
  totalPages: number;
}>();

// 定义组件的事件
const emit = defineEmits<{
  (e: 'update:pageNum', value: number): void;
  (e: 'pageChange', value: number): void;
}>();

// 响应式状态
const localPageNum = ref(props.pageNum);
const localTotalPages = ref(props.totalPages);

// 计算属性：根据当前页码动态生成分页布局
const pageLayout = computed(() => {
  if (localPageNum.value === 1) {
    // 第一页只显示页码和下一页按钮
    return 'pager, next';
  } else if (localPageNum.value === localTotalPages.value) {
    // 最后一页只显示上一页按钮和页码
    return 'prev, pager';
  } else {
    // 中间页显示完整的上一页、页码、下一页
    return 'prev, pager, next';
  }
});

// 监听props变化，更新本地状态
watch(
  () => props.pageNum,
  (newVal) => {
    localPageNum.value = newVal;
  }
);

watch(
  () => props.totalPages,
  (newVal) => {
    localTotalPages.value = newVal;
  }
);

// 处理页码变化
const handlePageChange = (newPage: number) => {
  // 更新本地页码
  localPageNum.value = newPage;
  // 触发update:pageNum事件，实现双向绑定
  emit('update:pageNum', newPage);
  // 触发pageChange事件，通知父组件页码变化
  emit('pageChange', newPage);
};
</script>

<style scoped>
.custom-pagination {
  display: flex;
  justify-content: center;
  margin: 1rem 0;
}

.mt-4 {
  margin-top: 1rem;
}
</style>
