<template>
  <template v-if="menuItem.children">
    <MenuItem v-if="hasOneChild(menuItem.children, menuItem)" :path="singleChild.path" :meta="singleChild.meta" :default-icon="defaultIcon"></MenuItem>
    <el-sub-menu v-else :index="currPath" class="custom-base-sub-menu">
      <template #title>
        <svg-icon v-if="menuItem.meta.icon || defaultIcon" class="animated custom-base-icon" :icon-name="menuItem.meta.icon || defaultIcon"></svg-icon>
        <span class="custom-base-sub-menu__title">{{ menuItem.meta.title }}</span>
      </template>
      <template v-for="child in menuItem.children">
        <sidebar-item v-if="!child.hidden && !isLimitLevel && child.children" :menuItem="child" :key="child.path" :base-path="currPath" :default-icon="defaultIcon"></sidebar-item>
        <MenuItem v-else-if="!child.hidden" :path="resolvePath(currPath, child.path)" :meta="child.meta" :key="`${child.path1}`" :default-icon="defaultIcon"></MenuItem>
      </template>
    </el-sub-menu>
  </template>
  <MenuItem v-else :path="currPath" :meta="menuItem.meta"></MenuItem>
</template>

<script>
import { resolvePath } from 'utils/resolvePath'
import MenuItem from './MenuItem.vue'
export default {
  components: {
    MenuItem
  },
  name: 'SidebarItem',
  data() {
    return {
      singleChild: {}
    }
  },
  props: {
    menuItem: {
      type: Object
    },
    basePath: {
      type: String
    },
    isLimitLevel: {
      type: Boolean
    },
    defaultIcon: {
      type: String
    }
  },
  computed: {
    currPath() {
      return this.resolvePath(this.basePath, this.menuItem.path)
    }
  },
  methods: {
    resolvePath(basePath, routePath) {
      return resolvePath(basePath, routePath)
    },
    hasOneChild(children, parent) {
      if (children.length === 1 && !parent.meta.alwaysShow) {
        this.singleChild = children[0]
        return true
      }
      return false
    }
  }
}
</script>

<style lang="scss" scoped>
.custom-base-sub-menu {
  :deep(.#{$namespace}-sub-menu__title) {
    margin: 4px 0;
  }
  .custom-base-icon {
    font-size: 16px !important;
    margin-right: 10px;
    color: var(--custom-base-color-text);
  }
  :deep(.#{$namespace}-menu) {
    background-color: var(--custom-base-color-background-sub) !important;
    color: var(--custom-base-color-text);
  }
  &:hover,
  &.is-active {
    :deep(.#{$namespace}-sub-menu__title) {
      .custom-base-sub-menu__title {
        color: var(--custom-base-color-text-selected);
      }
      & > .#{$namespace}-sub-menu__icon-arrow {
        color: var(--custom-base-color-text-selected);
      }
    }
    .custom-base-icon {
      animation-name: swing;
      color: var(--custom-base-color-text-selected);
    }
  }
}
</style>
