<template>
  <div class="hb-layout" v-loading="fullLoading.visible">
    <main-menu ref="mainMenu" :menu-list="menuList" :actived-code="activedMenu.length > 0 ? activedMenu[0].menuCode : ''" @showLoading="onShowLoading"></main-menu>
    <aside-menu v-show="showAside" :menu-list="activedMenu.length > 0 ? activedMenu[0].childList : []" :actived-code="activedMenu.length > 2 ? activedMenu[2].menuCode : ''"></aside-menu>
    <div class="hb-layout-content" :style="{ width: showAside ? 'calc(100% - 206px)' : '100%' }">
      <bread-menu v-if="activedMenu.length > 3" :menu-list="activedMenu.slice(2)"></bread-menu>
      <div class="hb-layout-pager" :style="{ height: activedMenu.length > 3 ? `calc(100% - 30px)` : '100%', 'padding-bottom': pagePaddingBottom }">
        <!-- 页面内容 -->
        <!-- <router-view v-if="activeBrand" :brandId="activeBrand" :activeGroupId="activeGroup" :tabType="activeTab" @showTab="showTab"></router-view> -->
        <keep-alive>
          <router-view :brand-id="enterpriseId" v-if="$route.meta.keepAlive"></router-view>
        </keep-alive>
        <router-view v-if="!$route.meta.keepAlive" :brand-id="enterpriseId"></router-view>
      </div>
    </div>
  </div>
</template>

<script>
import { getRequest } from '@/api/api.js';
import errorMsg from '@/common/js/error.js';
import MainMenu from './main-menu.vue';
import AsideMenu from './aside-menu.vue';
import BreadMenu from './bread-menu.vue';
let provideData = { layoutVm: {} };
export default {
  name: 'DmHbLayout',
  components: { MainMenu, AsideMenu, BreadMenu },
  provide: () => provideData,
  props: {
    // 菜单树数据
    menuList: {
      type: Array,
      default: () => []
    },
    pageRight: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      showAside: true,
      pagePaddingBottom: null,
      enterpriseId: '',
      // 菜单平铺数据
      flatMenuList: [],
      // 侧边栏菜单数据
      asideMenu: [],
      // 激活的菜单
      activedMenu: [],
      fullLoading: {
        visible: false,
        timer: null
      }
    };
  },
  watch: {
    menuList: {
      immediate: true,
      handler(list) {
        this.flatMenuList = this.getFlatMenuList(list);
        this.activedMenu = this.getActivedMenu(this.getMenuByPath(this.$route.path.slice(1)));
      }
    }
  },
  created() {
    this.$router.beforeEach((to, from, next) => {
      this.activedMenu = this.getActivedMenu(this.getMenuByPath(to.path.slice(1)));
      next();
    });
    provideData.layoutVm = this;
    this.enterpriseId = JSON.parse(sessionStorage.getItem('userInfos') || '{}').enterpriseId;
    this.$on('command', this.onCommand);
    this.getEnterpriseSecret();
  },
  methods: {
    getEnterpriseSecret() {
      if (this.$route.path == '/enterpriseSet') return;
      getRequest('/haoban-manage3-web/is-wx-enterprise-secret-set', {}).then(res => {
        const { errorCode, result } = res.data || {};
        if (errorCode != 1) {
          errorMsg.errorMsg(res.data);
          return;
        }
        if (!result) {
          this.$confirm('提示', '请先完成商户初始化设置后，再进行其他操作', {
            type: 'warning',
            cancelButtonText: '忽略',
            confirmButtonText: '去完成'
          }).then(() => {
            this.$router.push('/enterpriseSet');
          });
        }
      });
    },
    getFlatMenuList(menuList) {
      return menuList.reduce((list, el) => {
        if (Array.isArray(el.childList)) {
          list = list.concat(this.getFlatMenuList(el.childList));
        }
        list.push(el);
        return list;
      }, []);
    },
    getActivedMenu(menu) {
      if (!menu.menuCode) return [];
      let result = [menu];
      const parentMenu = this.flatMenuList.find(el => el.menuCode == menu.parentCode) || {};
      if (parentMenu.menuCode) {
        result = [...this.getActivedMenu(parentMenu), ...result];
      }
      return result;
    },
    getMenuByPath(path) {
      return this.pageRight.find(el => el.regexp.test('/' + path)) || {};
    },
    onShowLoading(loading) {
      if (loading) {
        this.fullLoading.visible = true;
        if (this.timer) {
          clearTimeout(this.fullLoading.timer);
          this.fullLoading.timer = null;
        }
      } else {
        // loading取消时，延迟半秒钟
        this.fullLoading.timer = setTimeout(() => {
          this.fullLoading.visible = false;
        }, 500);
      }
    },
    onCommand(command) {
      const methods = {
        updateApplyCount: () => this.$refs.mainMenu.updateAplyCount(),
        showAside: () => (this.showAside = true),
        hideAside: () => (this.showAside = false)
      };
      if (typeof methods[command] == 'function') {
        methods[command]();
      }
    }
  }
};
</script>

<style lang="scss" scoped>
.hb-layout {
  display: flex;
  flex-wrap: wrap;
  justify-content: flex-start;
  align-items: flex-start;
  width: 100%;
  min-width: 1440px;
  height: 100vh;
  background: #f2f3f5;
  box-sizing: border-box;
  overflow: hidden;
  overflow-x: auto;
  .hb-layout-content {
    padding-top: 20px;
    height: calc(100vh - 60px);
    box-sizing: border-box;
    .hb-layout-pager {
      height: 100%;
      background: #fff;
      overflow: auto;
      box-sizing: border-box;
    }
  }
}
</style>
