<template>
  <el-aside width="220px" class="sidebar">
    <div class="logo">
      <span>流程审批系统</span>
    </div>
    <el-menu
      :default-active="activeMenu"
      router
      background-color="#304156"
      text-color="#bfcbd9"
      active-text-color="#409EFF"
      :collapse="false"
    >
      <template v-for="item in filteredMenuRoutes" :key="item.path">
        <!-- 只有一个子路由时，扁平化显示 -->
        <el-menu-item v-if="item.children.length === 1" :index="resolvePath(item.path, item.children[0].path)">
          <el-icon v-if="item.children[0].meta?.icon">
            <component :is="item.children[0].meta.icon" />
          </el-icon>
          <span>{{ item.children[0].meta?.title }}</span>
        </el-menu-item>

        <!-- 多个子路由时渲染为 sub-menu -->
        <el-sub-menu v-else :index="item.path">
          <template #title>
            <el-icon v-if="item.meta?.icon">
              <component :is="item.meta.icon" />
            </el-icon>
            <span>{{ item.meta?.title }}</span>
          </template>
          <el-menu-item
            v-for="child in item.children"
            :key="child.path"
            :index="resolvePath(item.path, child.path)"
          >
            <el-icon v-if="child.meta?.icon">
              <component :is="child.meta.icon" />
            </el-icon>
            <span>{{ child.meta?.title }}</span>
          </el-menu-item>
        </el-sub-menu>
      </template>
    </el-menu>
  </el-aside>
</template>

<script setup lang="ts">
import { computed } from 'vue'
import { useRoute } from 'vue-router'
import router from '@/router'
import { useUserStore } from '@/stores/user-store'
import { getAllowedMenuRoutes } from '@/utils/permission'

const currentRoute = useRoute()
const userStore = useUserStore()
const activeMenu = computed(() => currentRoute.path)

function resolvePath(parentPath: string, childPath: string) {
  if (childPath.startsWith('/')) {
    return childPath
  }
  if (parentPath === '/') {
    return '/' + childPath
  }
  return parentPath + '/' + childPath
}

// 路由表运行时不会变化，一次性计算即可，避免每次路由切换重复构造菜单
const menuRoutes = getAllowedMenuRoutes(router.getRoutes(), userStore.userInfo?.employeeType)

const filteredMenuRoutes = computed(() =>
  getAllowedMenuRoutes(router.getRoutes(), userStore.userInfo?.employeeType)
)
</script>

<style scoped>
.sidebar {
  background-color: #304156;
  color: #fff;
}
.logo {
  height: 60px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 18px;
  font-weight: bold;
  border-bottom: 1px solid #1f2d3d;
}
.el-menu {
  border-right: none;
}
</style>
