<script setup lang="ts">
import { computed } from 'vue'
import type { MenuItem } from '@/types/menu'

interface Props {
  item: MenuItem
  basePath?: string
}

const props = withDefaults(defineProps<Props>(), {
  basePath: ''
})

// 过滤隐藏的子菜单
const visibleChildren = computed(() => {
  return props.item.children?.filter(child => !child.meta?.hidden) || []
})

// 判断是否有可见的子菜单
const hasChildren = computed(() => {
  return visibleChildren.value.length > 0
})

// 解决路径
const resolvePath = computed(() => {
  return resolveBasePath(props.item.path)
})

function resolveBasePath(path: string) {
  // 如果 path 已经是绝对路径，直接返回，不再拼接
  if (path.startsWith('/')) {
    return path
  }
  if (props.basePath) {
    return `${props.basePath}/${path}`.replace(/\/+/g, '/')
  }
  return path
}
</script>

<template>
  <template v-if="!item.meta?.hidden" class="menu-item">
    <template v-if="hasChildren">
      <el-sub-menu :index="item.path">
        <template #title>
          <el-icon v-if="item.meta?.icon">
            <component :is="item.meta.icon" />
          </el-icon>
          <span>{{ item.meta?.title }}</span>
        </template>
        <SidebarItem
          v-for="child in visibleChildren"
          :key="child.path"
          :item="child"
          :base-path="resolveBasePath(item.path)"
        />
      </el-sub-menu>
    </template>
    <template v-else>
      <el-menu-item :index="resolvePath">
        <el-icon v-if="item.meta?.icon">
          <component :is="item.meta.icon" />
        </el-icon>
        <template #title>
          <span>{{ item.meta?.title }}</span>
        </template>
      </el-menu-item>
    </template>
  </template>
</template>

<style scoped>
.menu-item {
  /* 自定义样式 */
}
</style>
