<script setup>
import TPaginator from "@/components/ui/TPaginator.vue";
import {inject, ref, watch} from "vue";

const Tea = inject("$Tea")
const props = defineProps(["data"])
const popupState = inject("$popupState", null)

const key = ref()

watch(() => props.data, (v) => {
	key.value = v.current + "_" + v.size
})

const onChange = (page) => {
	let currentPage = page.page
	if (props.data) {
		if (currentPage == props.data.current && page.rows == props.data.size) {
			return
		}
	}

	props.data.current = currentPage

	let url = Tea.currentURL()
	if (url.indexOf("?") < 0) {
		url = url + "?page=" + currentPage + "&pageSize=" + page.rows
	} else if (url.indexOf("?page=") > 0) {
		url = url.replace(/\?page=(\d+)?/g, "?page=" + currentPage)
	} else if (url.indexOf("&page=") > 0) {
		url = url.replace(/&page=(\d+)?/g, "&page=" + currentPage)
	} else {
		url += "&page=" + currentPage
	}

	if (url.indexOf("?pageSize=") > 0) {
		url = url.replace(/\?pageSize=(\d+)?/g, "?pageSize=" + page.rows)
	} else if (url.indexOf("&pageSize=") > 0) {
		url = url.replace(/&pageSize=(\d+)?/g, "&pageSize=" + page.rows)
	} else {
		url += "&pageSize=" + page.rows
	}

	if (popupState) {
		Tea.reloadViewData(url, {
			onDone: () => {
				if (popupState != null) {
					const dialogs = document.querySelectorAll(".p-dialog-content")
					if (dialogs.length > 0) {
						dialogs[dialogs.length - 1].scrollTop = 0
					}
				}
			}
		})
	} else {
		window.location.href = url
	}
}

</script>

<template>
	<TPaginator :total="data.total" :rows="data.size" :page="data.current" :offset="data.offset"
				@change="onChange" :key="key" :alwaysShow="false"></TPaginator>
</template>

<style scoped>

</style>