<template>
  <div>
    <el-submenu v-if="item.children.length > 0" ref="subMenu" :index="item.uri" popper-append-to-body>
      <template slot="title">
        <item :icon="item && item.icon" :title="item.title" />
      </template>
      <sidebar-item v-for="child in item.children" :key="child.uri" :is-nest="true" :item="child"
        :base-path="child.uri" />
    </el-submenu>
    <router-link v-else :to="{ name: item.uri }">
      <el-menu-item @click="openMenuItem(item)" :index="item.uri" :class="{ 'submenu-title-noDropdown': !isNest }">
        <item :icon="item.icon" :title="item.title" />
      </el-menu-item>
    </router-link>
  </div>
</template>

<script>
import path from 'path'
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: {
    // route object
    item: {
      type: Object,
      required: true
    },
    isNest: {
      type: Boolean,
      default: false
    },
    basePath: {
      type: String,
      default: ''
    }
  },
  data() {
    this.onlyOneChild = null
    return {}
  },
  methods: {
    openMenuItem(chmenu) {
      const obj = {
        name: chmenu.title,
        path: chmenu.uri,
        id: chmenu.id
      }
      this.$store.commit('user/ADD_TABS', obj)
    },
    hasOneShowingChild(children = [], parent) {
      const showingChildren = children.filter(item => {
        if (item.hidden) {
          return false
        } else {
          this.onlyOneChild = item
          return true
        }
      })
      if (showingChildren.length === 1) {
        return true
      }
      if (showingChildren.length === 0) {
        this.onlyOneChild = { ...parent, path: '', noShowingChildren: true }
        return true
      }
      return false
    },
    resolvePath(routePath) {
      if (isExternal(routePath)) {
        return routePath
      }
      if (isExternal(this.basePath)) {
        return this.basePath
      }
      return path.resolve(this.basePath, routePath)
    }
  }
}
</script>
