<template>
	<a-menu
		v-model:openKeys="openKeys"
		v-model:selectedKeys="selectedKeys"
		mode="inline"
		@click="handleClick"
	>
		<template v-for="item in menus" :key="item.name">
			<!-- 是否有子菜单-->
			<template v-if="!item.children || item.meta.hideChildrenInMenu">
				<!-- 是否需要在菜单中隐藏-->
				<template v-if="!item.meta.hideMenu">
					<a-menu-item
						:key="item.name"
						:class="
							item.name === 'DataSource'
								? 'custom-a-menu-hidden'
								: ''
						"
					>
						<!-- 是否需要显示icon-->
						<template #icon v-if="item.meta.icon">
							<base-svg-icon :name="item.meta.icon" />
						</template>
						{{ item.meta.title }}
					</a-menu-item>
				</template>
			</template>
			<template v-else>
				<base-sub-menu :key="item.name" :menu-info="item" />
			</template>
		</template>
	</a-menu>
</template>
<script lang="ts">
import { defineComponent, ref, PropType } from 'vue'
import type { AppRouteRecordRaw } from '@/router/model'
import BaseSubMenu from './BaseSubMenu.vue'
import { useRoute } from 'vue-router'
import router from '@/router'
import { onBeforeRouteUpdate } from 'vue-router'

export default defineComponent({
	components: {
		BaseSubMenu,
	},
	props: {
		menus: {
			type: Array as PropType<AppRouteRecordRaw[]>,
			required: true,
		},
	},
	setup() {
		const route = useRoute()
		// const routerName = computed(() => route.name)
		// 获取当前路由name
		const selectedKeys = ref<string[]>(
			route.matched
				.filter(
					f =>
						f.name != 'Root' &&
						f.name != 'Auth' &&
						f.name != 'Errors'
				) //  && f.name != 'DesignUserAuth'
				.map(m => (m.name ? m.name.toString() : ''))
		)
		// 获取当前路由层级，并展开相应的sub menu
		const openKeys = ref<string[]>(
			route.matched
				.filter(
					f =>
						f.name != 'Root' &&
						f.name != 'Auth' &&
						f.name != 'Errors'
				)
				.map(m => (m.name ? m.name.toString() : ''))
		)
		const handleClick = ({ key }) => {
			router.push({ name: key })
		}
		// 监听路由更新前，重置菜单选中
		onBeforeRouteUpdate(to => {
			selectedKeys.value = to.matched
				.filter(
					f =>
						f.name != 'Root' &&
						f.name != 'Auth' &&
						f.name != 'Errors'
				)
				.map(m => (m.name ? m.name.toString() : ''))
			openKeys.value = to.matched
				.filter(
					f =>
						f.name != 'Root' &&
						f.name != 'Auth' &&
						f.name != 'Errors'
				)
				.map(m => (m.name ? m.name.toString() : ''))
		})
		return {
			selectedKeys,
			openKeys,
			handleClick,
		}
	},
})
</script>
