
<template>
  <div class="custom-pagination">
    <a-pagination
      :current="pageNum"
      :total="totalCount"
      :page-size="itemsPerPage"
      :show-size-changer="useLimit"
      :page-size-options="itemsPerPageArray.map(String)"
      @change="handlePageChange"
      @showSizeChange="changePageLeng"
    />
  </div>
</template>

<script>
export default {
	props: {
		useLimit: {
			type: Boolean,
			default: true,
		},
		totalCount: {
			type: Number,
			default: 0,
		},
		pageNum: {
			type: Number,
			default: 0,
		},
		limit: {
			type: Number,
			default: 0,
		},
		itemsPerPageArray: {
			type: Array,
			default: () => [10, 20, 50],
		},
	},
	data() {
		return {
			moveToPage: '',
		};
	},
	computed: {
		page: function() {
			return this.numberOfPages + '-' + this.lastPage;
		},
		lastPage: function() {
			//grid data가 없을 경우 1 리턴
			if (this.totalCount == 0) return 1;

			let pageLength = Math.floor(this.totalCount / this.itemsPerPage);
			if (this.totalCount % this.itemsPerPage > 0) {
				pageLength++;
			}
			return pageLength;
		},
		itemsPerPage: function() {
			return this.limit;
		},
		numberOfPages: function() {
			return Number(this.pageNum);
		},
		plusPage: function() {
			return Number(this.pageNum) + 1;
		},
		minusPage: function() {
			return Number(this.pageNum) - 1;
		},
	},
	watch: {
		totalCount: function(newData) {
			return (this.moveToPage = newData > 0 ? this.moveToPage : '');
		},
		moveToPage: function() {
			return (this.moveToPage = this.moveToPage.replaceAll(/[^0-9]/g, ''));
		},
	},
	methods: {	
		handlePageChange(newPage) {
		// Emit an event to the parent to load data for the selected page
		this.$emit('loadData', newPage, this.itemsPerPage);
		},
		changePageLeng: function(current, newLimit) {
			//부모 컴포넌트에서 loadData(데이터 조회) 구현
			//this.$emit('loadData', this.pageNum, limit);
			// limit 변경 시 1 페이지로 초기화
			this.$emit('loadData', 1, newLimit);
		},
	},
};
</script>
