<template>
  <div v-if="!item.hidden">
    <template v-if="hasOneShowingChild(item.children, item) && (!onlyOneChild.children || onlyOneChild.noShowingChildren) && !item.alwaysShow">
      <app-link :to="resolvePath(onlyOneChild.path, onlyOneChild.query)">
        <el-menu-item 
          style="height: 80px;" 
          :index="resolvePath(onlyOneChild.path)" 
          @click="handleNoChildrenClick(item)"
        >
          <svg-icon :icon-class="onlyOneChild.meta.icon || (item.meta && item.meta.icon)"/>
          <span class="menu-title" style="color: #fff;">{{ onlyOneChild.meta.title }}</span>
        </el-menu-item>
      </app-link>
    </template>

    <el-menu-item 
      v-else
      style="height: 80px;"
      :index="resolvePath(item.path)"
      @click="handleItemClick(item)"
    >
      <svg-icon :icon-class="item.meta && item.meta.icon" />
      <span class="menu-title" style="color: #fff;">{{ item.meta.title }}</span>
    </el-menu-item>
  </div>
</template>

<script setup>
import { isExternal } from '@/utils/validate'
import AppLink from './Link'
import { getNormalPath } from '@/utils/ruoyi'
import { ref } from 'vue'

const props = defineProps({
  // route object
  item: {
    type: Object,
    required: true
  },
  isNest: {
    type: Boolean,
    default: false
  },
  basePath: {
    type: String,
    default: ''
  }
})

const emit = defineEmits(['parent-click','no-children-click'])

const onlyOneChild = ref({})

function handleItemClick(item) {

  if (item.children && item.children.length > 0) {
    const visibleChildren = item.children.map(child => ({
      ...child,
      fullPath: getNormalPath(props.basePath + '/' + child.path) // 添加完整路径
    })).filter(child => !child.hidden)
    
    if (visibleChildren.length > 0) {
      emit('parent-click', visibleChildren)
    } else {
      emit('no-children-click')
    }
  } else {
    emit('no-children-click')
  }
  pageLuyou(item)
}

function handleNoChildrenClick(item) {
  emit('no-children-click')
  pageLuyou(item)
}

function pageLuyou(route) {
  console.log('导航到:', route)
}


function hasOneShowingChild(children = [], parent) {
  if (!children) {
    children = []
  }
  const showingChildren = children.filter(item => {
    if (item.hidden) {
      return false
    }
    onlyOneChild.value = item
    return true
  })

  if (showingChildren.length === 1) {
    return true
  }

  if (showingChildren.length === 0) {
    onlyOneChild.value = { ...parent, path: '', noShowingChildren: true }
    return true
  }

  return false
}

function resolvePath(routePath, routeQuery) {
  if (isExternal(routePath)) {
    return routePath
  }
  if (isExternal(props.basePath)) {
    return props.basePath
  }
  if (routeQuery) {
    let query = JSON.parse(routeQuery)
    return { 
      path: getNormalPath(props.basePath + '/' + routePath), 
      query: query 
    }
  }
  return getNormalPath(props.basePath + '/' + routePath)
}
</script>