<template>
  <div :class="['home', { 'home-page-main': IS_HOME_PAGE }]">
    <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="[
                'icon',
                MENU_ICONS[menu.url]
                  ? `icon-${MENU_ICONS[menu.url]}`
                  : 'icon-workspace'
              ]"
            ></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="toResetPwd">
            <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>

    <div class="home-navs">
      <div class="head-logo">
        <div class="head-logo-content">
          <img v-if="schoolLogo" :src="schoolLogo" :alt="APP_TITLE" />
          <h1 v-else>{{APP_TITLE}}</h1>
        </div>
      </div>

      <el-menu
        v-if="curMenu.children && curMenu.children.length"
        class="el-menu-home"
        active-text-color="#3a5ae5"
        text-color="#434656"
        router
        :default-active="curRouteName"
        :default-openeds="curSubMenuNames"
      >
        <template v-for="submenu in curMenu.children">
          <el-submenu
            v-if="submenu.children && submenu.children.length"
            :key="submenu.id"
            :index="submenu.url"
          >
            <span slot="title">{{ submenu.name }}</span>
            <el-menu-item
              v-for="nav in submenu.children"
              :key="nav.id"
              :index="nav.url"
              :route="{ name: nav.url }"
            >
              <span>{{ nav.name }}</span>
              <span
                class="nav-item-info"
                v-if="nav.url === 'WaitTask' && waitTaskCount"
                >{{ waitTaskCount }}</span
              >
            </el-menu-item>
          </el-submenu>
          <el-menu-item
            v-else
            :key="submenu.id"
            :index="submenu.url"
            :route="{ name: submenu.url }"
          >
            <span>{{ submenu.name }}</span>
          </el-menu-item>
        </template>
      </el-menu>
    </div>

    <div class="home-body">
      <div class="home-body-content">
        <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 in breadcrumbs" :key="bread.url">{{
              bread.name
            }}</el-breadcrumb-item>
          </el-breadcrumb>
        </div>

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

    <!-- 修改密码 -->
    <reset-pwd
      :user-info="userInfo"
      ref="ResetPwd"
      @modified="resetPwdModified"
    ></reset-pwd>
  </div>
</template>

<script>
import { mapState, mapActions } from "vuex";
import localMenus from "@/constants/menus-data";
import { sysMenu, logout } from "../modules/login/api";
import ResetPwd from "../modules/base/components/ResetPwd";
import { SYS_ADMIN_NAME } from "@/constants/enumerate";
import staticMenu from "../constants/staticMenu";
import { APP_TITLE } from "@/constants/app";

const MENU_ICONS = {
  base: "base",
  exam: "exam",
  customer: "customer",
  stmms: "book"
};
const HOME_PAGE_ROUTE = "HomePage";

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

    return {
      MENU_ICONS,APP_TITLE,
      privileges: [],
      menus: [],
      curMenu: { url: "", children: [] },
      curRouteName: "",
      curSubMenuNames: [],
      breadcrumbs: [],
      validRoutes: [],
      username: user.realName,
      userRoles: user.roleList,
      schoolLogo: this.$ls.get("schoolLogo"),
      schoolName: this.$ls.get("schoolName"),
      userInfo: {
        pwdCount: 0,
        mobileNumber: 1,
        userId: user.id
      },
      IS_SUPER_ADMIN
    };
  },
  watch: {
    $route(val) {
      if (val.name === "Home") return;
      if (this.$route.name === HOME_PAGE_ROUTE) {
        return;
      }

      this.routerChange();
    }
  },
  computed: {
    ...mapState("exam", ["waitTaskCount"]),
    IS_HOME_PAGE() {
      return this.$route.name === HOME_PAGE_ROUTE;
    }
  },
  created() {
    // this.initData1();
    this.initData();
  },
  methods: {
    ...mapActions("exam", ["updateWaitTaskCount"]),
    initData1() {
      // 开发阶段专用
      this.initPrivilegeMap(localMenus);
      this.privileges = this.transformMenu(localMenus);
      this.menus = this.getMenu();

      if (this.IS_HOME_PAGE) return;

      if (this.$route.name === "Home") {
        this.$router.replace({
          name: HOME_PAGE_ROUTE
        });
        return;
      }

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

      this.updateBreadcrumbs();
      const curMenu = this.menus.find(
        menu => menu.url === this.breadcrumbs[0].url
      );
      this.menuChange(curMenu);
      if (
        this.validRoutes.includes("WaitTask") &&
        this.curMenu.url === "exam"
      ) {
        this.updateWaitTaskCount();
      }
    },
    async initData() {
      const data = await sysMenu();
      const privileges = [...staticMenu, ...data.privileges];
      this.initPrivilegeMap(privileges);
      this.privileges = this.transformMenu(privileges);
      this.menus = this.getMenu();

      if (this.IS_HOME_PAGE) return;

      if (this.$route.name === "Home") {
        this.toMenu(this.menus[0]);
        // if (this.IS_SUPER_ADMIN) {
        //   this.toMenu(this.menus[0]);
        // } else {
        //   this.$router.replace({
        //     name: HOME_PAGE_ROUTE
        //   });
        // }
        return;
      }

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

      this.updateBreadcrumbs();
      const curMenu = this.menus.find(
        menu => menu.url === this.breadcrumbs[0].url
      );
      this.menuChange(curMenu);

      if (
        this.validRoutes.includes("WaitTask") &&
        this.curMenu.url === "exam"
      ) {
        this.updateWaitTaskCount();
      }
    },
    transformMenu(list) {
      return list.map(item => {
        return {
          id: item.id,
          parentId: item.parentId,
          name: item.name,
          type: item.type,
          url: item.url
        };
      });
    },
    getMenu() {
      const getChildren = id => {
        return this.privileges
          .filter(item => item.parentId === id)
          .map(item => {
            return { ...item };
          });
      };

      let menus = getChildren("-1");
      let validRoutes = [];
      const toTree = menus => {
        menus.forEach(menu => {
          const children = getChildren(menu.id);
          if (children.length) {
            menu.children = children;
            toTree(menu.children);
          } else {
            validRoutes.push(menu.url);
          }
        });
      };
      toTree(menus);

      this.validRoutes = validRoutes;
      // console.log(JSON.stringify(menus));
      return menus;
    },
    getCurMenuFirstRouter() {
      let firstRouteName = "";
      let menu = this.curMenu;
      while (menu) {
        firstRouteName = menu.url;
        menu = menu.children && menu.children[0];
      }

      return firstRouteName;
    },
    initPrivilegeMap(data) {
      let privilegeMap = {};
      const pageSetTypes = ["conditions", "buttons", "lists", "links"];
      data.forEach(item => {
        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);
    },
    menuChange(menu) {
      this.curMenu = menu;

      this.curSubMenuNames = this.privileges
        .filter(item => item.parentId === menu.id)
        .map(item => item.url);
    },
    toMenu(menu) {
      if (menu.url === HOME_PAGE_ROUTE) {
        if (this.$route.name !== HOME_PAGE_ROUTE) {
          this.curMenu = menu;
          this.$router.push({
            name: HOME_PAGE_ROUTE
          });
        }
        return;
      }
      if (this.curMenu.url === menu.url) return;
      this.menuChange(menu);
      const firstRouteName = this.getCurMenuFirstRouter();
      this.$router.replace({
        name: firstRouteName
      });
    },
    updateBreadcrumbs() {
      this.curRouteName = this.$route.name;
      let breadcrumbs = [];
      let curBreadcrumb = this.privileges.find(
        item => item.url === this.curRouteName
      );
      breadcrumbs.push({ ...curBreadcrumb });

      while (curBreadcrumb && curBreadcrumb.parentId !== "-1") {
        curBreadcrumb = this.privileges.find(
          item => item.id === curBreadcrumb.parentId
        );
        if (curBreadcrumb) breadcrumbs.unshift({ ...curBreadcrumb });
      }

      this.breadcrumbs = breadcrumbs;
    },
    routerChange() {
      this.updateBreadcrumbs();
      if (!this.curMenu.url) {
        // 从HomePage快捷菜单跳转过来的
        const curMenu = this.menus.find(
          menu => menu.url === this.breadcrumbs[0].url
        );
        this.menuChange(curMenu);
      }

      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" });
    },
    toResetPwd() {
      if (this.IS_SUPER_ADMIN) return;
      this.$refs.ResetPwd.open();
    },
    resetPwdModified() {
      this.logoutAction();
    },
    // other
    getSubMenus(menu) {
      return this.privileges.filter(
        m => m.parentId === menu.id && m.type === "MENU"
      );
    },
    getFirstRouter() {
      let childNavs = this.privileges;
      let firstRouteName = "";
      while (childNavs.length) {
        firstRouteName = childNavs[0].url;
        childNavs = this.privileges.filter(
          item => item.parentId === childNavs[0].id
        );
      }

      return firstRouteName;
    }
  }
};
</script>
