<template>
  <div v-if="!item.hidden">
    <template v-if="hasOneShowingChild(item.children,item) && (!onlyOneChild.children||onlyOneChild.noShowingChildren)&&!item.alwaysShow">
      <app-link
        v-if="onlyOneChild.meta"
        :id="`appLink_${item.id}`"
        :to="resolvePath(onlyOneChild.path, onlyOneChild.meta)"
        :item="item"
      >
        <el-tooltip
          v-if="tooltip && enableTip"
          :content="onlyOneChild.meta.title"
          class="item"
          effect="dark"
          placement="right"
        >
          <el-menu-item
            ref="menuItem"
            :class="{'submenu-title-noDropdown':!isNest}"
            :index="item.name || item.path"
            class="submenu_nowrap"
          >
            <item
              :icon="onlyOneChild.meta.icon||(item.meta&&item.meta.icon)"
              :title="onlyOneChild.meta.title"
            />
          </el-menu-item>
        </el-tooltip>
        <el-menu-item
          v-else
          ref="menuItem"
          :class="{'submenu-title-noDropdown':!isNest}"
          :index="item.name || item.path"
          class="submenu_nowrap hideToolTip"
        >
          <item
            :icon="onlyOneChild.meta.icon||(item.meta&&item.meta.icon)"
            :title="onlyOneChild.meta.title"
          />
        </el-menu-item>
      </app-link>
    </template>

    <el-submenu
      v-else
      ref="subMenu"
      :index="item.name || item.path"
      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"
        :is-nest="true"
        :item="child"
        :base-path="resolvePath(child.path)"
        class="nest-menu"
      />
    </el-submenu>
  </div>
</template>

<script>
import path from 'path'
import { isExternal } from 'ecip-web/utils/validate'
import Item from './Item'
import AppLink from './Link'
import FixiOSBug from './FixiOSBug'

export default {
  name: 'SidebarItem',
  components: { Item, AppLink },
  mixins: [FixiOSBug],
  props: {
    tooltip: {
      type: Boolean,
      required: false,
      default: true
    },
    item: {
      type: Object,
      required: true
    },
    isNest: {
      type: Boolean,
      default: false
    },
    basePath: {
      type: String,
      default: ''
    }
  },
  data() {
    // TODO: refactor with render function
    this.onlyOneChild = null
    return {
      enableTip: false
    }
  },

  mounted() {
    this.setTooltip()
  },

  methods: {
    hasOneShowingChild(children = [], parent) {
      const showingChildren = children.filter((item) => {
        if (item.hidden) {
          return false
        } else {
          // Temp set(will be used if only has one showing child)
          this.onlyOneChild = item
          return true
        }
      })

      // When there is only one child router, the child router is displayed by default
      if (showingChildren.length === 1) {
        return true
      }

      // Show parent if there are no child router to display
      if (showingChildren.length === 0) {
        this.onlyOneChild = { ...parent, path: '', noShowingChildren: true }
        return true
      }

      return false
    },
    resolvePath(routePath, meta) {
      if (meta && meta.isIframe) {
        const name = this.item.name
        return `/iframe?name=${name}&src=${this.item.meta.iframeUrl}`
      }
      if (isExternal(routePath)) {
        return routePath
      }
      if (isExternal(this.basePath)) {
        return this.basePath
      }
      return path.resolve(this.basePath, routePath)
    },
    getStyle(dom, attr) {
      return dom.currentStyle
        ? dom.currentStyle[attr]
        : getComputedStyle(dom, false)[attr]
    },
    setTooltip() {
      // 当前菜单
      setTimeout(() => {
        const menuItemDom = document.querySelector(
          '#appLink_' + this.item.id + ' li'
        )
        if (!menuItemDom) {
          return
        }

        // 获取菜单栏sidebar的宽度
        const sidebarWidth = document.querySelector('.ec-sidebar').clientWidth

        // 获取菜单的可用宽度
        const menuItemWidth = menuItemDom.clientWidth || sidebarWidth
        const menuItemPaddingLeft = Number(
          this.getStyle(menuItemDom, 'paddingLeft').replace(/\s+|px/gi, '')
        )
        const menuItemPaddingRight = Number(
          this.getStyle(menuItemDom, 'paddingRight').replace(/\s+|px/gi, '')
        )
        const menuItemAvailableWidth =
          menuItemWidth - menuItemPaddingLeft - menuItemPaddingRight

        // 获取icon的使用宽度
        const menuItemIconDom =
          menuItemDom.querySelector('i') ||
          menuItemDom.querySelector('svg-icon')
        let menuItemIconWidth = 0
        if (menuItemIconDom) {
          const menuItemIconFontSize =
            this.getStyle(menuItemIconDom, 'fontSize').replace(
              /\s+|px/gi,
              ''
            ) || 14
          menuItemIconWidth = menuItemIconDom
            ? Math.max(menuItemIconFontSize, menuItemIconDom.offsetWidth) +
              Number(
                this.getStyle(menuItemIconDom, 'marginLeft').replace(
                  /\s+|px/gi,
                  ''
                )
              ) +
              Number(
                this.getStyle(menuItemIconDom, 'marginRight').replace(
                  /\s+|px/gi,
                  ''
                )
              )
            : 14
        }

        // 获取文本所需要的宽度
        const menuItemTitleDom = menuItemDom.querySelector('span')
        let menuItemTitleNeedWidth = 0
        if (menuItemTitleDom) {
          const menuItemTitleContentLength = menuItemTitleDom.innerHTML.length
          const menuItemTitleFontSize =
            this.getStyle(menuItemTitleDom, 'fontSize').replace(
              /\s+|px/gi,
              ''
            ) || 14
          menuItemTitleNeedWidth =
            menuItemTitleContentLength * menuItemTitleFontSize +
            Number(
              this.getStyle(menuItemTitleDom, 'marginLeft').replace(
                /\s+|px/gi,
                ''
              )
            ) +
            Number(
              this.getStyle(menuItemTitleDom, 'marginRight').replace(
                /\s+|px/gi,
                ''
              )
            )
        }

        this.enableTip =
          menuItemAvailableWidth - menuItemIconWidth - 5 <
          menuItemTitleNeedWidth
      }, 500)
    }
  }
}
</script>

<style lang="scss" scoped>
@import '../../../styles/element-variables.scss';
.submenu_nowrap {
  text-overflow: ellipsis;
  overflow: hidden;
  white-space: nowrap;
}

::v-deep {
  .nest-menu .el-menu-item {
    padding-right: 10px;
  }

  .el-menu-item {
    padding-right: 10px;
  }
}

.ec-sidebar--primary .ec-sidebar__menu.el-menu .el-menu-item.is-active {
  color: #fff;
  background-color: rgba(0, 0, 0, 0.3) !important;
}

.ec-sidebar--dark .ec-sidebar__menu.el-menu .el-menu-item.is-active {
  color: #fff;
  background-color: #636c7c;
}

.ec-sidebar--bright .ec-sidebar__menu.el-menu .el-menu-item.is-active {
  background-color: #89c6fd80;
}
</style>
