<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import type { PropType } from 'vue'
import { isExternal } from '@/utils/validate'
import AppLink from '@/components/AppLink/index.vue'

// 使用类型断言来处理路由项
type MenuItem = any

const props = defineProps({
  item: {
    type: Object as PropType<MenuItem>,
    required: true
  },
  isNest: {
    type: Boolean,
    default: false
  },
  basePath: {
    type: String,
    default: ''
  },
  sidebarStatus: {
    type: Boolean,
  }
})

// 定义要显示的唯一子项
const onlyOneChild = ref<MenuItem | null>(null)

// 是否总是显示根菜单
const alwaysShowRootMenu = computed(() => {
  return props.item.meta?.alwaysShow || false
})

// 解析路径
const resolvePath = (routePath: string) => {
  
  if (isExternal(routePath)) {
    return routePath
  }
  if (isExternal(props.basePath)) {
    return props.basePath
  }
  return props.basePath ? props.basePath + '/' + routePath : routePath
}

// 是否只有一个要显示的子项
const hasOneShowingChild = (children: MenuItem[] = [], parent: MenuItem): boolean => {
  if (!children) {
    children = []
  }

  const showingChildren = children.filter(item => {
    if (item.meta?.hidden) {
      return false
    } else {
      // 临时设置（当只有一个子路由时使用）
      onlyOneChild.value = item
      return true
    }
  })

  // 当只有一个子路由时，默认显示该子路由
  if (showingChildren.length === 1) {
    return true
  }

  // 当没有要显示的子路由时，则显示父路由
  if (showingChildren.length === 0) {
    onlyOneChild.value = {
      ...parent,
      path: '',
      meta: parent.meta
    }
    return true
  }

  return false
}

onMounted(() => {

})
</script>

<template>
  <div v-if="!item.meta?.hidden" class="sidebar-item-container">
    <template
      v-if="hasOneShowingChild(item.children as MenuItem[], item) && (!onlyOneChild?.children?.length || onlyOneChild?.meta?.noShowingChildren) && !alwaysShowRootMenu">
      <app-link v-if="onlyOneChild?.meta" :to="resolvePath(onlyOneChild.path)" class="sidebar-link">
        <el-menu-item :index="resolvePath(onlyOneChild.path)">
          <el-icon v-if="onlyOneChild.meta?.icon">
            <component :is="onlyOneChild.meta.icon" />
          </el-icon>
          <span v-if="onlyOneChild.meta?.title && sidebarStatus">{{ onlyOneChild.meta.title }}</span>
        </el-menu-item>
      </app-link>
    </template>

    <el-sub-menu v-else ref="subMenu" :index="resolvePath(item.path)">
      <template #title>
        <el-icon v-if="item.meta?.icon">
          <component :is="item.meta.icon" />
        </el-icon>
        <span v-if="item.meta?.title">{{ item.meta.title }}</span>
      </template>
      <sidebar-item v-for="child in item.children" :key="child.path" :is-nest="true" :item="child"
        :base-path="resolvePath(child.path)" class="nest-menu" />
    </el-sub-menu>
  </div>
</template>

<style lang="scss" scoped>
.sidebar-link {
  text-decoration: none;
}

.el-menu-item,
.el-sub-menu {
  background-color: transparent !important;
}
</style>
