<template>
  <div class="left-menu">
    <t-menu :key="key" v-model:expanded="openKeys" v-model:value="activeKey">
      <children-menu v-model="userStore.moduleMenus" />
    </t-menu>
  </div>
</template>

<script setup name="LeftMenu">
import { ref, watch, onBeforeMount } from 'vue';
import { useRoute, useRouter, onBeforeRouteUpdate } from 'vue-router';
import { 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 userStore = useUserStore();
const key = ref(new Date().getTime() + '');

onBeforeMount(() => {
  userStore.setCurPage(route.name);
  activeKey.value = route.name;
  setOpenMenu();
});
onBeforeRouteUpdate((to) => {
  activeKey.value = to.name;
  let firstPath = to.path.split('/')[1];
  let curModuleName = moduleMap[firstPath];
  userStore.setCurPage(to.name);
  userStore.setCurPageModule(curModuleName);
});
watch(
  () => userStore.moduleMenus,
  () => {
    setOpenMenu();
    setTimeout(() => {
      key.value = new Date().getTime() + '';
    }, 0);
  }
);

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>
