<template>
  <el-scrollbar class="menu_scroll scrollbar">
    <el-menu
      :default-active="activeLink"
      :default-openeds="openMenu"
      :unique-opened="true"
      router
      class="shopmall-sidebar"
    >
      <el-menu-item
        v-for="(item,index) in menu"
        v-if="item.children&&item.children.length === 0"
        :key="index"
        :index="resolvePath(item.path)"
      >
        <span slot="title">{{ item.name&&item.name }}</span>
      </el-menu-item>
      <el-submenu v-else-if="item.children&&item.children.length > 0" :index="item.path">
        <template slot="title">
          <span slot="title">{{ item.name&&item.name }}</span>
        </template>
        <el-menu-item-group v-for="(child,ind) in item.children" :key="ind">
          <el-menu-item
            :index="resolvePath(item.path,child.path)"
          >
            {{ child.name&&child.name }}
          </el-menu-item>
        </el-menu-item-group>
      </el-submenu>
    </el-menu>
  </el-scrollbar>
</template>

<script>
import path from 'path'
export default {
  name: 'Sidebar',
  props: {
    sidebarData: {
      type: Array,
      default() {
        return {}
      }
    }
  },
  data() {
    return {
      openMenu: [],
      istrue: 0,
      menu: [],
      activeLink: ''
    }
  },
  computed: {
    // activeLink: {
    //   get() {
    //     if (this.$route.matched && this.$route.matched.length > 1) {
    //       if (this.$route.matched[1].meta.path) {
    //         return path.resolve(this.$route.matched[0].path, this.$route.matched[1].meta.path)
    //       } else {
    //         return this.$route.path
    //       }
    //     }
    //   },
    //   set(path) {
    //     return path
    //   }
    // }
  },
  watch: {
    $route: {
      handler(to) {
        // 路由选中的方法，这种方法有问题，临时解决，如果有时间后期需要改掉
        // 原理是，因为可以跳转的菜单只有二级菜单，且只有二级菜单，超出二级就会有问题，只有一级理论上应该没事，但是没有测试，后期会测到
        if (to.matched && to.matched.length > 1) {
          if (to.matched[0].path && to.matched[1].meta && to.matched[1].meta.path) {
            this.activeLink = path.resolve(to.matched[0].path, to.matched[1].meta && to.matched[1].meta.path)
            return
          }
          this.activeLink = to.matched[1].path
        } else {
          this.activeLink = to.path
        }
      },
      immediate: true
    },
    'sidebarData': {
      handler(val) {
        this.menu = val
        this.menu.forEach((item) => {
          this.openMenu.push(item.path)
        })
      },
      immediate: true
    }
  },
  created() {
  },
  methods: {
    handleClose(key, keyPath) {
    },
    handleChange(index) {
      this.istrue = index
      this.$router.push({
        path: this.menu[index].path
      })
    },
    resolvePath(...paths) {
      return path.resolve(...paths)
    }
  }
}
</script>

<style scoped lang="less">
.menu_scroll {
  height: 600px;
}
</style>
