<template>
  <n-menu ref="menuInstRef" class="menu" :indent="0" :options="menuOptions" v-model:value="selectedKey" key-field="deptId"
    label-field="deptName" :default-expand-all="false" :watch-props="['defaultExpandedKeys']"
    :render-label="renderMenuLabel" @update:value="menuUpdateValue" />
</template>

<script lang="ts" setup>
import type { MenuOption } from 'naive-ui';
// import { NEllipsis } from 'naive-ui';
import { getMenu } from '@/api/table/list';
import { getFirstNodeLastLevel } from '@/utils/index';
import useStorage from '@/utils/useStorage'
import mitt from '@/plugins/bus';
const menuOptions = ref([]);
const selectedKey = ref();
const sessionStorageIns = useStorage('sessionStorage');

const emit = defineEmits(['tableMenuData']);

onMounted(() => {
  menuApi();
});

function menuApi() {
  //获取左侧菜单
  getMenu().then((res: any) => {
    if (res.code === 200) {
      const key = getFirstNodeLastLevel(res.data).deptId
      removeChildren(res.data);
      menuOptions.value = res.data;
      selectedKey.value = key;
      sessionStorageIns.setUseStorage('deptId', key);
      mitt.emit('menuKey', key);
      emit('tableMenuData', res.data);
    }
  });
}

function removeChildren(menu: any) {
  //处理菜单空children
  if (!Array.isArray(menu)) {
    return;
  }

  menu.forEach((item) => {
    if (item.children && item.children.length === 0) {
      delete item.children;
    } else {
      removeChildren(item.children);
    }
  });
}

function renderMenuLabel(option: MenuOption) {
  //菜单标题增加提示
  return h(NEllipsis, null, option.deptName as string);
}

function menuUpdateValue(key: string, item: MenuOption) {
  //点击菜单
  sessionStorageIns.setUseStorage('id', key);
  mitt.emit('menuKey', key);
  console.log(key, item);
}
</script>
<style lang="scss" scoped>
@import '../index.scss';
</style>
