<script lang="ts">
import { computed, defineComponent, onMounted, ref, unref, watch } from "vue";
import { useRoute, useRouter } from "vue-router";
import { IconGroup } from "../IconGroup";
import { useAsyncRouteStore } from "@/store/modules/asyncRoute";
import { generatorMenu } from "@/utils";
import { storage } from "@/utils/Storage";
import { CURRENT_USER } from "@/store/mutation-types";

export default defineComponent({
  name: "AppMenu",
  components: { IconGroup },
  emits: ["clickMenuItem"],
  setup(props, { emit }) {
    // 当前路由
    const currentRoute = useRoute();
    const router = useRouter();
    const asyncRouteStore = useAsyncRouteStore();
    const menus = ref<any[]>([]);
    const selectedSvg = ref<string>(currentRoute.meta.svgname as string);

    const getSelectedSvg = computed(() => {
      return unref(selectedSvg);
    });

    // 跟随页面路由变化，切换菜单选中状态
    watch(
      () => currentRoute.fullPath,
      () => {
        updateMenu();
      }
    );

    function updateSelectedKeys() {
      const svgname: string = (currentRoute.meta?.svgname as string) || "";
      selectedSvg.value = svgname;
    }

    function updateMenu() {
      menus.value = generatorMenu(asyncRouteStore.getMenus);
      const userInfo = storage.get(CURRENT_USER);
      if (userInfo && userInfo.frontmenuTList) {
        menus.value = userInfo.frontmenuTList.map((item) => {
          let v = {
            component: () =>
              item.resUrl == "/task"
                ? import("@/views/task/index.vue")
                : item.resUrl == "/home"
                ? import("@/views/home/index.vue")
                : item.resUrl == "/worksheet"
                ? import("@/views/worksheet/index.vue")
                : item.resUrl == "/final"
                ? import("@/views/final/index.vue")
                : "",
            icon: undefined,
            key: item.resKey,
            label: item.description,
            meta: {
              title: item.description,
              permissions: [item.resKey],
            },
            path: item.resUrl,
            name: item.resKey,
            svgname: item.icon,
            svgsize: item.resUrl == "/home" ? 60 : 22,
            title: item.description,
          };
          return v;
        });
      }
      updateSelectedKeys();
    }

    // 点击菜单
    function clickMenuItem(key: string) {
      if (/http(s)?:/.test(key)) window.open(key);
      else router.push({ name: key });

      emit("clickMenuItem" as any, key);
    }

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

    return {
      menus,
      selectedSvg,
      getSelectedSvg,
      clickMenuItem,
    };
  },
});
</script>

<template>
  <IconGroup :options="menus" :value="getSelectedSvg" @update:value="clickMenuItem" />
</template>
