<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'

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)
      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>
