<template>
  <div class="admin">
    <div class="home-header">
      <div class="head-user menu-list">
        <ul>
          <li @click="toSelectSchool">
            <i class="el-icon-s-home"></i>
            <span>切换学校</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">
          <h1>知学知考</h1>
        </div>
      </div>
      <el-menu
        class="el-menu-home"
        active-text-color="#705eff"
        text-color="#383b4a"
        router
        :default-active="curRouteName"
        :default-openeds="curSubMenuNames"
      >
        <el-submenu
          v-for="submenu in menus"
          :key="submenu.url"
          :index="submenu.url"
        >
          <template slot="title">
            <span>{{ submenu.name }}</span>
          </template>

          <el-menu-item
            v-for="nav in submenu.children"
            :key="nav.url"
            :index="nav.url"
            :route="{ name: nav.url }"
          >
            <span>{{ nav.name }}</span>
          </el-menu-item>
        </el-submenu>
      </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, index) in breadcrumbs"
              :key="index"
              >{{ bread.name }}</el-breadcrumb-item
            >
          </el-breadcrumb>
        </div>

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

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

<script>
import localNavs from "@/constants/adminNavs";
import { SYS_ADMIN_NAME } from "@/constants/enumerate";
import { logout } from "@/modules/login/api";
import ResetPwd from "../../base/components/ResetPwd";

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

    return {
      menus: [],
      privileges: [],
      curRouteName: "",
      curSubMenuNames: [],
      breadcrumbs: [],
      username: user.realName,
      userInfo: {
        pwdCount: 0,
        mobileNumber: 1,
        userId: user.id
      }
    };
  },
  watch: {
    $route(val) {
      if (val.name === "Admin") return;
      this.actCurNav();
    }
  },
  created() {
    const loginName = this.$ls.get("user", { loginName: "" }).loginName;
    if (loginName !== SYS_ADMIN_NAME) {
      this.$message.error("非法操作!");
      this.$router.replace({ name: "Login" });
      return;
    }

    if (this.$route.name === "Admin") {
      this.$router.replace({
        name: "AdminUserManage"
      });
    }
    this.initData();
  },
  methods: {
    initData() {
      this.privileges = localNavs;
      this.menus = this.getMenu();
      this.curSubMenuNames = this.menus.map(item => item.url);

      if (this.$route.name === "Admin") {
        const firstRouteName = this.getFirstRouter();
        this.$router.replace({
          name: firstRouteName
        });
        return;
      }

      this.actCurNav();
    },
    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;
    },
    getMenu() {
      let menus = this.privileges.filter(item => item.parentId === "-1");
      const toTree = menus => {
        menus.forEach(menu => {
          const children = this.privileges.filter(
            item => item.parentId === menu.id
          );
          if (children.length) {
            menu.children = children;
            toTree(menu.children);
          }
        });
      };
      toTree(menus);

      return menus;
    },
    actCurNav() {
      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;
    },
    toLogout() {
      this.$confirm("确定要退出登录吗？", "提示", {
        type: "warning"
      })
        .then(() => {
          this.logoutAction();
        })
        .catch(() => {});
    },
    async logoutAction() {
      await logout();
      this.$ls.clear();
      this.$router.push({ name: "Login" });
    },
    toSelectSchool() {
      this.$router.push({ name: "SelectSchool" });
    },
    toResetPwd() {
      this.$refs.ResetPwd.open();
    },
    resetPwdModified() {
      this.logoutAction();
    }
  }
};
</script>
