<template>
	<div class="menu_link">
		<span class="link_item" v-for="item in menu" :key="item.id" @click="moduleClick(item.id)"
			:class="{active:item.id === selectedKeys[0]}"
		>
			<component :is="item.meta.icon" />
			{{item.meta.title}}
		</span>
		<!-- <a-menu
			v-model:selectedKeys="selectedKeys"
			mode="horizontal"
			v-if="menu && menu.length > 1 && !isMobile"
			class="module-menu"
			id="moduleMenu"
		>
			<a-menu-item
				v-for="item in menu"
				:key="item.id"
				class="!px-3"
				style="position: relative"
				@click="moduleClick(item.id)"
			>
				<template #icon>
					<component :is="item.meta.icon" />
				</template>
				<span style="margin-left: -5px">{{ item.meta.title }}</span>
			</a-menu-item>
		</a-menu> -->
	</div>
</template>

<script setup>
	import router from '@/router'
	import tool from '@/utils/tool'
	import { globalStore } from '@/store'
	import { watch } from 'vue'
	import { storeToRefs } from 'pinia'

	const store = globalStore()

	const { moduleUnfoldOpen, topHeaderThemeColorOpen } = storeToRefs(store)
	const moduleBackColor = ref(topHeaderThemeColorOpen)
	const module = computed(() => {
		return store.module
	})
	const isMobile = computed(() => {
		return store.isMobile
	})
	// 监听目录是否折叠
	watch(moduleUnfoldOpen, (newValue) => {
		nextTick(() => {
			setModuleBackColor()
		})
	})
	watch(module, (newValue) => {
		selectedKeys.value = [newValue]
		setSelectedKeys()
	})
	// 监听是否开启了顶栏颜色
	watch(topHeaderThemeColorOpen, (newValue) => {
		moduleBackColor.value = newValue
		setModuleBackColor()
	})

	const emit = defineEmits({ switchModule: null })
	const menu = router.getMenu()
	const selectedKeys = ref([module.value])
	const moduleClick = (id) => {
		emit('switchModule', id)
		tool.data.set('SNOWY_MENU_MODULE_ID', id)
		nextTick(() => {
			setSelectedKeys()
		})
	}

	onMounted(() => {
		setModuleBackColor()
	})
	// 设置背景色
	const setModuleBackColor = () => {
		if (moduleUnfoldOpen.value) {
			try {
				const moduleMenu = document.getElementById('moduleMenu')
				moduleBackColor.value
					? moduleMenu.classList.add('module-menu-color')
					: moduleMenu.classList.remove('module-menu-color')
				// eslint-disable-next-line no-empty
			} catch (err) {}
			setSelectedKeys()
		}
	}
	// 设置选中
	const setSelectedKeys = () => {
		// 顶部应用列表让显示出来默认的
		moduleBackColor.value
			? (selectedKeys.value = new Array([]))
			: (selectedKeys.value = [tool.data.get('SNOWY_MENU_MODULE_ID')])
	};
</script>

<style lang="less">
.menu_link{
	.link_item{
		margin-right:20px; color:#fff;
		padding:10px 12px; cursor:pointer;
		&.active{
			background:#fff; color:#333;
		}
	}
}
</style>
