<template>
  <div id="Sidebar">
    <el-row class="sidebar">
      <el-col :span="24" class="main">
        <el-col :span="24" class="one">
          <el-menu class="sidebar-el-menu" :default-active="onRoutes" :collapse="false" unique-opened router>
            <template v-for="item in items">
              <menu-item :key="item._id" :item="item"></menu-item>
            </template>
          </el-menu>
        </el-col>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import menuItem from './sidebar/menu-item.vue';
const { devMenu } = require('./data/menu');
import { mapState, createNamespacedHelpers } from 'vuex';
const { mapActions } = createNamespacedHelpers('menus');
import _ from 'lodash';
import bus from './bus';
export default {
  name: 'Sidebar',
  props: {},
  components: { menuItem },
  data: function () {
    return {
      collapse: false,
      items: [],
    };
  },
  created() {
    bus.$on('collapse', (msg) => {
      this.collapse = msg;
      bus.$emit('collapse-content', msg);
    });
  },
  methods: {
    ...mapActions(['query', 'userMenu']),
    async getMenu() {
      const menu = _.get(this.user, 'role.menu', {});
      const mode = _.get(menu, 'mode');
      if (mode === 'all') {
        await this.getAllMenu();
        if (this.$dev_env) this.items.unshift(...devMenu);
      } else await this.getUserMenu();
    },
    async getAllMenu() {
      const res = await this.query();
      if (this.$checkRes(res)) {
        this.$set(this, `items`, res.data);
      }
    },
    async getUserMenu() {
      const res = await this.userMenu();
      if (this.$checkRes(res)) {
        this.$set(this, `items`, res.data);
      }
    },
  },
  computed: {
    ...mapState(['user', 'menuList']),
    onRoutes() {
      return this.$route.path;
    },
  },
  metaInfo() {
    return { title: this.$route.meta.title };
  },
  watch: {
    user: {
      deep: true,
      immediate: true,
      handler(val) {
        if (_.get(val, 'role')) this.getMenu();
      },
    },
  },
};
</script>

<style lang="less" scoped>
.sidebar {
  display: block;
  position: absolute;
  left: 0;
  top: 60px;
  bottom: 0;
  overflow-y: scroll;
}
.sidebar::-webkit-scrollbar {
  width: 0;
}
.sidebar-el-menu:not(.el-menu--collapse) {
  width: 200px;
}
.sidebar > ul {
  height: 100%;
}
</style>
