<script setup>
const props = defineProps({
    item: {
        type: Object,
        required: true
    }
})
const onlyOneChild = ref(null)
function fatherHasOneSonOrMenu(children = [], parent) {
    if (!children) {
        children = []
    }
    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
}
function isExternal(path) {
    return /^(https?:|mailto:|tel:)/.test(path)
}

const router = useRouter()
const handleClickMenu = item => {
    console.log(item.path)
    if (isExternal(item.path)) {
        window.open(item.path, '_blank')
    } else {
        if (item.path.startsWith('/tjmchild')) {
            const parts = item.path.split('/') // 使用斜杠分割路径
            console.log(parts.slice(3).join('/'))
            router.push({
                name: parts[2],
                params: { page: parts.slice(3).join('/') }
            })
        } else {
            router.push(item.path)
        }
    }
}
</script>

<template>
    <template v-if="!item.hidden">
        <template v-if="fatherHasOneSonOrMenu(item.children, item) && !item.alwaysShow">
            <el-menu-item :index="onlyOneChild.path" @click="handleClickMenu(onlyOneChild)">
                <el-icon size="16">
                    <component v-if="onlyOneChild.meta.icon.indexOf('ep') !== -1" :is="onlyOneChild.meta.icon.slice(2)" />
                    <svg-icon v-if="onlyOneChild.meta.icon.indexOf('tjm') !== -1" :icon-class="onlyOneChild.meta.icon.slice(4)" />
                </el-icon>
                <template #title>{{ onlyOneChild.meta.title }}</template>
            </el-menu-item>
        </template>
        <el-sub-menu v-else :index="item.path">
            <template #title>
                <el-icon size="16">
                    <component v-if="item.meta.icon.indexOf('ep') !== -1" :is="item.meta.icon.slice(2)" />
                    <svg-icon v-if="item.meta.icon.indexOf('tjm') !== -1" :icon-class="item.meta.icon.slice(4)" />
                </el-icon>
                <span>{{ item.meta.title }}</span>
            </template>
            <sideBarItem v-for="(route, index) in item.children" :key="route.path + index" :item="route" />
        </el-sub-menu>
    </template>
</template>

<style lang="scss" scoped></style>