<script setup lang="ts">
import { useRouterStore } from '@/stores/router'
import { useMenuStore } from '@/stores/menu'

const menuStore = useMenuStore()

// 生成菜单部分开始
const routerStore = useRouterStore()
const menuRouter = routerStore.menuRouter
const generatorMenu = (routes: any[]) => {
  routes.forEach(route => {
    if (route.children && route.children.length) {
      route.menuName = 'el-sub-menu'
      generatorMenu(route.children)
    } else {
      route.menuName = 'el-menu-item'
    }
  })
}
generatorMenu(menuRouter)
// 生成菜单部分结束

const router = useRouter()
const route = useRoute()

const isAbsolutePath = (path: string) => {
  return path.startsWith('http')
}
const handleSelect = (index: string) => {
  if (isAbsolutePath(index)) {
    window.open(index)
  } else {
    router.push(index)
  }
}
</script>

<template>
  <el-menu
    :default-active="route.path"
    :collapse="menuStore.collapse"
    :collapse-transition="false"
    class="layout-menu"
    :class="{ 'menu-normal': !menuStore.collapse }"
    @select="handleSelect"
  >
    <component :is="item.menuName" :index="item.path" v-for="(item, index) in menuRouter" :key="index">
      <el-icon v-if="item.menuName === 'el-menu-item'"><component :is="item.meta?.icon"></component></el-icon>
      <template #title>
        <el-icon v-if="item.menuName === 'el-sub-menu'"><component :is="item.meta?.icon"></component></el-icon>
        <span>{{ item.meta.title }}</span>
      </template>
      <el-menu-item
        :index="isAbsolutePath(subItem.path) ? subItem.path : item.path + '/' + subItem.path"
        v-for="(subItem, key) in item.children"
        :key="key"
      >
        <template #title>
          <el-icon v-if="subItem.meta?.icon"><component :is="subItem.meta?.icon"></component></el-icon>
          <span>{{ subItem.meta.title }}</span>
        </template>
      </el-menu-item>
    </component>
  </el-menu>
</template>

<style scoped>
.menu-normal {
  width: var(--menu-width);
}
.layout-menu {
  background-color: #fff;
  height: 100%;
  border: none;
  flex-shrink: 0;
}
.layout-menu .el-menu-item.is-active {
  background-color: var(--el-color-primary);
  color: #fff;
}
</style>
