<template>
  <div class="h-full flex-col flex">
    <div class="flex-1 relative">
      <el-menu
        unique-opened
        class="el-menu-vertical-demo"
        :collapse="isCollapse"
        :default-active="currentPath"
      >
        <template v-for="item in routes" :key="item.path">
          <!-- 多级路由 -->
          <el-sub-menu v-if="item.children!.length > 0" :index="item.path">
            <template #title>
              <el-icon>
                <template #default>
                  <img
                    :src="
                      item.path === currentPath ||
                      item.children?.some((it) => {
                        return it.path === currentPath
                      })
                        ? item.lightIcno
                        : item.icno
                    "
                    alt=""
                  />
                </template>
              </el-icon>
              <span>{{ item.name }}</span>
            </template>
            <el-menu-item
              :index="citem.path"
              v-for="citem in item.children"
              :key="citem.path"
              @click="changeRouter(citem.path)"
              ><p>{{ citem.name }}</p></el-menu-item
            >
          </el-sub-menu>
          <!-- 单级路由 -->
          <el-menu-item :index="item.path" v-else @click="changeRouter(item.path)">
            <el-icon>
              <template #default>
                <img :src="item.path === currentPath ? item.lightIcno : item.icno" alt="" />
              </template>
            </el-icon>
            <span>{{ item.name }}</span>
          </el-menu-item>
        </template>
      </el-menu>
      <div class="absolute bottom-4 left-1/2 -translate-x-1/2" @click="toggle">
        <el-icon v-if="isCollapse" class="cursor-pointer"><Expand /></el-icon>
        <el-icon v-else><Fold /></el-icon>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, computed } from 'vue'
import { Expand, Fold } from '@element-plus/icons-vue'
import mapRoutes from '@/router-handle/mapRoutes'
import { useRoute, useRouter } from 'vue-router'
const isCollapse = ref(false)
const router = useRouter()
const route = useRoute()
// 获取home下的子路由，并且进行排序
const routes = mapRoutes().sort((a, b) => {
  return a.index - b.index
})

const currentPath = computed(() => {
  return route.fullPath
})

const toggle = () => {
  isCollapse.value = !isCollapse.value
}
const changeRouter = (path: string) => {
  router.push(path)
}
</script>

<style>
.el-menu-vertical-demo {
  height: 100%;
}
.el-menu-vertical-demo:not(.el-menu--collapse) {
  width: 240px;
}
</style>
