<template>
  <div v-if="!item.hidden">
    <template v-if="!item.children">
      <app-link :to="resolvePath(item)">
        <el-menu-item :index="resolvePath(item)">
          <item :icon="item.meta.icon" :title="item.meta.title"/>
        </el-menu-item>
      </app-link>
    </template>

    <template v-else-if="isOnlyOneChildMenu()">
      <app-link :to="resolvePath(getOnlyOneChildMenu())">
        <el-menu-item :index="resolvePath(getOnlyOneChildMenu())">
          <item :icon="getOnlyOneChildMenu().meta.icon" :title="getOnlyOneChildMenu().meta.title"/>
        </el-menu-item>
      </app-link>
    </template>

    <el-submenu v-else :index="resolvePath(item)" popper-append-to-body>
      <template slot="title">
        <item v-if="item.meta" :icon="item.meta && item.meta.icon" :title="item.meta.title"/>
      </template>
      <sidebar-item v-for="child in item.children"
                    :key="child.path"
                    :item="child"
                    :base-path="resolvePath(child)"/>
    </el-submenu>
  </div>
</template>

<script>
import {isExternal} from '@/utils/validate'
import Item from './Item'
import AppLink from './Link'
import FixiOSBug from './FixiOSBug'

export default {
  name: 'SidebarItem',
  components: {Item, AppLink},
  mixins: [FixiOSBug],
  props: {
    item: {
      type: Object,
      required: true
    },
    basePath: {
      type: String,
      default: ''
    }
  },
  methods: {
    // 判断是否仅有一个可显示的菜单
    isOnlyOneChildMenu() {
      return this.item.children.filter(item => !item.hidden).length === 1;
    },

    // 获取这个唯一的可显示菜单
    getOnlyOneChildMenu() {
      return this.item.children.filter(item => !item.hidden)[0];
    },

    resolvePath(router) {
      if (isExternal(router.path)) {
        return router.path
      } else if (isExternal(this.basePath)) {
        return this.basePath;
      } else if (router.path.indexOf(":") >= 0) {
        return router.meta.activePath
      } else {
        return router.path
      }
    }
  }
}
</script>
