<template>
  <div class="demo-pagination-block" style="text-align: center; margin-top: 20px;">
    <el-pagination
      v-model:current-page="currentPage"
      v-model:page-size="pageSize"
      :page-sizes="[10, 20, 30, 40]"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
  </div>
</template>

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

// 定义 props
interface Props {
  total: number;
  currentPage?: number;
  pageSize?: number;
}

const props = defineProps<Props>();

// 定义 emits
const emit = defineEmits<{
  (e: 'update:currentPage', value: number): void;
  (e: 'update:pageSize', value: number): void;
  (e: 'size-change', value: number): void;
  (e: 'current-change', value: number): void;
}>();

// 初始化 currentPage 和 pageSize
const currentPage = ref<number>(props.currentPage ?? 1);
const pageSize = ref<number>(props.pageSize ?? 10);

// 监听 props.currentPage 变化
watch(() => props.currentPage, (newVal) => {
  if (newVal !== undefined && newVal !== currentPage.value) {
    currentPage.value = newVal;
  }
});

// 监听 props.pageSize 变化
watch(() => props.pageSize, (newVal) => {
  if (newVal !== undefined && newVal !== pageSize.value) {
    pageSize.value = newVal;
  }
});

// 监听 currentPage 变化并触发事件
watch(currentPage, (newVal) => {
  emit('update:currentPage', newVal);
  emit('current-change', newVal);
});

// 监听 pageSize 变化并触发事件
watch(pageSize, (newVal) => {
  emit('update:pageSize', newVal);
  emit('size-change', newVal);
});

// 处理页面大小变化
const handleSizeChange = (newSize: number) => {
  pageSize.value = newSize;
};

// 处理当前页变化
const handleCurrentChange = (newPage: number) => {
  currentPage.value = newPage;
};
</script>