<template>
  <template v-if="depth > 10">
    <el-menu-item disabled>
      <span>{{ t('menu.menuTooDeep') }}</span>
    </el-menu-item>
  </template>
  
  <el-sub-menu v-else-if="hasChildren" :index="indexValue">
    <template #title>
      <span>{{ t(item.menu_name) }}</span>
    </template>
    <template v-for="child in children" :key="child.id">
      <sidebar-item 
        :item="child" 
        :menu-data="menuData" 
        :depth="depth + 1" 
      />
    </template>
  </el-sub-menu>

  <el-menu-item 
    v-else 
    :index="indexValue" 
    :route="item.menu_url || undefined"
  >
    <span>{{ t(item.menu_name) }}</span>
  </el-menu-item>
</template>

<script setup>
import { defineProps, computed } from 'vue'
import { useI18n } from 'vue-i18n'

const { t } = useI18n()

const props = defineProps({
  item: {
    type: Object,
    required: true,
    default: () => ({})
  },
  menuData: {
    type: Array,
    required: true,
    default: () => []
  },
  depth: {
    type: Number,
    default: 1
  }
})

// 计算索引值，优先使用menu_url，否则使用id
const indexValue = computed(() => {
  return props.item.menu_url || String(props.item.id);
})

// 获取子菜单
const children = computed(() => {
  return props.menuData
    .filter(child => 
      child.parent_id === props.item.id && 
      child.id !== props.item.id // 防止自引用
    )
    .sort((a, b) => a.id - b.id); // 按ID排序
})

// 判断是否有子菜单
const hasChildren = computed(() => {
  return children.value.length > 0;
})
</script>
