<!--
 * @Author: WangJiaCheng
 * @Date: 2021-05-07 16:07:56
 * @LastEditors: WangJiaCheng
 * @LastEditTime: 2021-05-07 17:41:55
 * @Description:
-->
<template>
  <div
    v-if="!item.meta || !item.meta.hidden"
    :class="[isCollapse ? 'simple-mode' : 'full-mode']"
  >
    <template v-if="theOnlyOneChild && !theOnlyOneChild.children">
      <side-item-link
        v-if="theOnlyOneChild.meta"
        :to="resolvePath(theOnlyOneChild.path)"
      >
        <el-menu-item
          :index="resolvePath(theOnlyOneChild.path)"
          :class="{'submenu-title-noDropdown': isFirstLevel}"
        >
          <span
            v-if="theOnlyOneChild.meta.title"
            slot="title"
          >{{ theOnlyOneChild.meta.title }}</span>
        </el-menu-item>
      </side-item-link>
    </template>
    <el-submenu
      v-else
      :index="resolvePath(item.path)"
      popper-append-to-body
    >
      <template slot="title">
        <span
          v-if="item.meta && item.meta.title"
          slot="title"
        >{{ item.meta.title }}</span>
      </template>
      <template v-if="item.children">
        <side-item
          v-for="child in item.children"
          :key="child.path"
          :item="child"
          :is-collapse="isCollapse"
          :is-first-level="false"
          :base-path="resolvePath(child.path)"
          class="nest-menu"
        />
      </template>
    </el-submenu>
  </div>
</template>

<script>
import path from 'path'

import SideItemLink from './SideItemLink'

export default {
  name: 'SideItem',
  components: {
    SideItemLink
  },
  props: {
    isCollapse: Boolean,
    basePath: String,
    isFirstLevel: {
      type: Boolean,
      default: true
    },
    item: {
      type: Object,
      default() {
        return {}
      }
    }
  },
  computed: {
    showingChildNumber() {
      if (this.item.children) {
        const showingChildren = this.item.children.filter(c => {
          if (c.meta && c.meta.hidden) {
            return false
          }
          return true
        })
        return showingChildren.length
      }
      return 0
    },
    theOnlyOneChild() {
      if (this.showingChildNumber > 1) {
        return null
      }
      if (this.item.children) {
        for (const child of this.item.children) {
          if (!child.meta || !child.meta.hidden) {
            return child
          }
        }
      }
      return { ...this.item, path: '' }
    }
  },
  methods: {
    resolvePath(routePath) {
      return path.resolve(this.basePath, routePath)
    }
  }
}
</script>

<style lang="less">

</style>
