<script lang="ts" setup>
import { computed } from 'vue'
import { Menu } from 'ant-design-vue'
import { useRouter } from 'vue-router'
import { itemProps } from '../props'
import BasicMenuItem from './BasicMenuItem.vue'
import MenuItemContent from './MenuItemContent.vue'
import { useDesign } from '@/hooks/web/useDesign'
import type { Menu as MenuType } from '@/router/types'

defineOptions({ name: 'BasicSubMenuItem' })

const props = defineProps(itemProps)

const SubMenu = Menu.SubMenu

const { prefixCls } = useDesign('basic-menu-item')

const getShowMenu = computed(() => !props.item.meta?.hideMenu)
function menuHasChildren(menuTreeItem: MenuType): boolean {
  return (
    !menuTreeItem.meta?.hideChildrenInMenu
    && Reflect.has(menuTreeItem, 'children')
    && !!menuTreeItem.children
    && menuTreeItem.children.length > 0
  )
}

const router = useRouter()

function handleSwitchCloud(item: MenuType) {
  router.push(getFirstPathOfLastChild(item))
}

function getFirstPathOfLastChild(item: MenuType): string {
  // 如果当前菜单没有子菜单，直接返回当前菜单的 path
  if (!item.children || item.children.length === 0)
    return item.path

  // 递归找到最后一个子菜单的第一个 path
  return getFirstPathOfLastChild(item.children[0])
}
</script>

<template>
  <BasicMenuItem v-if="!menuHasChildren(item) && getShowMenu" v-bind="$props" :class="prefixCls" />
  <SubMenu v-if="menuHasChildren(item) && getShowMenu" :key="`submenu-${item.path}`" :class="[theme]" popup-class-name="app-top-menu-popup">
    <template #title>
      <MenuItemContent v-bind="$props" :item="item" @click="handleSwitchCloud(item)" />
    </template>

    <!--    <template v-for="childrenItem in item.children || []" :key="childrenItem.path"> -->
    <!--      <BasicSubMenuItem v-bind="$props" :item="childrenItem" /> -->
    <!--    </template> -->
  </SubMenu>
</template>
