<template>
  <div style="height: 100%;">
    <el-button :icon="isCollapse ? 'iconfont icon-icon-shouqizhankai1' : 'iconfont icon-icon-shouqizhankai'" @click="collapseChange" class="collapse-btn"></el-button>
    <el-menu
      ref="sideMenu"
      router
      :default-active="activeMenu"
      :default-openeds="defaultKeys"
      :collapse="isCollapse"
      :collapse-transition="false"
      @select="handleSelect"
    >
      <!--使用字段 show 控制是否展示菜单-->
      <template v-for="(item, index) in filteredMenu">
        <!-- 无子页面 -->
        <el-menu-item
          v-if="!item.children && (item.show || item.name === '首页')"
          :key="index"
          :index="`${index}`"
          :route="item.route"
        >
          <i class="iconfont" :class="item.iconClass"></i>
          <span slot="title">{{item.name}}</span>
        </el-menu-item >
        <!-- 有子页面 -->
        <el-submenu :index="`${index}`" v-if="item.show && item.children" :key="index">
          <template slot="title">
            <i class="iconfont" :class="item.iconClass"></i>
            <span slot="title">{{item.name}}</span>
          </template>
          <template v-for="(subitem, subindex) in item.children">
            <el-menu-item
              v-if="subitem.show"
              :key="subindex"
              :index="`${index}-${subindex}`"
              :route="subitem.route"
            >{{subitem.name}}</el-menu-item>
          </template>
        </el-submenu>
      </template>
    </el-menu>
  </div>
</template>

<script>
import { createNamespacedHelpers } from 'vuex'
import MENU from '@/config/menu.js'

const { mapState } = createNamespacedHelpers('framework')
export default {
  name: 'Side',
  computed: {
    ...mapState(['activeMenu', 'openMenuId', 'restoredSideMenuItem']),
  },
  created () {
    this.getMenu()
  },
  mounted () {
    this.$store.commit('framework/setRootMenu', this.$refs.sideMenu.items)
  },
  watch: {
    restoredSideMenuItem (val) {
      // console.log(this.$refs.sideMenu, val)
      // 恢复关闭菜单的路由信息
      this.$refs.sideMenu.items[val.index].route.name = val.immutableName
    },
  },
  data () {
    return {
      isCollapse: false,
      permissionMenu: [], // 带权限的目录数据
      MENU,
      filteredMenu: [], // 过滤后的数据
      defaultKeys: [],
      filteredRouters: [], // 过滤后的路由名
    }
  },
  methods: {
    // 判断是否显示目录
    filterMenu (wholeArr, limitedArr) {
      wholeArr.map((item, index) => {
        limitedArr.map((oldItem, oldIndex) => {
          // 条件: 旧系统一级菜单就判断 text 一致, 旧系统二级菜单就判断路径包含 originalUrl, 新系统业务直接 show: true
          const condition = item.show || (oldItem.mainmenu ? item.name === oldItem.mainmenu.text : oldItem.url.includes(item.originalUrl))
          if (condition) {
            item.show = true
            if (item.children) {
              this.filterMenu(item.children, limitedArr[oldIndex].submenu)
            } else {
              !this.filteredRouters.includes(item.route.name) && this.filteredRouters.push(item.route.name)
            }
          }
        })
      })
    },
    // 获取目录
    getMenu () {
      const url = this.$API.menu
      this.$https.get(url)
        .then(data => {
          this.permissionMenu = JSON.parse(data)
        })
        .then(() => {
          const menu = JSON.parse(JSON.stringify(this.MENU)) // copy一份
          this.filterMenu(menu, this.permissionMenu) // 改变了menu, 产生了filteredRouters
          this.filteredMenu = menu
          window.localStorage.setItem('filteredRouters', JSON.stringify(this.filteredRouters))
        })
    },
    // 选择目录
    handleSelect (keyPath, keyPathArr, vmNode) {
      // 在三级子页面的话, 设置缓存, 便于点击菜单回归时保持在子页面而不是回到二级主列表页面
      if (this.$route.matched.length >= 3) {
        const currItem = vmNode.rootMenu.items[this.activeMenu]
        if (currItem.route.name !== this.$route.name) {
          !currItem.immutableName && (currItem.immutableName = currItem.route.name)
          currItem.route.name = this.$route.name // 更新路由名, 便于回来时还在路由
          console.log(currItem)
        }
      }

      const pathArr = keyPath.split('-')
      const index = pathArr[0]
      const route = this.MENU[index] // 一级路由面包屑
      // let title = route.name
      let breadcrumb = [route]
      let subRoute

      if (pathArr.length > 1) {
        const subIndex = pathArr[1]
        const subMenus = route.children
        subRoute = subMenus[subIndex] // 二级子路由面包屑
        // title = subRoute.name
        breadcrumb.push(subRoute)
      }
      // 添加顶部标签页
      this.$store.commit('framework/addTabControlMenu', {
        index: keyPath,
        route: vmNode.route,
        name: vmNode.$el.innerText,
        immutableName: vmNode.immutableName, // 原始路由名, 设置即不变
      })
      this.$store.commit('framework/changeBreadcrumb', breadcrumb)
      this.$nextTick(() => {
        // 存入激活的id
        this.$store.commit('framework/changeActiveMenu', keyPath)
        // 点击时存入当前展开的菜单id
        this.$store.commit('framework/changeOpenMenuId', index)
      })
    },
    // 展开收起变化
    collapseChange () {
      this.isCollapse = !this.isCollapse
      this.$emit('collapseChange', this.isCollapse)
    }
  },
}
</script>

<style scoped lang="scss">
  .collapse-btn {
    width: 100%;
    height: 50px; // 与 content 导航栏一样高
    color:#909399;
  }
  .el-menu {
    width: 100%;
    height: calc(100% - 50px);
    overflow-x: hidden;
    overflow-y: auto;
    border-right: none;
    .iconfont {
      margin-right: 10px;
      font-size: 20px;
    }
    &.el-menu--collapse {
      /deep/
      .el-submenu__title, .el-menu-item {
        text-align: center;
        .iconfont {
          margin-right: initial;
          font-size: 20px;
        }
      }
    }
  }
</style>
