<script setup>
import { onMounted, onUnmounted, computed, watch, nextTick } from 'vue'
import { storeToRefs } from 'pinia'
import { useI18nStore } from './stores/modules/i18n'
import { useLayoutStore } from './stores/modules/layout'
import { useUserStore } from './stores/modules/user'
import { useMessageStore } from './stores/modules/message'
import { useWebSocket } from './hooks/useWebSocket'
import { theme } from 'ant-design-vue'
import i18n from './i18n'
import zhCN from 'ant-design-vue/es/locale/zh_CN'
import enUS from 'ant-design-vue/es/locale/en_US'
import dayjs from 'dayjs'
import 'dayjs/locale/zh-cn'
import 'dayjs/locale/en'

// 定义组件名称
defineOptions({
	name: 'App',
})

// i18n store
const i18nStore = useI18nStore()

// layout store
const layoutStore = useLayoutStore()

// user store
const userStore = useUserStore()

// message store
const messageStore = useMessageStore()

// WebSocket
const { initWebSocket, closeWebSocket } = useWebSocket()

// 解构 themeColor 以确保响应式
const { themeColor } = storeToRefs(layoutStore)

// Ant Design Vue 语言配置
const antLocale = computed(() => {
	return i18nStore.currentLocale === 'zh-CN' ? zhCN : enUS
})

// 获取弹出容器
const getPopupContainer = () => {
	return document.body
}

// Ant Design Vue 主题配置
const antdTheme = computed(() => {
	return {
		algorithm: theme.defaultAlgorithm,
		token: {
			colorPrimary: themeColor.value || '#1890ff',
			borderRadius: 6,
			fontSize: 14,
		},
		components: {
			Layout: {
				headerBg: '#fff',
				siderBg: '#001529',
			},
			Menu: {
				darkItemBg: '#001529',
				darkItemSelectedBg: themeColor.value || '#1890ff',
				darkItemHoverBg: '#002140',
			},
		},
	}
})

// 监听主题颜色变化，更新 CSS 变量
watch(
	themeColor,
	(newColor) => {
		if (newColor) {
			document.documentElement.style.setProperty('--primary-color', newColor)
		}
	},
	{ immediate: true },
)

// 监听用户信息变化，当用户信息完整时初始化 WebSocket
watch(
	() => [userStore.token, userStore.userInfo],
	() => {
		if (userStore.isUserInfoComplete()) {
			initWebSocket()
		} else if (!userStore.isLoggedIn()) {
			// 用户未登录，关闭 WebSocket
			closeWebSocket()
		}
	},
	{ deep: true },
)

onMounted(async () => {
	await nextTick()

	// 恢复消息数据
	messageStore.restoreMessages()

	// 从持久化的 store 中读取语言设置并同步到 i18n
	i18n.global.locale.value = i18nStore.currentLocale

	// 同步 dayjs 语言
	dayjs.locale(i18nStore.currentLocale === 'zh-CN' ? 'zh-cn' : 'en')

	// 初始化主题颜色到 CSS 变量
	if (layoutStore.themeColor) {
		document.documentElement.style.setProperty('--primary-color', layoutStore.themeColor)
	}

	// 尝试初始化 WebSocket 连接
	if (userStore.isUserInfoComplete()) {
		initWebSocket()
	}
})

onUnmounted(() => {
	// 关闭 WebSocket 连接
	closeWebSocket()
})
</script>

<template>
	<a-config-provider :locale="antLocale" :theme="antdTheme" :getPopupContainer="getPopupContainer">
		<router-view />
	</a-config-provider>
</template>
