<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',`icon-${menu.url}`
              ]"
            ></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 menu-item-logout" @click="toLogout">
            <i class="el-icon-switch-button" title="退出登录"></i>
            <span>退出</span>
          </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-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>
    <view-footer></view-footer>

    <!-- 修改密码 -->
    <reset-pwd
      :user-info="userInfo"
      ref="ResetPwd"
      @modified="logoutAction"
    ></reset-pwd>
    <!-- 切换学校 -->
    <switch-school-dialog v-if="hasMoreSchool" ref="SwitchSchoolDialog">
    </switch-school-dialog>
  </div>
</template>

<script>
import { mapState } from "vuex";
import { logout } from "../modules/login/api";
import { SYS_ADMIN_NAME } from "@/constants/enumerate";
import { logoutHandle } from "../plugins/logout";

import ResetPwd from "../modules/base/components/ResetPwd.vue";
import SwitchSchoolDialog from "../modules/login/components/SwitchSchoolDialog.vue";
import ViewFooter from "../components/ViewFooter.vue";

const HOME_PAGE_ROUTE = "HomePage";

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

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

      this.routerChange();
    },
  },
  computed: {
    ...mapState("app", ["menus", "privileges"]),
    IS_HOME_PAGE() {
      return this.$route.name === HOME_PAGE_ROUTE;
    },
    hasMoreSchool() {
      return this.schoolInfo && this.schoolInfo.length > 1;
    },
  },
  created() {
    this.initData();
  },
  methods: {
    initData() {
      if (this.IS_HOME_PAGE) {
        this.curMenu = { url: HOME_PAGE_ROUTE };
        return;
      }

      if (this.$route.name === "Home") {
        this.toMenu(this.menus[0]);
        return;
      }

      this.updateBreadcrumbs();
      const curMenu = this.menus.find(
        (menu) => menu.url === this.breadcrumbs[0].url
      );
      this.menuChange(curMenu);
    },
    getCurMenuFirstRouter() {
      let firstRouteName = "";
      let menu = this.curMenu;
      while (menu) {
        firstRouteName = menu.url;
        menu = menu.children && menu.children[0];
      }

      return firstRouteName;
    },
    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;
      const 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();

      const curMenu = this.menus.find(
        (menu) => menu.url === this.breadcrumbs[0].url
      );
      this.menuChange(curMenu);
    },
    toLogout() {
      this.$confirm("确定要退出登录吗？", "提示", {
        type: "warning",
      })
        .then(() => {
          this.logoutAction();
        })
        .catch(() => {});
    },
    toSelectSchool() {
      if (this.IS_SUPER_ADMIN) {
        this.$router.push({ name: "SelectSchool" });
        return;
      }
      if (this.hasMoreSchool) {
        this.$refs.SwitchSchoolDialog.open();
      }
    },
    toResetPwd() {
      if (this.IS_SUPER_ADMIN) return;
      this.$refs.ResetPwd.open();
    },
    async logoutAction() {
      await logout().catch(() => {});
      logoutHandle();
    },
    // 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>
