<template>
	<div class="tools-container" v-loading.fullscreen.lock="fullscreenLoading">
		<div class="input">
			<SearchInput v-model="searchText" placeholder="Please enter the key words" @search="handleTextSearch" />
		</div>
		<div class="list">
			<ListCardItem v-for="it in articleList" :key="it.id" :item="it" type="tool" />
		</div>
		<div class="pagination-wrapper">
			<Pagination :current-page="currentPage" :total-pages="totalPages" @page-change="handlePageChange" />
		</div>
	</div>
</template>

<script>
	import ListCardItem from "@/pages/AIHub/components/ListCardItem.vue";

	export default {
		components: {
			ListCardItem,
		},
		data() {
			return {
				currentPage: 1,
				totalPages: 1,
				pageSize: 10,
				articleList: [],
				searchText: '',
				total: 0,
				fullscreenLoading: false,
			}
		},
		watch: {
			total() {
				this.calculateTotalPages();
			},
			pageSize() {
				this.calculateTotalPages();
			}
		},
		methods: {
			// 模糊搜索
			async handleTextSearch() {
				await this.getArticleListData(this.currentPage, this.pageSize, this.searchText);
			},
			calculateTotalPages() {
				// 否则向上取整计算总页数
				this.totalPages = this.total === 0 ? 1 : Math.ceil(this.total / this.pageSize);
			},
			handlePageChange(pageNumber) {
				this.currentPage = pageNumber;
				this.getArticleListData(pageNumber, this.pageSize);
			},
			// 获取文章列表
			async getArticleListData(page = 1, limit = 10, searchText) {
				const params = {page, limit, articleType: 'tool', title: searchText};
				if (!searchText) {
					delete params.title;
				}
				this.fullscreenLoading = true;
				const {data: res} = await this.$api.article.getArticleList(params);
				const {code, data} = res;
				if (code === 0 && data.list) {
					this.articleList = data.list;
					this.total = data.total;
					this.calculateTotalPages();
				}
				this.fullscreenLoading = false;
			},
		},
		mounted() {
			this.getArticleListData(this.currentPage, this.pageSize);
		}
	}
</script>

<style lang="scss" scoped>
.input {
	display: flex;
	justify-content: flex-end;
	.input-container {
		margin-top: 100px;
		margin-bottom: 60px;
	}
}
.list {
	display: flex;
	flex-direction: column;
	gap: 30px;
	margin-bottom: 60px;
}
</style>
