<template>
  <div :class="{'has-logo':showLogo}" @mouseenter="sideEnter" @mouseleave="sideLeave"
    :style="{ backgroundColor: settings.sideTheme === 'theme-dark' ? variables.menuBackground : variables.menuLightBackground }">
    <logo v-if="showLogo" :collapse="isCollapse" />
    <el-scrollbar :class="settings.sideTheme" wrap-class="scrollbar-wrapper">
      <el-menu :default-active="activeMenu" :default-openeds="comDefaultOpeneds" :collapse="isCollapse" :background-color="variables.menuBg"
        :text-color="variables.menuText" :unique-opened="false" :active-text-color="settings.theme" :collapse-transition="false" mode="vertical">
        <sidebar-item v-for="(route, index) of sideBarMenu" :key="route.path  + index" :is-collapse="isCollapse" :active-menu="activeMenu"
          :item="route" :base-path="route.path" :class="route.fixed&&route.fixed.isFixed?'sideFoot':''"
          :style="route.fixed&&route.fixed.isFixed?{'bottom': route.fixed.number*50+'px'}: bottomMenu&&index==routes.length-bottomMenu-2?{'padding-bottom': bottomMenu*50+'px'}:''"
          class="secondary-menu" />
      </el-menu>
    </el-scrollbar>
    <div v-show="isExpand" class="side-expand" @click="toggleSideBar">
      <img :src="isCollapse?require('@/assets/images/sidebar_right.png'):require('@/assets/images/sidebar_left.png')">
    </div>
  </div>
</template>

<script>
import { mapGetters, mapState } from "vuex";
import Logo from "./Logo";
import SidebarItem from "./SidebarItem";
import variables from "@/assets/styles/variables.scss";
import { addTreeLevel } from "@/utils";
import { cloneDeep } from "lodash-es";
import { isExternal } from '@/utils/validate';
import path from 'path';

export default {

  components: { SidebarItem, Logo },
  data() {
    return {
      isExpand: false,
      comDefaultOpeneds: [],
      sideBarMenu: []
    };
  },
  computed: {
    ...mapState(["settings"]),
    ...mapGetters(["sidebarRouters", "sidebar"]),
    activeMenu() {
      const route = this.$route;
      const { meta, path } = route;
      // if set path, the sidebar will highlight the path you set
      if (meta.activeMenu) {
        return meta.activeMenu;
      }
      return path;
    },
    device() {
      return this.$store.state.app.device;
    },
    bottomMenu() {
      const routeArr = this.$router.options.routes;
      const navFixed = routeArr.filter(item => item.fixed && item.fixed.isFixed);
      return navFixed.length;
    },
    showLogo() {
      return this.$store.state.settings.sidebarLogo;
    },
    variables() {
      return variables;
    },
    isCollapse() {
      return !this.sidebar.opened;
    },
  },
  watch: {
    sidebarRouters: {
      handler(newValue) {
        const result = this.hidechildren(newValue ? newValue : []);
        this.sideBarMenu = result;
        this.comDefaultOpeneds = this.findSubMenuIndex(result);
      },
      deep: true,
      immediate: true
    },
  },
  methods: {
    hidechildren(routes = []) {
      let temp = cloneDeep(routes);
      temp = addTreeLevel(temp);
      const result = temp.map(item => {
        if (item.children?.length) {
          item.children = item.children.filter(i => {
            if (typeof (i.hidden) == 'boolean' && i.hidden == false || i.path == "index") {
              return i;
            }
          });
        }
        return item;
      });
      return result;
    },
    findSubMenuIndex(menu) {
      let openeds = this.openTargetAllSubMenu(menu);
      if (openeds instanceof Array) {
        // 去重
        openeds = Array.from(new Set(openeds));
      }
      return openeds;
    },
    // 展开所有指定层级的菜单 默认二级
    openTargetAllSubMenu(_tempTree = [], level = 2) {
      // 组件外传入了值 使用传入值，否则默认获取二级菜单打开二级
      if (_tempTree instanceof Array && _tempTree.length) {
        // 递归查找当前二级目录index
        const result = this.findTargetLevelIndex(_tempTree, level, []);
        return result;
      }
    },
    findTargetLevelIndex(data = [], level = 2, result = []) {
      if (data.length) {
        for (const item of data) {
          // level大于传入level直接跳出循环
          if (item.level > level) break;
          // 确保打开菜单为目录
          if (item.level <= level && item.children instanceof Array) {
            if (item.path) {
              const path = this.resolvePath(item.path, item.path);
              path ? result.push(path) : null;
            }
          }
          if (item.children instanceof Array && item.children.length) {
            this.findTargetLevelIndex(item.children, level, result);
          }
        }
      }
      return result.map(item => this.createMenuIndex(item));
    },
    createMenuIndex(index) {
      if (index || index == "0") {
        return index.toString();
      }
    },
    resolvePath(routePath, basePath) {
      if (isExternal(routePath)) {
        return routePath;
      }
      if (isExternal(basePath)) {
        return basePath;
      }
      return path.resolve(basePath, routePath);
    },
    toggleSideBar() {
      this.$emit('handleBar', this.isCollapse ? '-96' : '96'); // 96为展开宽度和收起宽度之差
      this.$store.dispatch('app/toggleSideBar');
    },
    sideEnter() {
      if (this.device !== 'mobile') {
        this.isExpand = true;
      }
    },
    sideLeave() {
      if (this.device !== 'mobile') {
        this.isExpand = false;
      }
    },
  },
};
</script>
