import { createRouter, createWebHistory } from 'vue-router'
import { useUserInfoStore } from '@/stores/userInfo'
import { useGlobalStore } from '@/stores/global'
import { getUserLanguage } from '@/api/user'
import { fetchAllUnreadMessage } from '@/api/notification'
import i18n from '@/lang/index'
import myEvent from '@/utils/myEvent'

// 语言映射：后端格式 -> i18n 格式
const backendToI18nLanguage: Record<string, string> = {
	en: 'ENGLISH',
	'zh-CN': 'CHINESE_SIMPLIFIED'
}

// 语言同步状态缓存（避免每次路由切换都请求）
let languageSynced = false

/**
 * 路由缓存机制:
 * 1. 设置路由的meta属性为{ cache: true }，表示需要缓存
 * 2. App.vue中使用RouteCache组件，通过路由的name来进行匹配
 * 3. 路由的name默认是文件名,如果文件名与name不一致,通过defineOptions({ name: 'componentName' })来设置
 * 
 * 需要登录路由: meta={ login:true }
 */
const router = createRouter({
	routes: [
		{
			path: '/',
			name: 'home',
			component: () => import('../views/home/index.vue')
		},
		{
			path: '/collectionStory',
			name: 'collectionStory',
			component: () => import('../views/collectionStory/index.vue')
		},
		{
			path: '/brand',
			name: 'brand',
			component: () => import('../views/brand/index.vue')
		},
		{
			path: '/brand/:id',
			name: 'brandDetail',
			component: () => import('../views/brandDetail/index.vue')
		},
		{
			path: '/digitalItem',
			name: 'digitalItem',
			component: () => import('../views/digitalItem/index.vue'),
			meta: { cache: true }
		},
		{
			path: '/digitalItem/:id',
			name: 'digitalItemDetail',
			component: () => import('../views/digitalDetail/index.vue')
		},
		{
			path: '/settings',
			name: 'settings',
			component: () => import('@/views/setting/index.vue'),
			meta: { cache: true }
		},
		{
			path: '/shoppingCart', // 购物车
			name: 'shoppingCart',
			component: () => import('@/views/shoppingCart/index.vue'),
			meta: { login: true }
		},
		{
			path: '/notifications',
			name: 'notifications',
			component: () => import('@/views/notifications/index.vue')
		},
		{
			path: '/wardrobe',
			name: 'wardrobe',
			component: () => import('@/views/wardrobe/index.vue')
		},
		{
			path: '/account',
			name: 'account',
			component: () => import('@/views/account/index.vue')
		},
		{
			path: '/pay',
			name: 'pay',
			component: () => import('@/views/pay/index.vue')
		},
		{
			path: '/:pathMatch(.*)',
			name: '404',
			component: () => import('../views/404.vue')
		}
	],
	history: createWebHistory('/')
})

router.beforeEach((to, from, next) => {
	if(to.meta?.login && !useUserInfoStore().state.token) {
		myEvent.emit('openLoginDialog')
	}
	next()
})

router.afterEach(async () => {
	const userInfoStore = useUserInfoStore()
	const token = userInfoStore.state.token

	if (!token) {
		languageSynced = false
		return
	}

  const globalStore = useGlobalStore()
	fetchAllUnreadMessage().then((res) => {
    globalStore.setUnredCount(res.totalUnread)
	})

	if (languageSynced) {
		return
	}

	try {
		// 获取用户语言设置
		const response = await getUserLanguage()
		const userLanguage = (response as any)?.language // 后端返回 'en' 或 'zh-CN'

		if (!userLanguage) {
			return
		}

		// 转换为 i18n 格式
		const i18nLanguage = backendToI18nLanguage[userLanguage]

		if (!i18nLanguage) {
			return
		}

		// 获取当前 i18n 语言
		const currentLocale = i18n.global.locale.value

		// 如果用户语言和本地 i18n 不一致，更新 i18n
		if (i18nLanguage !== currentLocale) {
			i18n.global.locale.value = i18nLanguage as 'ENGLISH' | 'CHINESE_SIMPLIFIED'
			localStorage.setItem('language', i18nLanguage)
		}

		// 标记已同步
		languageSynced = true
	} catch (error) {
		// 静默失败，不影响页面正常加载
		console.warn('Failed to sync user language:', error)
	}
})

export default router
