<template>
	<div class="page_container !bg-white">
		<NavBar :title="$t('momentsTips.logs')">
			<div @click="tryClear">{{ $t('buttons.clear') }}</div>
		</NavBar>
		<div class="overflow-y-auto" ref="el">
			<IMessageItem v-for="(item, i) in source.workMoments" :source="item" :key="item.workMomentID"
				:border="i !== source.workMoments.length - 1" />
			<div class="noMoreLogs" v-if="source.workMoments.length<=0">
				<img src="../../../assets/images/zwxgxx.png" alt="" />
				{{ $t('momentsTips.noMoreLogs2') }}~
			</div>
		</div>
	</div>
</template>

<script setup lang="ts">
	import NavBar from '@/components/NavBar/index.vue'
	import IMessageItem from './IMessageItem.vue'
	import { MomentsClearType, clearUnreadMoments, getMomentLogs } from '@/api/moments'
	import { useInfiniteScroll } from '@vueuse/core'
	import { WorkMoments } from '@/types/moment'
	import { closeToast, showLoadingToast } from 'vant'

	type Source = {
		workMoments : WorkMoments[]
		loading : boolean
		hasMore : boolean
		current : number
	}
	const el = ref<HTMLElement | null>(null)
	const source = reactive<Source>({
		workMoments: [],
		loading: false,
		hasMore: true,
		current: 1,
	})

	onMounted(() => {
		fetchData()
		clearUnread()
	})

	const { t } = useI18n()
	useInfiniteScroll(
		el,
		() => {
			fetchData()
		},
		{ distance: 50 },
	)

	const clearUnread = async () => {
		await clearUnreadMoments(MomentsClearType.Count)
	}

	const fetchData = async () => {
		if (!source.hasMore || source.loading) return
		source.loading = true
		showLoadingToast({
			message: t('loading'),
			forbidClick: true,
			duration: 0,
		})
		const { data } = await getMomentLogs(source.current)
		source.workMoments = [...source.workMoments, ...(data.workMoments ?? [])]
		source.current++
		source.hasMore = data.workMoments?.length === 20
		source.loading = false
		closeToast()
	}

	const tryClear = async () => {
		await clearUnreadMoments(MomentsClearType.List)
		source.workMoments = []
	}
</script>
<style lang="scss">
	.noMoreLogs {
		display: flex;
		flex-direction: column;
		align-items: center;
		font-size: 1.04rem;
		color: #989FB0;
		margin-top: 9.75rem;

		img {
			width: 9.03rem;
			height: 9.03rem;
			margin-bottom: 0.97rem;
		}
	}
</style>