<template>
	<aside style="user-select: none">
		<a-menu v-model:openKeys="openKeys" v-model:selectedKeys="selectedKeys" class="menu" mode="inline">
			<menu-item v-for="item of menus" :key="item.id" :menu="item" @onItemClick="clickMenu" />
		</a-menu>
	</aside>
</template>

<script lang="ts" setup>
import { useRoute, useRouter } from 'vue-router'
import { computed, onMounted, ref } from 'vue'
import { useMenuStore } from '../../../store/menu'
import MenuItem from './MenuItem.vue'
import { SystemMenu } from '../../../entity/system/system-menu'

// 菜单
const menuStore = useMenuStore()
/**
 * 菜单列表
 */
const menus = computed(() => menuStore.currentMenu?.children || [])

// 路由
const router = useRouter()

/**
 * 菜单点击事件
 */
function clickMenu(item: SystemMenu) {
	if (!item.linkUrl) return

	const pattern = /^((http|https|ftp):\/\/)/

	if (pattern.test(item.linkUrl)) {
		// 如果是http开头，那么就是网址
		window.open(item.linkUrl, '_blank')
	} else {
		// 否则打开路由
		router.replace(item.linkUrl)
	}
}

/**
 * 当前展开的 SubMenu 菜单项 key 数组
 * 当前选中的菜单项 key 数组
 */
const openKeys = ref<string[]>([])
const selectedKeys = ref<string[]>([])

/**
 * 根据路由的地址查找菜单，并选中
 */
router.afterEach((to, from) => {
	menuUpdate(decodeURI(to.path))
})

// 从地址首次进入，需要打开左侧的菜单
onMounted(() => {
	let route = useRoute()
	if (selectedKeys.value.length <= 0) {
		menuUpdate(decodeURI(route.path))
	}
})

/**
 * 更新菜单
 * @param path
 */
function menuUpdate(path: string) {
	// 从地址首次进入，需要打开左侧的菜单
	let systemMenu = menuStore.menuMap[path]
	if (!systemMenu) return
	// 从地址进入，显示对应的菜单
	const menuIds = systemMenu.menuIds
	if (menuIds?.length || 0 > 0) {
		menuStore.setIndexById(menuIds ? menuIds[0] : '')
	}

	// 当前选中的菜单id
	selectedKeys.value = [systemMenu.id]
	// 当前打开的item id
	if (systemMenu.menuIds) {
		// openKeys.value = [...openKeys.value, systemMenu.fkParentId]
		openKeys.value = openKeys.value.concat(systemMenu.menuIds)
	}
}
</script>
<script lang="ts">
export default {
	name: 'IndexMenu'
}
</script>

<style lang="less" scoped>
@import '@/assets/scss/theme.less';

.main-aside {
	overflow-y: scroll;
	width: @menu-width;
	// 去掉滚动条
	scrollbar-width: none; /* firefox */
	-ms-overflow-style: none; /* IE 10+ */
	background: @primary-color;

	&::-webkit-scrollbar {
		display: none; /* Chrome Safari */
	}

	// 菜单的图标
	.icon {
		width: 14px;
		height: 14px;
	}

	:deep(.ant-menu-inline) {
		border: none;
	}
}
</style>
