<template>
  <div class="menu-wrapper">
    <template v-for="item in routes">
      <template v-if="!item.hidden&&item.children">
        <router-link
          v-if="hasOneShowingChildren(item.children) && getShowingChildren(item.children[0].children)==0 &&!item.alwaysShow"
          :to="item.path+'/'+item.children[0].path"
          :key="item.children[0].name">
          <el-menu-item :index="item.path+'/'+item.children[0].path" :class="{'submenu-title-noDropdown':!isNest}">
            <svg-icon v-if="item.meta&&item.meta.icon"
                      :name="item.meta.icon"></svg-icon>
            <span v-if="item.children[0].meta&&item.children[0].meta.title" slot="title">{{generateTitle(item.children[0].meta.title)}}</span>
          </el-menu-item>
        </router-link>

        <el-submenu v-else :index="item.name||item.path" :key="item.name">
          <template slot="title">
            <svg-icon v-if="item.meta&&item.meta.icon" :name="item.meta.icon"></svg-icon>
            <span v-if="item.meta&&item.meta.title" slot="title">{{generateTitle(item.meta.title)}}</span>
          </template>

          <template v-for="child in item.children">
            <template v-if="!child.hidden">
              <sidebar-item :is-nest="true" class="nest-menu" v-if="child.children&&child.children.length>0"
                            :routes="[child]" :key="child.path"></sidebar-item>

              <router-link v-else :to="item.path+'/'+child.path" :key="child.name">
                <el-menu-item :index="item.path+'/'+child.path">
                  <svg-icon v-if="child.meta&&child.meta.icon" :name="child.meta.icon"></svg-icon>
                  <span v-if="child.meta&&child.meta.title" slot="title">{{generateTitle(child.meta.title)}}</span>
                </el-menu-item>
              </router-link>
            </template>
          </template>
        </el-submenu>
      </template>
    </template>
  </div>
</template>

<script>
  export default {
    name: 'SidebarItem',
    props: {
      routes: {
        type: Array
      },
      isNest: {
        type: Boolean,
        default: false
      }
    },
    methods: {
      getShowingChildren (children) {
        if (children === undefined) return 0;
        const showingChildren = children.filter(item => {
          return !item.hidden
        })
        return showingChildren.length;
      },
      hasOneShowingChildren (children) {
        const showingChildren = children.filter(item => {
          return !item.hidden
        })
        if (showingChildren.length === 1) {
          return true
        }
        return false
      },
      generateTitle (title) {
        const hasKey = this.$te('route.' + title)
        const translatedTitle = this.$t('route.' + title)
        if (hasKey) {
          return translatedTitle
        }
        return title
      }
    }
  }
</script>
