<script setup>
// 常用事件：
//    change - change({page, offset, rows, count, total})

// 常用属性：
//   total <number> 总条数
//   rows <number> 每页行数
//   page <number> 当前所在页码
//   offset <number> 当前显示的条目位置，从0开始

import Paginator from "primevue/paginator";
import T from "./T.js"
import {onMounted, ref} from "vue";

const props = defineProps({
	total: 0,
	rows: 0,
	offset: 0,
	page: 0
})

let rows = props.rows
if (T.isNull(rows) || rows < 1) {
	rows = 10
}

let pageOffset = ref(props.offset)
if (props.page > 0) {
	pageOffset.value = (props.page - 1) * rows
} else {
	pageOffset.value = 0
}

const emits = defineEmits(["change"])

const changePage = e => {
	emits("change", {
		page: e.page + 1,
		offset: e.first,
		rows: e.rows,
		count: e.pageCount,
		total: props.total
	})
}

const changePageSize = pageSize => {
	emits("change", {
		page: 1,
		offset: 0,
		rows: pageSize,
		count: Math.ceil(props.total / pageSize),
		total: props.total
	})
}

onMounted(() => {
	if (props.total > 0) {
		changePage({
			page: T.isNull(props.page) ? 0 : props.page - 1,
			first: pageOffset.value,
			rows: rows,
			pageCount: Math.ceil(props.total / rows)
		})
	}
})

</script>

<template>
	<Paginator :total-records="total"
			   :rows="rows"
			   :pageLinkSize="5"
			   :first="pageOffset"
			   :alwaysShow="true"
			   :rowsPerPageOptions="[5, 10, 20, 30, 40, 50, 100]" @page="changePage" @update:rows="changePageSize">
	</Paginator>
</template>

<style scoped>

</style>