<template>
  <div class="left-menu">
    <t-menu
      :key="key"
      theme="dark"
      v-model:expanded="openKeys"
      v-model:value="activeKey"
      :collapsed="appStore.menuCollapse"
      :width="
        (appStore.menuCollapse ? appStore.collapseWidth : appStore.menuWidth) +
        'px'
      "
    >
      <template #logo>
        <div class="logo-box flex justify-center items-center">
          <img src="../assets/logo.svg" />
        </div>
      </template>
      <children-menu v-model="userStore.moduleMenus" />
      <template #operations>
        <div
          class="flex justify-center items-center cursor-pointer h-full"
          @click="onCollapse"
        >
          <t-icon
            v-if="appStore.menuCollapse"
            name="chevron-right-double"
            color="#fff"
          />
          <t-icon v-else name="chevron-left-double" color="#fff" />
        </div>
      </template>
    </t-menu>
  </div>
</template>

<script setup name="LeftMenu">
import { ref, watch, onBeforeMount } from 'vue';
import { useRoute, useRouter, onBeforeRouteUpdate } from 'vue-router';
import { useAppStore, useUserStore } from '@/store';
import childrenMenu from './children-menu.vue';
import { moduleMap } from '@/router/asyncRoutes';
const route = useRoute();
const router = useRouter();
// const menus = ref([]);
const activeKey = ref('');
const openKeys = ref([]);
const appStore = useAppStore();
const userStore = useUserStore();
const key = ref(new Date().getTime() + '');

onBeforeMount(() => {
  activeKey.value = route.name;
  setOpenMenu();
});
onBeforeRouteUpdate((to) => {
  activeKey.value = to.name;
  let firstPath = to.path.split('/')[1];
  let curModuleName = moduleMap[firstPath];
  userStore.setCurPageModule(curModuleName);
});
watch(
  () => userStore.moduleMenus,
  () => {
    setOpenMenu();
    setTimeout(() => {
      key.value = new Date().getTime() + '';
    }, 0);
  }
);
const onCollapse = () => {
  appStore.toggleMenu();
};
const setOpenMenu = () => {
  openKeys.value = [];
  //如果初始化的时候左侧全部展开
  const moduleMenus = userStore.moduleMenus;
  for (const item of moduleMenus) {
    openKeys.value.push(item.name);
  }

  //如果只展开当前页面所在的父菜单
  // if (route.matched.length && route.matched.length > 1) {
  //   const last = route.matched[route.matched.length - 1];
  //   if (last.meta && Array.isArray(last.meta.breadcrumb))
  //     last.meta.breadcrumb.map((item) => {
  //       openKeys.value.push(item.name);
  //     });
  // }
};
</script>

<style lang="less" scoped>
.left-menu {
  height: 100%;
  :deep(.t-menu__operations) {
    padding: 0 !important;
    height: 40px;
  }
  .logo-box {
    padding: 10px;
    height: 100%;
    width: 100%;
    span {
      font-size: 22px;
      color: #ccc;
    }
    img {
      max-height: 100%;
      max-width: 100%;
    }
  }
}
</style>
