<template>
    <a-menu v-model:selected-keys="selectedKey"
        :default-open-keys="selectedKey">
        <template v-for="menu in menuData" :key="menu.key">
            <a-sub-menu v-if="menu.children" :key="menu.key">
                <template #icon>
                    <component :is="menu.icon"></component>
                </template>
                <template #title>{{ menu.label }}</template>
                <a-menu-item v-for="child in menu.children" :key="child.key" :disabled="child.disabled"
                    @click="$router.push(child.key)">
                    {{ child.label }}
                </a-menu-item>
            </a-sub-menu>

            <a-menu-item v-else :key="menu.key" :disabled="menu.disabled" @click="$router.push(menu.key)">
                <template #icon>
                    <component :is="menu.icon"></component>
                </template>
                {{ menu.label }}
            </a-menu-item>
        </template>
    </a-menu>
</template>

<script setup>
import { onMounted, ref } from 'vue'
import { routes } from '@/router'
import { useUserStore } from '@/store/modules/user'
import { useRouteListener } from '@/utils/route-listener'
import { isElectron } from '../../utils/electron'

const userStore = useUserStore()
const user = ref({})
const electron = ref(false)
const menuData = ref([])

const { selectedKey } = useRouteListener()

const hasPermission = (route) => {
    if (!route.meta || !route.meta.permission) return true
    if (!user.value.roles || user.value.roles.length === 0) return false
    return route.meta.permission.some((perm) => user.value.roles.includes(perm))
}

const checkEnv = (route) => {
    if (!route.meta) return true
    if (route.meta.onlyWeb) return !electron.value
    if (route.meta.onlyElectron) return !!electron.value
    return true
}

const generateMenu = (routes, parentPath = '') => {
    return routes
        .filter((route) => hasPermission(route) && !(route.meta && route.meta.hideInMenu) && checkEnv(route))
        .map((route) => {
            const fullPath = parentPath + route.path; // 确保子路由路径完整
            const menu = {
                key: fullPath,
                label: route.meta?.title || route.name,
                icon: route.meta?.icon || '',
                disabled: route.meta?.disabled || false
            }

            if (route.children && route.children.length > 0) {
                menu.children = generateMenu(route.children, fullPath + '/')
            }

            return menu
        })
}

onMounted(async () => {
    user.value = await userStore.getInfo()
    electron.value = isElectron()
    menuData.value = generateMenu(routes)
})
</script>