<!--
 * @Description: In User Settings Edit
 * @Author: your name
 * @Date: 2019-03-20 14:31:43
 * @LastEditTime: 2019-10-28 10:32:41
 * @LastEditors: Please set LastEditors
 -->
<template>
  <div class="zte-menu" :class="{ 'is-collapse': isCollapse }">
    <div class="menu-title" v-if="search">
      <template>
        <svg-icon v-if="!isCollapse" key="open" icon-class="menu-open" @click.native="isCollapse = !isCollapse"></svg-icon>
        <svg-icon v-else key="close" icon-class="menu-close" @click.native="isCollapse = !isCollapse"></svg-icon>
      </template>
      <el-cascader
        v-if="!isCollapse"
        expand-trigger="hover"
        :options="cascaderOptions"
        :show-all-levels="false"
        placeholder="搜索"
        v-model="menuSelected"
        filterable
        clearable
        @change="handleCascaderChange">
      </el-cascader>
    </div>
    <el-scrollbar class="menu-sroll">
      <el-menu
        class="menu-vertical"
        ref="menu"
        router
        unique-opened
        :collapse="isCollapse"
        :default-active="activeMenu">
        <template v-for="(sub, index) in menus">
          <el-submenu :index="index.toString()" v-if="sub.children && sub.children.length" :key="sub.name">
            <template slot="title">
              <svg-icon :icon-class="sub.icon || ''"></svg-icon>
              <span v-text="sub.name" slot="title"></span>
            </template>
            <el-menu-item
              :title="item.name"
              v-for="item in sub.children"
              :key="item.name"
              :index="item.url"
            >
              <span v-text="item.name" slot="title"></span>
            </el-menu-item>
          </el-submenu>
          <el-menu-item
            :title="sub.name"
            :index="sub.url"
            :key="sub.name"
            v-else>
            <span v-text="sub.name" slot="title"></span>
          </el-menu-item>
        </template>
      </el-menu>
    </el-scrollbar>
  </div>
</template>

<script>
import svgIcon from './svg-icon';

export default {
  name: 'zteMenu',
  components: {
    svgIcon,
  },
  props: {
    menus: {
      type: Array,
      default: () => ([]),
    },
    search: {
      type: Boolean,
      default: true,
    },
  },
  data() {
    return {
      activeIndex: this.$route.path,
      isCollapse: false,
      menuSelected: [],
    };
  },
  computed: {
    activeMenu() {
      return this.$route.fullPath.replace('/', '');
    },
    cascaderOptions() {
      const options = this.menus.map(opt => ({
        label: opt.name,
        value: opt.id,
        children: (opt.children || []).map(child => ({ label: child.name, value: child.url })),
      }));
      return options;
    },
  },
  watch: {
    '$route'(to) {
      this.activeIndex = to.path;
    },
  },
  methods: {
    handleCascaderChange(value) {
      if (value.length === 2) {
        this.$router.push(`/${value[1]}`);
      }
    },
  },
};
</script>

