<template>
  <div class="home">
    <div class="home-header">
      <div class="head-logo">
        <h1>逸教云</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="['icon', `icon-${menu.name}`]"></i>
            <span>{{ menu.title }}</span>
          </li>
        </ul>
      </div>
      <div class="head-user menu-list">
        <ul>
          <li
            class="menu-item menu-item-account"
            @click="$refs.ResetPwd.open()"
          >
            <i class="icon icon-account"></i>
            <span :title="username">{{ username }}</span>
          </li>
          <li class="menu-item" @click="toLogout">
            <i class="icon icon-shut"></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="icon icon-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 /> -->
          <keep-alive>
            <router-view />
          </keep-alive>
        </div>
      </div>
    </div>

    <!-- popover menu-->
    <!-- TODO: -->

    <!-- 修改密码 -->
    <reset-pwd @modified="logoutAction" ref="ResetPwd"></reset-pwd>
  </div>
</template>

<script>
// import { mapState, mapActions } from "vuex";
import localNavs from "@/constants/navs";
import { deepCopy } from "@/plugins/utils";
import { sysMenu } from "../modules/login/api";
import ResetPwd from "../modules/base/components/ResetPwd";

export default {
  name: "home",
  components: { ResetPwd },
  data() {
    return {
      menus: [],
      curMenu: { name: "" },
      curActNav: "",
      breadcrumbs: [],
      validRoutes: [],
      username: this.$ls.get("user", { realName: "" }).realName,
      menuDailogIsShow: false,
      waitTaskCount: 0
    };
  },
  watch: {
    $route(val) {
      if (val.name === "Home") return;
      this.actCurNav();
    }
  },
  computed: {
    // ...mapState("examCenter", ["waitTaskCount"]),
  },
  created() {
    this.getMenus();
    // this.menus = localNavs;
    // this.actCurNav();
  },
  methods: {
    // ...mapActions("examCenter", ["updateWaitTaskCount"]),
    getMenus() {
      this.menus = localNavs;
      if (this.$route.name === "Home") {
        this.$router.replace({
          name: "ExamTaskManage"
        });
      } else {
        this.actCurNav();
      }
    },
    async getMenus1() {
      const data = await sysMenu();
      const { menus, firstRouter } = this.menusToTree(data.records);
      console.log(menus, firstRouter);
      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();
      }
    },
    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 });
    },
    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();
      }
    },
    toLogout() {
      this.$confirm("确定要退出登录吗？", "提示", {
        cancelButtonClass: "el-button--danger is-plain",
        confirmButtonClass: "el-button--primary",
        type: "warning"
      })
        .then(() => {
          this.logoutAction();
        })
        .catch(() => {});
    },
    logoutAction() {
      // await logout(this.$ls.get("user", { id: "" }).id);
      this.$ls.clear();
      this.$router.push({ name: "Login" });
    },
    // popover menu
    showMenu() {
      this.menuDailogIsShow = !this.menuDailogIsShow;
    },
    toNavDetail(mainNo, subNo) {
      this.toNav(subNo);
      this.showMenu();
    }
  }
};
</script>
