<template>
  <template v-for="item in rootItems" :key="item.id">
    <el-sub-menu v-if="hasChildren(item.id)" :index="item.id.toString()">
      <template #title>
        <el-icon><Document /></el-icon>
        <span>{{ item.label }}</span>
      </template>
      <template v-for="child in getChildren(item.id)" :key="child.id">
        <el-sub-menu v-if="hasChildren(child.id)" :index="child.id.toString()">
          <template #title>
            <el-icon><Document /></el-icon>
            <span>{{ child.label }}</span>
          </template>
          <el-menu-item
            v-for="grandChild in getChildren(child.id)"
            :key="grandChild.id"
            :index="grandChild.id.toString()"
          >
            <el-icon><Document /></el-icon>
            <span>{{ grandChild.label }}</span>
          </el-menu-item>
        </el-sub-menu>
        <el-menu-item v-else :index="child.id.toString()">
          <el-icon><Document /></el-icon>
          <span>{{ child.label }}</span>
        </el-menu-item>
      </template>
    </el-sub-menu>
    <el-menu-item v-else :index="item.id.toString()">
      <el-icon><Document /></el-icon>
      <span>{{ item.label }}</span>
    </el-menu-item>
  </template>
</template>

<script lang="ts">
import { defineComponent, PropType, computed } from "vue";
import type { HelpDoc } from "@/api/help";
import { Document } from "@element-plus/icons-vue";

export default defineComponent({
  name: "RecursiveMenu",
  components: {
    Document
  },
  props: {
    items: {
      type: Array as PropType<HelpDoc[]>,
      required: true
    }
  },
  setup(props) {
    const rootItems = computed(() => {
      return props.items.filter(item => item.parentId === 0);
    });
    const getChildren = (parentId: number) => {
      return props.items.filter(item => item.parentId === parentId);
    };
    const hasChildren = (parentId: number) => {
      return props.items.some(item => item.parentId === parentId);
    };
    return {
      rootItems,
      getChildren,
      hasChildren
    };
  }
});
</script>
