<template>
	<div class="pagination-container">
		<el-pagination
			:background="background"
			v-model:current-page="currentPage"
			v-model:page-size="pageSize"
			:layout="layout"
			:total="total"
			:small="small"
			:page-sizes="pageSizes"
			@size-change="handleSizeChange"
			@current-change="handleCurrentChange"
			:pager-count="pagerCount"
			:disabled="disabled"
		/>
	</div>
</template>

<script lang="ts" name="pagination" setup>
import { computed, onMounted, ref } from 'vue';
// 定义父组件传过来的值
const props = defineProps({
	total: {
		required: true,
		type: Number,
	},
	currentPage: {
		type: Number,
		default: 1,
	},
	pageSize: {
		type: Number,
		default: 10,
	},
	pageSizes: {
		type: Array,
		default() {
			return [10, 20, 50, 100, 200];
		},
	},
	pagerCount: {
		type: Number,
		default: 5,
	},
	layout: {
		type: String,
		default: 'total, sizes, prev, pager, next, jumper',
	},
	background: {
		type: Boolean,
		default: false,
	},
	autoScroll: {
		type: Boolean,
		default: true,
	},
	disabled:{
		type: Boolean,
		default: false,
	}
});

// 定义子组件向父组件传值/事件
const emit = defineEmits(['update:current-page', 'update:page-size', 'pagination']);

// 定义变量内容
const small = ref(false);
const currentPage = computed({
	get() {
		return props.currentPage;
	},
	set(val) {
		emit('update:current-page', val);
	},
});
const pageSize = computed({
	get() {
		return props.pageSize;
	},
	set(val) {
		emit('update:page-size', val);
	},
});
const handleSizeChange = (val: any) => {
	pageSize.value = val;
	/**
	 * 场景：API返回总数为25条，按照10条每页，一共有3页。选了2的页数之后，然后把size选择成30条，
	 * 这个时候，分页就会同时触发size选择函数以及current选择函数。{page: 2, size: 30}，{page: 1, size: 30}请求两次，会导致列表会有暂无数据的情况
	 * 解决办法：如果当前页大于最大页数，就把当前页设置成最大页数
	 */
	// 获取最大页数
	let pageMax = Math.ceil(props.total / val);
	if (currentPage.value > pageMax) {
		currentPage.value = pageMax;
	}
	emit('pagination', { page: currentPage.value, limit: val });
};
const handleCurrentChange = (val: any) => {
	currentPage.value = val;
	emit('pagination', { page: val, limit: pageSize.value });
};
onMounted(() => {
	// 监听布局大小 改变分页的大小
	// let themeConfig = Local.get('themeConfig');
	// small.value = themeConfig.globalComponentSize == 'small';
});
</script>
<style scoped>
.pagination-container {
	display: flex;
	justify-content: flex-end;
	align-items: center;
}
</style>
