<template>
  <div class="newslist flex flex-col items-center">
		<Spin class="w-full h-full" :spinning="isLoading">
			<div class="px-5 mb-6">
				<router-link tag="div" :to="{path: '/newsDetails', query: { id: item.id, lang: $route.query.lang }}" v-for="item in newsLists" :key="item.id" class="overflow-hidden rounded-sm my-6">
					<m-news-item :item="item"></m-news-item>
				</router-link>
				<div v-show="newsLists.length < allLists.length" class="load-more text-xs text-footer-color text-center" @click="handleChange()">加载更多</div>
			</div>
		</Spin>
	</div>
</template>

<script lang="ts">
import Vue from 'vue'
import { Spin } from "ant-design-vue"
import { getNews } from '@/service/api'
import MNewsItem from '@/components/mobile/m-newsItem.vue'
export default Vue.extend({
	name: 'newsLists',
	data() {
		return {
			total: 0,
			currentPage: 1,
			pageSize: 7,
			allLists: [],
			newsLists: [],
			isLoading: false
		}
	},
	components: {
		Spin,
		MNewsItem
	},
	methods: {
		handleChange() {
			this.currentPage++
			this.getLists()
		},
		getLists() {
			const copy = JSON.parse(JSON.stringify(this.allLists))
			this.newsLists = copy.slice(0, Math.min((this.currentPage) * this.pageSize, this.total))
		},
		getNewsList() {
			const language = window.sessionStorage.getItem('language') || 'zh-CN'
			this.isLoading = true
			getNews(language).then(res => {
				this.allLists = res.rows
				this.allLists.forEach((item: {cover: string}) => {
					item.cover = item.cover.replace(/public.33.cn/g, 'public.yuan.org')
				})
				this.total = this.allLists.length
				this.getLists()
				this.isLoading = false
			}).catch(e => {
				this.isLoading = false
				throw Error(e)
			})
		}
	},
	created() {
		this.getNewsList()
	},
	watch: {
		$route(n, o) {
			// this.currentPage = 1
			if (n.query.lang !== o.query.lang) {
				this.currentPage = 1
			}
			this.getNewsList()
		}
	}
})
</script>

<style scoped>
	.newslist {
		padding-top: 44px;
		min-height: calc(100vh - 156px);
	}
	.news_items:nth-of-type(odd) {
		margin-right: 16%;
	}
	.m-news-cover {
		width: 114px;
		height: 75px;
	}
	.load-more {
		height: 40px;
		line-height: 40px;
		background: #F5F5F7;
	}
</style>