<!--
 * @Description:
 * @Author: zenghua.wang
 * @Date: 2023-06-20 14:29:45
 * @LastEditors: zenghua.wang
 * @LastEditTime: 2024-01-27 16:07:37
-->
<template>
  <template v-if="!item.hidden">
    <template v-if="!item.alwaysShow && hasOneShowingChild(item.children, item)">
      <layout-link v-if="onlyOneChild.meta" :to="onlyOneChild.path">
        <el-menu-item :index="onlyOneChild.path">
          <img v-if="onlyOneChild.meta.icon" :src="getAssetsFile(onlyOneChild.meta.icon)" style="height: 20px; margin-right: 20px" alt="" />
          <!--          <layout-icon :size="20" :icon="onlyOneChild?.meta?.icon ? getAssetsFile(onlyOneChild.meta.icon) : undefined" />-->
          <template #title>{{ onlyOneChild.meta && onlyOneChild.meta?.title }}</template>
        </el-menu-item>
      </layout-link>
    </template>
    <el-sub-menu v-else :index="item.path" teleported>
      <template #title>
        <!--        <layout-icon :size="20" :icon="item?.meta?.icon ? getAssetsFile(item.meta.icon) : undefined" />-->
        <span>{{ item.meta && item.meta?.title }}</span>
      </template>
      <sub-item v-for="child in item.children" :key="child.path" :item="child" />
    </el-sub-menu>
  </template>
</template>

<script setup name="sub-item">
import { ref } from 'vue';
// import { isExternal } from '@/utils/validate.js';
import LayoutLink from './Link';
import LayoutIcon from './Icon';
import { getAssetsFile } from '@/utils/index.js';
// import path from 'path-browserify';

defineProps({
  item: {
    type: Object,
    required: true,
  },
  basePath: {
    type: String,
    default: '',
  },
});

const onlyOneChild = ref(null);
const hasOneShowingChild = (children = [], parent) => {
  const showingChildren = children.filter((item) => {
    // 过滤掉需要隐藏的菜单
    if (item.hidden) {
      return false;
    } else {
      // 临时设置（如果只有一个显示子项，则将使用）
      onlyOneChild.value = item;
      return true;
    }
  });

  // 当只有一个子路由器时，默认情况下会显示该子路由器
  if (showingChildren.length === 1) {
    return true;
  }
  // 如果没有要显示的子路由器，则显示父路由器
  if (showingChildren.length === 0) {
    onlyOneChild.value = { ...parent, noShowingChildren: true };
    return true;
  }
  return false;
};

// const resolvePath = (routePath) => {
//   if (isExternal(routePath)) {
//     return routePath;
//   }
//   if (isExternal(props.basePath)) {
//     return props.basePath;
//   }
//   return path.resolve(props.basePath, routePath);
// };
</script>
