<script setup lang="ts">
import Item from './Item.vue'
import MenuItem from './MenuItem.vue';
import type { RouteRecordDetailRaw } from '~/router/routes.d'
import { ref } from 'vue';


const props = defineProps<{
  item: RouteRecordDetailRaw
}>()

const currentRoute: RouteRecordDetailRaw = props.item
const showRoute = ref<RouteRecordDetailRaw>(currentRoute)

const showMode = ref<number>(0)

function filterShowChild(children?: RouteRecordDetailRaw[]): RouteRecordDetailRaw[] {
  if (Array.isArray(children)) {
    const temp = children.filter(child => !child.meta.hidden).sort((a, b) => a.meta.sort - b.meta.sort)
    if (temp.length === 1 && Array.isArray(temp[0].children)) {
      return filterShowChild(temp[0].children)
    }
    return temp
  }
  else {
    return []
  }
}
const currentRouteShowChildren = filterShowChild(currentRoute.children)

if (currentRouteShowChildren.length === 0) {
  showMode.value = 1
}
else if (currentRouteShowChildren.length === 1) {
  showRoute.value = currentRouteShowChildren[0]
  showMode.value = 1
}
else {
  showMode.value = 2
}

</script>

<template>
  <template v-if="!item?.meta?.hidden">
    <template v-if="showMode === 1">
      <AppLink :to="showRoute.name">
        <el-menu-item :index="showRoute.name">
          <Item :icon="showRoute?.meta?.icon" :title="showRoute?.meta?.title"></Item>
        </el-menu-item>
      </AppLink>
    </template>

    <template v-if="showMode === 2">
      <el-sub-menu :index="showRoute.name">
        <template #title>
          <Item :icon="showRoute?.meta?.icon" :title="showRoute.meta.title"></Item>
        </template>

        <MenuItem v-for="route in showRoute.children" :item="route" />

      </el-sub-menu>
    </template>
  </template>

</template>
