<template>
  <el-menu :default-active="activeIndex" @select="handleSelect" ref="asideMenu">
    <template v-for="el in menu">
      <!-- 有子菜单 -->
      <el-submenu
        v-if="el.isShow != 0 && Array.isArray(el.children) && el.children.filter(v => { return v.isShow } ).length > 0"
        popper-class="dm-menu-submenu"
        :key="el.menuId"
        :index="`${el.menuId}`">
        <template slot="title">
          <i :class="['menu-icon', el.iconUrl]"></i>
          <span class="menu-text">{{el.menuName}}</span>
        </template>
        <template v-for="item in el.children">
          <!-- 子菜单 -->
          <el-menu-item v-if="item.isShow != 0" :key="item.menuId" :index="`${el.menuId}-${item.menuId}`">
            <i :class="['menu-icon', item.iconUrl]"></i>
            <span class="menu-text" slot="title">{{item.menuName}}</span>
          </el-menu-item>
        </template>
      </el-submenu>
      <!-- 无子菜单 -->
      <el-menu-item v-else-if="el.isShow != 0" :key="el.menuId" :index="`${el.menuId}`">
        <i :class="['menu-icon', el.iconUrl]"></i>
        <span class="menu-text" slot="title">{{el.menuName}}</span>
      </el-menu-item>
    </template>
  </el-menu>
</template>

<script>
import { mapState } from 'vuex';
export default {
  name: 'AsideMenu',
  data() {
    return {
      menuFlat: [],
      parentdIds: [],
      activeIndex: ''
    };
  },
  methods: {
    flat(menu) {
      menu.forEach(el => {
        this.menuFlat.push(el);
        if (Array.isArray(el.children) && el.children.length > 0) {
          this.flat(el.children);
        }
      });
    },
    /**
     * 一级菜单下无二级菜单时，需要配置projectUrl和menuUrl
     * 一级菜单下有二级菜单时，无需配置projectUrl和menuUrl
     * @param {string} index
    */
    handleSelect(index) {
      let projectUrl = window.location.pathname;
      projectUrl = projectUrl.split('/')[1];
      projectUrl = `/${projectUrl}`;
      const menuIds = index.split('-');
      const menuId = menuIds.length > 1 ? menuIds[1] : menuIds[0];
      const menu = this.menuFlat.filter(el => el.menuId == menuId)[0] || {};
      // 一级菜单的menuUrl或者二级菜单的menuUrl
      let menuUrl = menu.menuUrl || '';
      // 一级菜单的projectUrl或者二级菜单的projectUrl
      let menuProjectUrl = menu.projectUrlForWeb;

      if (menuIds.length > 1) {
        // 点击二级菜单，如果二级菜单下有三级菜单，取出第一个三级菜单作为跳转路径
        const thirdMenu = menu.children || [];
        if (thirdMenu[0] && thirdMenu[0].menuUrl) {
          // 二级菜单下第一个三级菜单的menuUrl
          menuUrl = thirdMenu[0].menuUrl;
          // 二级菜单下第一个三级菜单的projectUrl
          menuProjectUrl = thirdMenu[0].projectUrlForWeb;
        }
      }
      // UI需求，新切页面时只能展开自己的tab，其余的close
      this.menu.map(el => {
        if (Array.isArray(el.children) && el.children.length > 0 && el.menuId != menuIds[0]) {
          if(el.children.some(v => v.isShow)) {
            this.$refs.asideMenu.close(`${el.menuId}`);
          }
        }
      });
      if (projectUrl === menuProjectUrl) {
        this.$router.push(menuUrl.replace('/#', ''));
      } else {
        window.location.href = `${menuProjectUrl}${menuUrl}`;
      }
    },
    // 设置选中的left tab
    getActiveIndex() {
      // warn：要filter掉不显示的菜单
      const act = this.menu.find(v => {
        if(v.children && v.children.filter(v => { return v.isShow; }).length) {
          const c = v.children.find(child => {
            return child.menuUrl === this.$route.path || child.menuUrl === this.$route.meta.path;
          });
          if(c) {
            return true;
          }
        } else {
          return v.menuUrl === this.$route.path || v.menuUrl === this.$route.meta.path;
        }
      });
      if (act) {
        if (act.children && act.children.filter(v => { return v.isShow; }).length) {
          // 有子菜单
          const children = act.children.find(v => {
            return v.menuUrl === this.$route.path || v.menuUrl === this.$route.meta.path;
          });
          this.activeIndex = `${act.menuId}-${children.menuId}`;
        } else {
          // 无子菜单
          this.activeIndex = `${act.menuId}`;
        }
      }
    },
  },
  computed: {
    ...mapState([
      'routePath',
      'menuCode',
      'project'
    ]),
    menu() {
      const { project } = this;
      if(project == '' || project == 'index') {
        return [];
      }
      const code = project.includes('card') ? 'card' : 'gift';
      const currentRoute = this.routePath.filter(v => v.menuCode.includes(code));
      return currentRoute || [];
    }
  },
  watch: {
    'menu': {
      handler() {
        // 拿到菜单数据后，先把多维数组转为一维数组
        this.flat(this.menu.slice());
        this.getActiveIndex();
      },
      deep: true,
      immediate: true,
    },
    '$route.path': {
      handler() {
        this.getActiveIndex();
      }
    }
  }
};
</script>
