<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="(nav, index) in navs"
            :key="index"
            @click="toPage(index, 0)"
            :class="{ 'menu-item-act': curMainIndex === index }"
          >
            <div class="menu-item">
              <i :class="['icon', `icon-${nav.router}`]"></i>
              <span>{{ nav.title }}</span>
            </div>
          </li>
        </ul>
      </div>
      <div class="head-user menu-list">
        <ul>
          <li>
            <div class="menu-item">
              <i class="icon icon-account"></i>
              <span>账户设置</span>
            </div>
          </li>
          <li @click="toLogout">
            <div class="menu-item">
              <i class="icon icon-shut"></i>
              <span>退出登录</span>
            </div>
          </li>
        </ul>
      </div>
    </div>

    <div class="home-navs" v-if="curNav">
      <div class="nav-head">
        <i :class="['icon', `icon-${curNav.router}-gray`]"></i>
        <span>{{ curNav.title }}</span>
      </div>
      <ul class="nav-list">
        <li
          class="nav-item"
          v-for="(nav, subNo) in curNav.children"
          :key="subNo"
        >
          <div
            :class="[
              'nav-item-main',
              { 'nav-item-main-act': curSubIndex === subNo }
            ]"
            @click="switchNav(subNo)"
          >
            <p class="nav-item-cont">{{ nav.title }}</p>
            <span class="nav-item-icon nav-item-icon-right">
              <i
                :class="[
                  'icon',
                  curSubIndex === subNo
                    ? 'icon-arrow-right-act'
                    : 'icon-arrow-right'
                ]"
              ></i>
            </span>
          </div>
        </li>
      </ul>
    </div>

    <div class="home-body">
      <div class="home-main">
        <div class="home-breadcrumb" v-if="breadcrumbs.length">
          <el-breadcrumb separator=">">
            <el-breadcrumb-item :to="{ name: 'Home' }">
              <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 />
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import localNavs from "@/constants/navs";
import { deepCopy } from "@/plugins/utils";
import { MENU_ROUTER_DICT } from "@/constants/enumerate";
import { logout, sysMenu } from "../modules/login/api";

export default {
  name: "home",
  data() {
    return {
      navs: [],
      validRoutes: [],
      curMainIndex: 0,
      curSubIndex: 0,
      breadcrumbs: []
    };
  },
  watch: {
    $route(val) {
      this.actCurNav();
    }
  },
  computed: {
    curNav() {
      return this.navs[this.curMainIndex];
    }
  },
  created() {
    this.getMenus();
  },
  methods: {
    async getMenus() {
      const data = await sysMenu();
      this.navs = this.menusToTree(data.records);
      console.log(this.$route.name);

      if (this.$route.name === "Home") {
        this.$router.replace({
          name: this.navs[0].children[0].router
        });
      } else {
        if (!this.validRoutes.includes(this.$route.name)) {
          this.$router.replace({
            name: "404"
          });
        }
      }
      this.actCurNav();
    },
    menusToTree(menus) {
      let navTree = deepCopy(localNavs);
      let validRoutes = [];
      const anchorNav = (menu, navs) => {
        const name = MENU_ROUTER_DICT[menu.url];
        navs.forEach(item => {
          if (item.router === name) {
            item.fixed = true;
            validRoutes.push(item.router);

            if (menu.parentId !== null && item["children"]) {
              item.children.map(el => {
                el.fixed = true;
                validRoutes.push(el.router);
              });
            }
            return;
          } else {
            if (item["children"]) anchorNav(menu, item.children);
          }
        });
      };
      const clearNoFixed = navs => {
        let list = [];
        navs.forEach(nav => {
          if (nav["fixed"]) {
            let navItem = { title: nav.title, router: nav.router };
            if (nav["children"])
              navItem.children = clearNoFixed(nav["children"]);
            list.push(navItem);
          }
        });
        return list;
      };

      menus.forEach(menu => {
        anchorNav(menu, navTree);
      });
      this.validRoutes = validRoutes;
      return clearNoFixed(navTree);
    },
    switchNav(subNo) {
      const curSubItem = this.curNav.children[subNo];
      if (curSubItem.router === this.$route.name) return;
      this.$router.push({ name: curSubItem.router });
    },
    actCurNav() {
      const relate = this.$route.meta && this.$route.meta.relate;
      const routerName = relate ? relate.split("/")[0] : this.$route.name;

      this.navs.forEach((item, index) => {
        item.children.forEach((elem, pindex) => {
          if (elem.router === routerName) {
            this.curSubIndex = pindex;
            this.curMainIndex = index;
            this.breadcrumbs = [
              { title: item.title, router: item.router },
              { title: elem.title, router: elem.router }
            ];
          }
        });
      });

      if (relate) this.getMoreBreadcrumbs(relate);
    },
    getMoreBreadcrumbs(relate) {
      const curSubNav = this.navs[this.curMainIndex].children[this.curSubIndex];
      if (!curSubNav.children || !curSubNav.children.length) return;

      relate
        .split("/")
        .slice(1)
        .map(routerName => {
          const matchRouter = curSubNav.children.find(
            elem => elem.router === routerName
          );
          if (matchRouter)
            this.breadcrumbs.push({
              title: matchRouter.title,
              router: matchRouter.router
            });
        });
    },
    toPage(mainIndex, subIndex) {
      const elem = this.navs[mainIndex].children[subIndex];
      if (elem.router === this.$route.name) return;
      this.$router.push({
        name: elem.router
      });
    },
    toLogout() {
      this.$confirm("确定要退出登录吗？", "提示", {
        cancelButtonClass: "el-button--primary",
        confirmButtonClass: "el-button--default-act",
        type: "warning"
      })
        .then(async () => {
          await logout(this.$ls.get("user", { id: "" }).id);
          this.$ls.clear();
          this.$router.push({ name: "Login" });
        })
        .catch(() => {});
    }
  }
};
</script>
