<template>
  <div class="home">
    <div class="home-header">
      <div class="head-logo">
        <img v-if="schoolLogo" :src="schoolLogo" alt="分布式印刷" />
        <h1 v-else>分布式印刷</h1>
      </div>
      <div class="head-menu menu-list">
        <ul>
          <li
            v-for="(menu, index) in menus"
            :key="index"
            :class="[
              'menu-item',
              { 'menu-item-act': curMenu.name === menu.name }
            ]"
            @click="toMenu(menu)"
          >
            <i :class="menu.icon"></i>
            <span>{{ menu.title }}</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="el-icon-s-custom"></i>
            <span :title="username">{{ username }}</span>
          </li>
          <li class="menu-item" @click="toLogout">
            <i class="el-icon-switch-button"></i>
            <span>退出登录</span>
          </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
        v-for="(submenu, sindex) in curMenu.children"
        :key="sindex"
        class="nav-part"
      >
        <div class="nav-head">
          <i :class="submenu.icon"></i>
          <span>{{ submenu.title }}</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.router }
              ]"
              @click="toNav(nav)"
            >
              <p class="nav-item-cont">{{ nav.title }}</p>
              <span class="nav-item-icon nav-item-icon-right">
                <i
                  :class="[
                    'icon',
                    curActNav === nav.router
                      ? 'icon-arrow-right-act'
                      : 'icon-arrow-right'
                  ]"
                ></i>
              </span>
              <span
                class="nav-item-info"
                v-if="nav.router === '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">
          <el-breadcrumb separator=">">
            <el-breadcrumb-item>
              <i class="el-icon-s-home" style="margin-top: -2px;"></i>
            </el-breadcrumb-item>
            <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.title }} - {{ submenu.title }}</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.router }
                ]"
                @click="toNav(nav)"
              >
                <p class="nav-item-cont">{{ nav.title }}</p>
                <span class="nav-item-icon nav-item-icon-right">
                  <i
                    :class="[
                      'icon',
                      curActNav === nav.router
                        ? 'icon-arrow-right-act'
                        : 'icon-arrow-right'
                    ]"
                  ></i>
                </span>
                <span
                  class="nav-item-info"
                  v-if="nav.router === '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: { name: "" },
      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.getMenus1();
  },
  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);
      const { menus, firstRouter } = this.menusToTree(data);
      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 = ["querys", "buttons", "columns", "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(`${type}_${elem.url}`.toLowerCase());
            });
          }
        });
      });
      this.$store.dispatch("setPrivilegeMap", 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["router"] || item["name"];
          if (!validMenuDict[routerOrName]) return;

          if (!firstRouter && item["router"]) firstRouter = item["router"];
          item.title = 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) {
      this.curMenu = menu;
      const firstRouter = menu.children[0].children[0];
      this.toNav(firstRouter);
    },
    toNav(nav) {
      if (nav.router === this.$route.name) return;
      this.curActNav = nav.router;
      this.$router.push({ name: nav.router });
      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["router"] === routerName) {
            breadcrumbs = [
              ...navPathList,
              { title: nav.title, router: nav.router, isRouter: true }
            ];
            return;
          } else {
            const routerOrName = nav["router"] || nav["name"];
            navPathList = [
              ...navPathList,
              {
                title: nav.title,
                router: routerOrName,
                isRouter: !!nav["router"]
              }
            ];
            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.name === breadcrumbs[0].router
      );

      this.breadcrumbs = breadcrumbs;

      if (
        this.validRoutes.includes("WaitTask") &&
        this.curMenu.name === "exam"
      ) {
        this.updateWaitTaskCount(this.userRoles);
      }
    },
    toLogout() {
      this.$confirm("确定要退出登录吗？", "提示", {
        cancelButtonClass: "el-button--danger is-plain",
        confirmButtonClass: "el-button--primary",
        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>
