<template>
	<div class="page_container !bg-white">
		<MomentsHeader />
		<div class="overflow-hidden overflow-y-auto flex-1" ref="el">
			<div class="relative" @click="toDesignatedMoments">
				<img class="mt-[-46px]" :src="background" alt="" />
				<Avatar class="!absolute bottom-[-18px] right-4" :size="48" :src="userStore.selfInfo.faceURL"
					:desc="userStore.selfInfo.nickname" />
				<div class="!absolute right-[74px] bottom-[-15px] flex h-[48px] items-center justify-center text-white">
					{{ userStore.selfInfo.nickname }}
				</div>
			</div>
			<div v-if="unread" class="mt-4 flex items-center justify-center"
				@click="router.push('/interactiveMessage')">
				<span class="rounded-md bg-[#4C4C4E] bg-opacity-30 px-4 py-1.5 text-sm text-white">{{
            $t('momentsTips.newMsg', {
              total: unread,
            })
          }}</span>
			</div>
			<MomentsItem v-for="item in source.workMoments" :source="item" :item="item" @startComment="startComment"
				:key="item.workMomentID" @tryDeleteMoment="tryDeleteMoment" />
		</div>
		<div v-if="commentState.show" class="flex items-center justify-center bg-[#F0F2F6] px-4 py-2">
			<van-field class="flex-1 !bg-white px-2" ref="inputRef" v-model="commentState.content" />
			<!-- <img @click="clickEmojiBtn" class="ml-3 h-[26px] min-w-[26px]" :src="emoji" alt="" /> -->
			<!-- <img class=" h-[26px] min-w-[26px]" :src="send" alt="send" /> -->
			<div class="send ml-2" @click="tryComment">
				发送
			</div>
		</div>
		<ChatFooterEmoji v-show="showEmojiBar" @closeEmojiBar="closeEmojiBar" @emojiClick="emojiClick" />
	</div>
</template>

<script setup lang="ts" name="moments">
	import background from '@/assets/images/moments/background.png'
	import emoji from '@/assets/images/chatFooter/emoji.png'
	import MomentsHeader from './components/MomentsHeader.vue'
	import MomentsItem from './components/MomentsItem.vue'
	import {
		createComment,
		deleteMoment,
		fetchUserMoments,
		getMomentsUnreadCount,
	} from '@/api/moments'
	import { onClickOutside, useInfiniteScroll } from '@vueuse/core'
	import { Comments, WorkMoments } from '@/types/moment'
	import { closeToast, showToast, showLoadingToast } from 'vant'
	import { IMSDK } from '@/utils/imCommon'
	import { CbEvents } from 'open-im-sdk-wasm'
	import type { WSEvent } from 'open-im-sdk-wasm/lib/types/entity'
	import useUserStore from '@/store/modules/user'
	import ChatFooterEmoji from './ChatFooterEmoji.vue'

	type Source = {
		workMoments : WorkMoments[]
		loading : boolean
		hasMore : boolean
		current : number
	}
	const toDesignatedMoments = () => {
		router.push({
			path: '/designatedMoments',
			state: {
				userID: userStore.selfInfo.userID,
				nickname: userStore.selfInfo.nickname,
				faceURL: userStore.selfInfo.faceURL,
			},
		})
	}
	onMounted(() => {
		fetchData()
		fetchUnread()
		IMSDK.on(CbEvents.OnRecvCustomBusinessMessage, customMessageHandler)
	})

	onBeforeMount(() => {
		IMSDK.off(CbEvents.OnRecvCustomBusinessMessage, customMessageHandler)
	})

	const el = ref<HTMLElement | null>(null)
	const inputRef = ref()
	const unread = ref(0)
	const router = useRouter()
	// action bar
	const showActionBar = ref(false)
	const showEmojiBar = ref(false)
	const emojiClick = (str : string) => {
		const parser = new DOMParser()
		const doc = parser.parseFromString(str, 'text/html')
		const nodes = Array.from(doc.body.childNodes)
		inputRef.value.insertAtCursor(nodes)
	}

	const closeActionBar = () => {
		showActionBar.value = false
	}
	const closeEmojiBar = () => {
		showEmojiBar.value = false
	}
	const clickAddBtn = () => {
		if (showEmojiBar.value) {
			showEmojiBar.value = false
		}
		showActionBar.value = !showActionBar.value
	}
	const clickEmojiBtn = () => {
		if (showActionBar.value) {
			showActionBar.value = false
		}
		showEmojiBar.value = !showEmojiBar.value
	}
	const commentState = reactive({
		show: false,
		content: '',
		workMomentID: '',
		comment: {
			userID: '',
			nickname: '',
		},
	})
	const source = reactive<Source>({
		workMoments: [],
		loading: false,
		hasMore: true,
		current: 1,
	})

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

	onClickOutside(
		inputRef,
		() => {
			commentState.show = false
		},
		{
			ignore: ['.van-overlay', '.van-action-sheet__content'],
		},
	)

	const customMessageHandler = ({
		data: { key, data },
	} : WSEvent<{ key : string; data : string }>) => {
		console.log('customMessageHandler', data)
		if (key.includes('wm_')) {
			fetchUnread()
			const moments = JSON.parse(data).body as WorkMoments
			const idx = source.workMoments.findIndex(
				(item) => item.workMomentID === moments.workMomentID,
			)
			source.workMoments[idx] = { ...source.workMoments[idx], ...moments }
		}
	}

	const fetchUnread = async () => {
		const { data } = await getMomentsUnreadCount()
		unread.value = data.total
	}

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

	const tryComment = async () => {
		if (commentState.content && !/^[\s\n]*$/.test(commentState.content)) {
			await createComment({
				workMomentID: commentState.workMomentID,
				content: commentState.content,
				replyUserID: commentState.comment.userID,
			})
		} else {
			showToast('内容不能为空');
		}

	}

	const startComment = (workMomentID : string, comment : Comments) => {
		commentState.content = ''
		commentState.show = true
		commentState.workMomentID = workMomentID
		commentState.comment = comment || { nickname: '', userID: '' }
		nextTick(() => {
			inputRef.value.focus()
		})
	}

	const tryDeleteMoment = async (workMomentID : string) => {
		await deleteMoment(workMomentID)
		source.workMoments = source.workMoments.filter(
			(item) => item.workMomentID !== workMomentID,
		)
	}
</script>
<style lang="scss" scoped>
	.van-cell {
		background: white !important;
		padding: 4px !important;
	}

	:deep(.van-button__content) {
		width: max-content;
	}

	.send {
		width: 3.64rem;
		height: 1.95rem;
		display: flex;
		align-items: center;
		justify-content: center;
		font-size: 0.8rem;
		color: #fff;
		background-color: #07C160;
		border-radius: 0.2rem;
	}
</style>