<template>
  <div class="home">
    <div class="home-header">
      <div class="head-logo">
        <h1>{{ APP_TITLE }}</h1>
      </div>
      <div class="head-info">
        <el-breadcrumb>
          <el-breadcrumb-item :to="{ name: 'Home' }">
            <i class="el-icon-s-home" style="margin-top: -4px"></i>
          </el-breadcrumb-item>
          <el-breadcrumb-item
            v-for="(bread, index) in breadcrumbs"
            :key="index"
            >{{ bread.name }}</el-breadcrumb-item
          >
        </el-breadcrumb>
      </div>
      <div class="head-user">
        <span class="user-item user-name" :title="username" @click="toResetPwd">
          <i class="el-icon-user-solid"></i>
          <span>{{ username }}</span>
        </span>
        <span class="user-item user-logout" title="退出登录" @click="logout">
          <i class="el-icon-switch-button"></i>
        </span>
      </div>
    </div>

    <div class="home-navs">
      <el-menu
        v-if="menus && menus.length"
        class="el-menu-home"
        active-text-color="#3a5ae5"
        text-color="#434656"
        router
        :default-active="curRouteName"
        :collapse="false"
      >
        <template v-for="submenu in menus">
          <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">
        <router-view />

        <view-footer></view-footer>
      </div>
    </div>

    <!-- ResetPwd -->
    <reset-pwd ref="ResetPwd" @modified="logout"></reset-pwd>
  </div>
</template>

<script>
import { navs } from "@/constants/navs";
import { APP_TITLE } from "@/constants/app";
import ResetPwd from "../modules/admin/user/ResetPwd";

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

    return {
      APP_TITLE,
      navs,
      privileges: [],
      menus: [],
      curRouteName: "",
      validRoutes: [],
      username: user.name,
      userRoles: user.role,
      curMain: 0,
      curSub: "",
      breadcrumbs: [],
    };
  },
  watch: {
    $route(val) {
      if (val.name === "Home") return;

      this.updateBreadcrumbs();
    },
  },
  created() {
    this.initData();
  },
  methods: {
    initData() {
      this.menus = this.getMenu();
      this.privileges = this.getPrivileges();

      if (this.$route.name === "Home") {
        // console.log(this.getMenuFirstRouter());
        this.$router.replace({ name: this.getMenuFirstRouter() });
        return;
      }

      if (!this.validRoutes.includes(this.$route.name)) {
        this.$router.replace({
          name: "404",
        });
        return;
      }

      this.updateBreadcrumbs();
    },
    getMenuFirstRouter() {
      let firstRouteName = "";
      let menu = this.menus[0];
      while (menu) {
        firstRouteName = menu.url;
        menu = menu.children && menu.children[0];
      }

      return firstRouteName;
    },
    getMenu() {
      const privilegeMap = this.$store.state.privilegeMap;
      const getChildren = (id) => {
        return navs
          .filter(
            (item) =>
              item.parentId === id &&
              (!item.privilege ||
                (item.privilege && privilegeMap[item.privilege]))
          )
          .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;
    },
    getPrivileges() {
      let privileges = [];
      const listTree = (dataList) => {
        dataList.forEach((item) => {
          privileges.push({
            id: item.id,
            name: item.name,
            parentId: item.parentId,
            url: item.url,
          });
          if (item.children && item.children.length) {
            listTree(item.children);
          }
        });
      };
      listTree(this.menus);
      return privileges;
    },
    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;
    },
    toPage(mainIndex, subIndex) {
      const item = this.navs[mainIndex];
      const elem = item.children[subIndex];
      this.breadcrumbs = [
        { title: item.title, router: item.router },
        { title: elem.title, router: elem.router },
      ];
      this.curMain = mainIndex;
      this.curSub = mainIndex + "-" + subIndex;

      this.$router.push({
        name: elem.router,
      });
    },
    logout() {
      this.$ls.clear();
      this.$router.push({ name: "Login" });
    },
    toResetPwd() {
      this.$refs.ResetPwd.open();
    },
  },
};
</script>
