<template>
  <n-menu
    :mode="menuMode"
    :value="currentRoute.title ?? currentRoute.meta.title"
    :options="getMenuOptions"
    :default-expanded-keys="defaultExpandedKeys"
    :watch-props="['defaultExpandedKeys']"
    @update:value="handleMenuSelect"
  />
</template>

<script setup>
import { useRouter, useRoute } from 'vue-router'
import { computed, defineProps, toRaw, ref } from 'vue'
import { isExternal } from '@/utils/is.js'
import { usePermissionStore } from '@/store/modules/permission'

const props = defineProps({
  menuMode: {
    type: String,
    default: 'vertical'
  }
})

// 刷新展开相应路由
const route = useRoute()
const defaultExpandedKeys = ref([])
const menuInstRef = ref(null)
setTimeout(() => {
  if (route.meta.isHidden) { // 没有菜单的路由
    defaultExpandedKeys.value = [route.matched[0]?.meta?.title] // 展开 父级菜单
  } else { // 有菜单的路由
    menuInstRef.value?.showOption(route.meta?.title) // 选中该菜单
  }
})

const menuMode = toRaw(props.menuMode)

const router = useRouter()
const { currentRoute } = router
const permissionStore = usePermissionStore()
const getMenuOptions = computed(() => {
  return generateOptions(permissionStore.routes, '')
})

function resolvePath(basePath, path) {
  if (isExternal(path)) return path
  return (
    '/' +
    [basePath, path]
      .filter((path) => !!path && path !== '/')
      .map((path) => path.replace(/(^\/)|(\/$)/g, ''))
      .join('/')
  )
}

function generateOptions(routes, basePath) {
  const options = []
  routes.forEach((route) => {
    if (route.title && !route.isHidden) {
      const curOption = {
        label: (route.meta && route.meta.title) || route.title,
        key: route.title,
        path: resolvePath(basePath, route.path),
        icons: route.icons ?? ''
      }
      if (route.children && route.children.length && !route.meta?.hideChild) {
        curOption.children = generateOptions(route.children, resolvePath(basePath, route.path))
      }
      options.push(curOption)
    }
  })
  return options
}

function handleMenuSelect(key, item) {
  if (isExternal(item.path)) {
    window.open(item.path)
  } else {
    router.push(item.path)
  }
}

</script>
<style scoped lang='scss'>
</style>
