<template>
  <div class="home">
    <div class="home-header">
      <div class="head-menu menu-list">
        <ul>
          <li
            v-for="(menu, index) in menus"
            :key="index"
            :class="[
              'menu-item',
              { 'menu-item-act': curMenu.url === menu.url }
            ]"
            @click="toMenu(menu)"
          >
            <i :class="menu.icon"></i>
            <span>{{ menu.name }}</span>
          </li>
        </ul>
      </div>
      <div class="head-user menu-list">
        <ul>
          <li v-if="schoolName" @click="toSelectSchool" title="切换学校">
            <i class="el-icon-s-home"></i>
            <span>{{ schoolName }}</span>
          </li>
          <li
            class="menu-item menu-item-account"
            @click="$refs.ResetPwd.open()"
          >
            <i class="icon icon-account"></i>
            <span :title="username">{{ username }}</span>
          </li>
          <li class="menu-item" @click="toLogout">
            <i class="icon icon-logout" title="退出登录"></i>
          </li>
        </ul>
      </div>
      <div class="head-menu-btn" @click="showMenu">
        <span><i class="el-icon-menu"></i></span>
      </div>
    </div>

    <div class="home-navs" v-if="curMenu.children">
      <div class="head-logo">
        <img v-if="schoolLogo" :src="schoolLogo" alt="分布式印刷" />
        <h1 v-else>分布式印刷</h1>
      </div>
      <div
        v-for="(submenu, sindex) in curMenu.children"
        :key="sindex"
        class="nav-part"
      >
        <div class="nav-head">
          <span>{{ submenu.name }}</span>
          <i class="nav-head-right-icon el-icon-caret-bottom"></i>
        </div>
        <ul class="nav-list">
          <li
            class="nav-item"
            v-for="(nav, navNo) in submenu.children"
            :key="navNo"
          >
            <div
              :class="[
                'nav-item-main',
                { 'nav-item-main-act': curActNav === nav.url }
              ]"
              @click="toNav(nav)"
            >
              <p class="nav-item-cont">{{ nav.name }}</p>
              <span
                class="nav-item-info"
                v-if="nav.url === 'WaitTask' && waitTaskCount"
                >{{ waitTaskCount }}</span
              >
            </div>
          </li>
        </ul>
      </div>
    </div>

    <div class="home-body">
      <div class="home-main">
        <div class="home-breadcrumb" v-if="breadcrumbs.length">
          <span class="breadcrumb-tips">
            <i class="icon icon-location"></i>
            <span>当前所在位置：</span>
          </span>
          <el-breadcrumb separator="/">
            <el-breadcrumb-item
              v-for="(bread, index) in breadcrumbs"
              :key="index"
              >{{ bread.title }}</el-breadcrumb-item
            >
          </el-breadcrumb>
        </div>

        <!-- home-view: page detail -->
        <div class="home-view">
          <router-view />
        </div>
      </div>
    </div>

    <!-- popover menu-->
    <el-dialog
      class="menu-dialog"
      :visible.sync="menuDailogIsShow"
      title="导航菜单"
      top="60px"
      fullscreen
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      append-to-body
    >
      <div
        class="home-navs home-navs-full"
        v-for="(curMenu, mainNo) in menus"
        :key="mainNo"
      >
        <div
          v-for="(submenu, sindex) in curMenu.children"
          :key="sindex"
          class="nav-part"
        >
          <div class="nav-head">
            <i :class="submenu.icon"></i>
            <span>{{ curMenu.name }} - {{ submenu.name }}</span>
          </div>
          <ul class="nav-list">
            <li
              class="nav-item"
              v-for="(nav, navNo) in submenu.children"
              :key="navNo"
            >
              <div
                :class="[
                  'nav-item-main',
                  { 'nav-item-main-act': curActNav === nav.url }
                ]"
                @click="toNav(nav)"
              >
                <p class="nav-item-cont">{{ nav.name }}</p>
                <span class="nav-item-icon nav-item-icon-right">
                  <i
                    :class="[
                      'icon',
                      curActNav === nav.url
                        ? 'icon-arrow-right-act'
                        : 'icon-arrow-right'
                    ]"
                  ></i>
                </span>
                <span
                  class="nav-item-info"
                  v-if="nav.url === 'WaitTask' && waitTaskCount"
                  >{{ waitTaskCount }}</span
                >
              </div>
            </li>
          </ul>
        </div>
      </div>
      <div class="menu-logout" @click="toLogout">
        <i class="el-icon-switch-button"></i>
      </div>
    </el-dialog>

    <!-- 修改密码 -->
    <reset-pwd ref="ResetPwd"></reset-pwd>
  </div>
</template>

<script>
import { mapState, mapActions } from "vuex";
import localNavs from "@/constants/navs";
import { deepCopy } from "@/plugins/utils";
import { sysMenu, logout } from "../modules/login/api";
import ResetPwd from "../modules/base/components/ResetPwd";
import { SYS_ADMIN_NAME } from "@/constants/enumerate";

export default {
  name: "home",
  components: { ResetPwd },
  data() {
    const IS_SUPER_ADMIN =
      this.$ls.get("user", { loginName: "" }).loginName === SYS_ADMIN_NAME;

    return {
      menus: [],
      curMenu: { url: "", children: [] },
      curActNav: "",
      breadcrumbs: [],
      validRoutes: [],
      username: this.$ls.get("user", { realName: "" }).realName,
      userRoles: this.$ls.get("user", { roleList: [] }).roleList,
      schoolLogo: this.$ls.get("schoolLogo"),
      schoolName: this.$ls.get("schoolName"),
      menuDailogIsShow: false,
      IS_SUPER_ADMIN
    };
  },
  watch: {
    $route(val) {
      if (val.name === "Home") return;
      this.actCurNav();
    }
  },
  computed: {
    ...mapState("exam", ["waitTaskCount"])
  },
  created() {
    this.getMenus();
  },
  methods: {
    ...mapActions("exam", ["updateWaitTaskCount"]),
    getMenus1() {
      this.menus = localNavs;
      if (this.$route.name === "Home") {
        this.$router.replace({
          name: "CampusManage"
        });
      } else {
        this.actCurNav();
      }
    },
    async getMenus() {
      const data = await sysMenu();
      this.initPrivilegeMap(data.privileges);
      const { menus, firstRouter } = this.menusToTree(data.privileges);
      this.menus = menus;

      if (this.$route.name === "Home") {
        this.$router.replace({
          name: firstRouter
        });
        return;
      } else {
        if (!this.validRoutes.includes(this.$route.name)) {
          this.$router.replace({
            name: "404"
          });
          return;
        }

        this.actCurNav();
      }
    },
    initPrivilegeMap(data) {
      let privilegeMap = {};
      const pageSetTypes = ["conditions", "buttons", "lists", "links"];
      data.forEach(item => {
        const isPage = pageSetTypes.some(
          type => item[type] && item[type].length
        );
        if (!isPage) return;
        privilegeMap[item.url] = [];
        pageSetTypes.forEach((type, index) => {
          if (item[type] && item[type].length) {
            item[type].forEach(elem => {
              privilegeMap[item.url].push(
                `${elem.type}_${elem.url}`.toLowerCase()
              );
            });
          }
        });
      });
      this.$store.commit("setPrivilegeMap", privilegeMap);
      this.$ls.set("privilegeMap", privilegeMap);
    },
    menusToTree(menus) {
      let navTree = deepCopy(localNavs);
      let validRoutes = [];
      let validMenuDict = {};
      let firstRouter = "";
      menus.forEach(item => (validMenuDict[item.url] = item.name));

      const anchorNav = menus => {
        let list = [];
        menus.forEach(item => {
          const routerOrName = item.url;
          if (!validMenuDict[routerOrName]) return;

          if (!firstRouter && item.isRouter) firstRouter = item.url;
          item.name = validMenuDict[routerOrName];
          validRoutes.push(routerOrName);
          let navItem = { ...item };
          if (item["children"]) {
            navItem.children = anchorNav(item.children);
          }
          list.push(navItem);
        });
        return list;
      };

      this.validRoutes = validRoutes;

      return { menus: anchorNav(navTree), firstRouter };
    },
    toMenu(menu) {
      if (this.curMenu.url === menu.url) return;
      this.curMenu = menu;
      const firstRouter = menu.children[0].children[0];
      this.toNav(firstRouter);
    },
    toNav(nav) {
      if (nav.url === this.$route.name) return;
      this.curActNav = nav.url;
      this.$router.push({ name: nav.url });
      this.menuDailogIsShow = false;
    },
    actCurNav() {
      const routerName = this.$route.name;
      let breadcrumbs = [];
      const getRouterPath = (navs, pathList) => {
        navs.forEach(nav => {
          let navPathList = [...pathList];
          if (breadcrumbs.length) return;
          if (nav.url === routerName) {
            breadcrumbs = [
              ...navPathList,
              { title: nav.name, router: nav.url, isRouter: true }
            ];
            return;
          } else {
            navPathList = [
              ...navPathList,
              {
                title: nav.name,
                router: nav.url,
                isRouter: !!nav.isRouter
              }
            ];
            if (nav["children"]) {
              getRouterPath(nav.children, navPathList);
            }
          }
        });
      };

      getRouterPath(this.menus, []);

      const curRouter = breadcrumbs.find(item => item.isRouter);
      this.curActNav = curRouter.router;
      this.curMenu = this.menus.find(
        menu => menu.url === breadcrumbs[0].router
      );

      this.breadcrumbs = breadcrumbs;

      if (
        this.validRoutes.includes("WaitTask") &&
        this.curMenu.url === "exam"
      ) {
        this.updateWaitTaskCount();
      }
    },
    toLogout() {
      this.$confirm("确定要退出登录吗？", "提示", {
        type: "warning"
      })
        .then(() => {
          this.logoutAction();
        })
        .catch(() => {});
    },
    async logoutAction() {
      await logout();
      this.$ls.clear();
      this.$router.push({ name: "Login" });
    },
    toSelectSchool() {
      if (this.IS_SUPER_ADMIN) this.$router.push({ name: "SelectSchool" });
    },
    // popover menu
    showMenu() {
      this.menuDailogIsShow = !this.menuDailogIsShow;
    },
    toNavDetail(mainNo, subNo) {
      this.toNav(subNo);
      this.showMenu();
    }
  }
};
</script>
