<template>
  <el-menu
    ref="menuRef"
    :key="key"
    class="main-layout-left-menu"
    unique-opened
    :default-active="defaultActive"
    :default-openeds="defaultOpened"
    :collapse="mainLayoutStore.collapse"
    @open="onOpen"
  >
    <menu-item
      v-for="menu in renderMenus"
      :key="menu.index"
      :current-index="activeIndex"
      :menu="menu"
      @handle="onHandle"
    ></menu-item>
  </el-menu>
</template>

<script setup lang="ts" name="MainLayoutLeftMenu">
import { computed, ref, watch, onActivated } from 'vue'
import { useRoute } from 'vue-router'
import { ElMenu } from 'element-plus'
import useMainLayoutStore from '@/store/layout'
import MenuItem from '@/layout/main/MenuItem.vue'
import useMainStore from '@/store/main'
const route = useRoute()
const mainLayoutStore = useMainLayoutStore()
const mainStore = useMainStore()
const renderMenus = computed(() => {
  let isHiddenAnalysis = mainStore?.myUserInfo?.role === 'ADMIN' || mainStore?.myUserInfo?.role === 'MARKER'

  return mainLayoutStore.renderMenus.filter((item: any) => {
    return !(item.index === 'analysis' && isHiddenAnalysis)
  })
})
const menuRef = ref<InstanceType<typeof ElMenu> & { close: (index: string) => void }>()
const key = ref('' + new Date().getTime())
onActivated(() => {
  key.value = '' + new Date().getTime()
})
const activeIndex = computed(() => {
  if (route.meta?.menu) {
    return route.meta.menuId
  }
  const ids = route.meta.menuId?.split('-')
  return ids?.slice(0, -1)?.join('-') || ''
})

const defaultActive = ref(activeIndex.value)

const defaultOpened = computed(() => {
  const rootSub = activeIndex.value.split('-')[0]
  return [rootSub]
})

watch(activeIndex, () => {
  if (defaultActive.value) {
    defaultActive.value = ''
  }
})

let opened = ''

const onOpen = (index: string) => {
  opened = index
}

const onHandle = () => {
  opened && menuRef.value?.close(opened)
}
</script>

<style scoped lang="scss">
.main-layout-left-menu {
  padding: $BaseGapSpace 0;
  border-right: none;
  font-weight: bold;
  background-color: #333;
}
.main-layout-left-menu {
  :deep(.el-sub-menu .el-menu-item) {
    height: 34px !important;
  }
  :deep(> .el-menu-item) {
    & > .main-layout-sub-menu-title {
      & > .router-link-active {
        color: #fff;
        background: $color--primary;
      }
    }
  }

  :deep(.el-menu) {
    background-color: #333;
    .el-menu-item {
      // color: #666;
      color: #fff;
      .router-link-active {
        color: #fff;
        background: $color--primary;
      }
    }
  }
}
</style>
