<template>
  <el-scrollbar wrap-class="scrollbar-wrapper">
    <el-menu
      :show-timeout="200"
      :default-active="$route.path"
      :collapse="isCollapse"
      :background-color="variables.menuBg"
      :text-color="variables.menuText"
      :active-text-color="variables.menuActiveText"
      mode="vertical"
    >
      <template v-for="route in routes">
        <sidebar-item :key="route.path" :item="route" :base-path="route.path" />
      </template>
    </el-menu>
  </el-scrollbar>
</template>

<script>
import { mapGetters } from "vuex";
import { gatewayUserRouters } from "@/api/login";
import variables from "@/styles/variables.scss";
import SidebarItem from "./SidebarItem";

export default {
  components: { SidebarItem },

  data() {
    return {
      routes: []
    };
  },

  computed: {
    ...mapGetters(["sidebar"]),

    variables() {
      return variables;
    },

    isCollapse() {
      return !this.sidebar.opened;
    }
  },

  mounted() {
    gatewayUserRouters().then(res => {
      let routes = this.$router.options.routes;
      let showList = res.result.data;
      this.mapRoutes(routes, showList);
    });
  },

  methods: {
    mapRoutes: function(routes, showList) {
      for (var i = 0; i < routes.length; i++) {
        for (var j = 0; j < showList.length; j++) {
          if (routes[i].name == showList[j].key) {
            routes[i].hidden = false;
            routes[i].meta = {
              title: showList[j].name,
              icon: "chart"
            };

            if (routes[i].children && routes[i].children.length > 0) {
              this.mapRoutes(routes[i].children, showList);
              break;
            }
            break;
          } else {
            routes[i].hidden = true;
          }
        }
      }

      this.routes = routes;
    }
  }
};
</script>
