<template>
  <div :class="{'has-logo':showLogo}">
    <logo v-if="showLogo" :collapse="isCollapse" />
    <el-scrollbar wrap-class="scrollbar-wrapper">
      <el-menu
        :default-active="activeMenu"
        :collapse="isCollapse"
        :background-color="variables.menuBg"
        :text-color="variables.menuText"
        :unique-opened="false"
        :active-text-color="variables.menuActiveText"
        :collapse-transition="false"
        mode="vertical"
        @select="handleSelect"
      >
        <sidebar-item v-for="route in routes" :key="route.path" :item="route" :base-path="route.path" />
        <el-submenu index="100">
          <template slot="title">
            <svg-icon icon-class="data" />
            <span slot="title" @mouseover="getGlobalInterface">数据中心</span>
          </template>
          <el-menu-item index="/data/upload-file">jar包管理</el-menu-item>
          <el-submenu v-for="(myMenu,index) in menu" :key="myMenu.menuName" :index="'100-' + index">
            <template slot="title">{{ myMenu.menuName }}</template>
            <el-menu-item v-for="(subMenu,index2) in myMenu.subMenus" :key="subMenu.path" :index="getIndex(index,index2)" @click="handleClick(subMenu)">{{ subMenu.subMenuName }}</el-menu-item>
          </el-submenu>
        </el-submenu>
      </el-menu>
    </el-scrollbar>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import Logo from './Logo'
import SidebarItem from './SidebarItem'
import variables from '@/styles/variables.scss'
import { getGlobalInterface } from '@/api/data.js'

export default {
  components: { SidebarItem, Logo },
  computed: {
    ...mapGetters([
      'sidebar',
      'menu'
    ]),
    routes() {
      return this.$router.options.routes
    },
    activeMenu() {
      const route = this.$route
      const { meta, path } = route
      // if set path, the sidebar will highlight the path you set
      if (meta.activeMenu) {
        return meta.activeMenu
      }
      return path
    },
    showLogo() {
      return this.$store.state.settings.sidebarLogo
    },
    variables() {
      return variables
    },
    isCollapse() {
      return !this.sidebar.opened
    }
  },
  mounted() {
    this.getGlobalInterface()
  },
  methods: {
    handleSelect(key, keypath) {
      switch (key) {
        case '/data/upload-file':
          this.$router.push({ name: 'jar包管理' })
          break
      }
    },
    handleClick(subMenu) {
      this.$store.dispatch('data/setSubMenu', subMenu)
      this.$router.push({ name: '动态数据' })
    },
    getGlobalInterface() {
      getGlobalInterface()
        .then(res => {
          this.$store.dispatch('data/setMenu', res.data)
          this.$store.dispatch('data/setSubMenu', res.data[0].subMenus[0])
        })
    },
    getIndex(index, index2) {
      if (index + index2 === 0) {
        return '/data/item'
      }
      return '100-' + index + '-' + index2
    }
  }
}
</script>
