<template>
	<main-header />
	<div class="view" ref="viewRef" :style="viewStyle"><RouteCache /></div>
	<login-dialog />
	<div id="loading" v-if="loading" v-loading="true"></div>
	<shopping-drawer />
</template>

<script setup lang="ts">
	import { computed, onMounted, ref, onBeforeUnmount, watch } from 'vue'
	import RouteCache from '@/components/RouteCache.vue'
	import MainHeader from '@/views/main-header.vue'
	import LoginDialog from '@/views/login/login-dialog.vue'
	import { useGlobalStore, useUserInfoStore } from '@/stores'
	import ShoppingDrawer from '@/views/shopping-drawer.vue'
	import { wsManager } from '@/utils/websocket'
	
	const globalStore = useGlobalStore()
	const userInfoStore = useUserInfoStore()
	const loading = computed(() => globalStore.state.loading)
	globalStore.setLoading(false)
	const viewRef = ref()
	const viewStyle = ref({
		'--app-view-width': '',
		'--app-view-height': ''
	})
	const observer = new ResizeObserver((entries) => {
		const { width, height } = entries[0].contentRect
		viewStyle.value['--app-view-width'] = width + 'px'
		viewStyle.value['--app-view-height'] = height + 'px'
	})
	
	// 监听 token 变化，建立或关闭 WebSocket 连接
	watch(
		() => userInfoStore.state.token,
		(newToken, oldToken) => {
			if (newToken && newToken !== oldToken) {
				// 用户登录，建立 WebSocket 连接
				console.log('用户已登录，建立 WebSocket 连接')
				wsManager.connect(newToken)
			} else if (!newToken && oldToken) {
				// 用户退出登录，关闭 WebSocket 连接
				console.log('用户已退出，关闭 WebSocket 连接')
				wsManager.close()
			}
		},
		{ immediate: true }
	)
	
	onMounted(() => {
		observer.observe(viewRef.value)
		
		// 如果已经有 token，立即建立连接
		const token = userInfoStore.state.token
		if (token) {
			console.log('应用启动时检测到 token，建立 WebSocket 连接')
			wsManager.connect(token)
		}
	})
	
	onBeforeUnmount(() => {
		observer.disconnect()
		// 组件卸载时关闭 WebSocket 连接
		wsManager.close()
	})
	
	window['onClickPrivacy'] = () => {
		const e = window.event || event
		e.stopPropagation()
		e.preventDefault()
		console.log('点击了隐私政策')
	}
</script>

<style lang="less">
	#app {
		font-size: 1.6rem;
		display: flex;
		flex-direction: column;
	}
	#loading {
		position: fixed;
		z-index: 999999999;
		top: 0;
		left: 0;
		width: 100%;
		height: 100%;
		--el-mask-color: rgba(0, 0, 0, 0.3);
		--el-color-primary: #007bff;
		--el-loading-spinner-size: 9rem;
	}
</style>
<style lang="less" scoped>
	* {
		--header-height: 8rem;
		--footer-height: 7rem;
	}
	.view {
		flex: 1;
		overflow: hidden;
	}
</style>
