<template>
	<template v-if="detail">
		<a-page-header>
			<template #title>
				<a-button @click="back" type="link">
					<ArrowLeftOutlined />返回
				</a-button>
			</template>
			<a-card style="width: 100%">
				<a-card-meta :title="detail.title" :description="'发布时间：'+detail.created_at">
				</a-card-meta>
				<a-divider />
				<div v-html="detail.content"></div>
			</a-card>
		</a-page-header>
	</template>
	<template v-else>
		<a-list item-layout="horizontal" :data-source="articleList">
			<template #renderItem="{ item }">
				<a-list-item @click="toDetail(item)">
					<a-list-item-meta :title="item.title" :description="'发布时间：'+item.created_at">
					</a-list-item-meta>
				</a-list-item>
			</template>
		</a-list>
		<a-flex align="center" justify="center">
			<a-pagination  hideOnSinglePage v-model:current="current"
				:total="total" @change="pageChange" />
		</a-flex>
	</template>
</template>

<script setup lang="ts">
	import { ref, computed, onMounted, defineProps, watch, onBeforeUnmount } from 'vue';
	import { GetArticleList } from '@/apis/models';
	import { ArrowLeftOutlined } from '@ant-design/icons-vue';
	let props = defineProps(['key_id']);
	let articleList = ref<object[]>([])
	let detail = ref<Object>(null)
	let key = ref<Number>(3)
	let current = ref<Number>(1)
	let total = ref<Number>(0)
	
	onMounted(() => {
		if(sessionStorage.getItem('article_data')) {
			detail.value = JSON.parse(sessionStorage.getItem('article_data')) 
			GetArticleList({page: current.value, hot: 2}).then(res => {
				articleList.value = res.data.articles;
				total.value = res.data.total;
			})
		}
	})
	
	onBeforeUnmount(() => {
		sessionStorage.removeItem('article_data')
	})
	
	const pageChange = (page) => {
		current.value = page
		getArticleList(key.value)
	}

	const getArticleList = (val) => {
		if(val == 1) {
			GetArticleList({page: current.value, hot: 2}).then(res => {
				articleList.value = res.data.articles;
				total.value = res.data.total;
			})
		} else {
			GetArticleList({section_id: val, page: current.value}).then(res => {
				articleList.value = res.data.articles;
				total.value = res.data.total;
			})
		}
	}

	const toDetail = (data) => {
		detail.value = data
	}
	
	const back = (data) => {
		detail.value = null
	}
	
	
	watch(() => props.key_id, (newVal) => {
		if(sessionStorage.getItem('article_data')) {
			key.value = 1
		} else  {
			key.value = newVal;
			detail.value = null
		}
		getArticleList(key.value)
	}, { immediate: true })
	
</script>

<style>
</style>