<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="[
                '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="知学知考" />
          <h1 v-else>知学知考</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>
            </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-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 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 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 { getAuthInfo } from "../plugins/auth";
import { autoSubmitForm } from "../plugins/utils";

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

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

    return {
      MENU_ICONS,
      privileges: [],
      menus: [],
      curMenu: { url: "", children: [] },
      curRouteName: "",
      curSubMenuNames: [],
      breadcrumbs: [],
      validRoutes: [],
      username: user.realName,
      userRoles: user.roleList,
      appSource: user.appSource,
      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;
      this.routerChange();
    }
  },
  created() {
    this.initData();
  },
  methods: {
    initData1() {
      // 开发阶段专用
      this.initPrivilegeMap(localMenus);
      this.privileges = this.transformMenu(localMenus);
      this.menus = this.getMenu();

      if (this.$route.name === "Home") {
        this.toMenu(this.menus[0]);
        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);
    },
    async initData() {
      const data = await sysMenu();
      this.initPrivilegeMap(data.privileges);
      this.privileges = this.transformMenu(data.privileges);
      this.menus = this.getMenu();

      if (this.$route.name === "Home") {
        this.toMenu(this.menus[0]);
        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);
    },
    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 => {
        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);
    },
    menuChange(menu) {
      this.curMenu = menu;

      this.curSubMenuNames = this.privileges
        .filter(item => item.parentId === menu.id)
        .map(item => item.url);
    },
    toMenu(menu) {
      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();
    },
    toLogout() {
      this.$confirm("确定要退出登录吗？", "提示", {
        type: "warning"
      })
        .then(() => {
          this.logoutAction();
        })
        .catch(() => {});
    },
    async logoutAction() {
      if (this.appSource === "SYSTEM") {
        await logout();

        this.$ls.clear();
        const ipDomainCode = window.sessionStorage.getItem("ipDomainCode");
        if (ipDomainCode) {
          this.$router.push({ name: "Login", query: { code: ipDomainCode } });
        } else {
          this.$router.push({ name: "Login" });
        }
      } else if (this.appSource === "WHU_THIRD") {
        window.location.href =
          "/api/report/wuda/open/user/authentication/logout";
      } else if (this.appSource === "PRINT_THIRD") {
        const url = "/api/report/sso/user/authentication/logout";
        const infos = getAuthInfo({
          sessionId: this.$ls.get("user", { sessionId: "" }).sessionId,
          token: this.$ls.get("token"),
          url,
          method: "post"
        });
        autoSubmitForm(url, {
          ...infos,
          orgId: this.$ls.get("orgId", ""),
          schoolId: this.$ls.get("schoolId", ""),
          userId: this.$ls.get("user", { id: "" }).id
        });
      } else {
        this.$message.error("未知来源");
      }
    },
    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>
