<!-- 侧边栏 license by http://eleadmin.com -->
<template>
  <div class="ele-admin-sidebar ele-scrollbar-hide">
    <slot name="top"/>
    <div class="ele-admin-sidebar-menus">
      <a-menu
        v-if="useDeep"
        mode="inline"
        :theme="theme"
        :open-keys="openKeys"
        :selected-keys="active"
        :inline-collapsed="collapse"
        :inline-indent="inlineIndent"
        @openChange="onOpenChange">
        <template v-for="m in data">
          <ele-pro-sidebar-item v-if="!m.meta.hide" :key="m.path" :item="m"/>
        </template>
      </a-menu>
      <ele-pro-sidebar-menus
        v-else
        :data="data"
        mode="inline"
        :theme="theme"
        :open-keys="openKeys"
        :selected-keys="active"
        :inline-collapsed="collapse"
        :inline-indent="inlineIndent"
        @openChange="onOpenChange"/>
    </div>
    <slot name="bottom"/>
  </div>
</template>

<script>
import EleProSidebarItem from '../../ele-pro-sidebar-item';
import EleProSidebarMenus from '../../ele-pro-sidebar-menus';

export default {
  name: 'EleProSidebar',
  components: {EleProSidebarItem, EleProSidebarMenus},
  props: {
    // 菜单数据
    data: Array,
    // 菜单选中
    active: Array,
    // 主题, light | dark
    theme: String,
    // 展开的key
    menuOpens: Array,
    // 是否折叠
    collapse: Boolean,
    // 是否只保持一个子菜单展开
    uniqueOpen: Boolean,
    // 菜单缩进
    inlineIndent: {
      type: Number,
      default: 16
    },
    // 是否使用递归渲染菜单
    useDeep: Boolean
  },
  data() {
    return {
      // 侧栏展开的key
      openKeys: this.collapse ? [] : this.menuOpens,
      // 侧栏展开的key备份
      openKeysCopy: this.menuOpens
    };
  },
  methods: {
    /* 子级展开事件 */
    onOpenChange(keys) {
      if (this.collapse) {
        this.openKeys = keys;
      } else {
        if (this.uniqueOpen && keys.length && (keys.length > this.openKeysCopy.length)) {
          const cks = keys.filter((k) => !this.openKeysCopy.some((t) => (k === t)));
          this.openKeysCopy = this.getTreeKeys(this.data, cks[0]) || [];
        } else {
          this.openKeysCopy = keys;
        }
        this.openKeys = this.openKeysCopy;
      }
    },
    /* 获取key及所有父级key */
    getTreeKeys(data, key, pks) {
      if (!pks) {
        pks = [];
      }
      for (let i = 0; i < data.length; i++) {
        const d = data[i];
        if (d.path === key) {
          return pks.concat([key]);
        } else if (d.children && d.children.length) {
          const ks = this.getTreeKeys(d.children, key, pks.concat([d.path]));
          if (ks) {
            return ks;
          }
        }
      }
    }
  },
  watch: {
    collapse() {
      if (this.collapse) {
        this.openKeys = [];
      } else {
        this.openKeys = this.openKeysCopy;
      }
    },
    menuOpens() {
      this.openKeysCopy = this.menuOpens;
      if (!this.collapse) {
        this.openKeys = this.openKeysCopy;
      }
    }
  }
}
</script>
