<template>
  <div class="home-side">
    <div class="home-logo">
      <router-link to="/questions/tips">
        <!-- <img src="@/assets/images/system-icon.png" /> -->
        <img src="@/assets/images/menu-icon.png" />
      </router-link>
    </div>
    <div class="menu-wrap">
      <el-menu
        class="el-menu-vertical-demo"
        active-text-color="#705eff"
        text-color="#383b4a"
        router
        :default-active="defaultActiveCode"
        unique-opened
      >
        <el-submenu
          v-for="(menu1, index) in menuList"
          :key="menu1.code"
          :index="menu1.code"
        >
          <template slot="title">
            <i :class="'icon icon-' + MENU_ICONS[index]"></i>

            <span>{{ menu1.name }}</span>
          </template>
          <el-menu-item
            v-for="menu2 in menu1.subRolePrivilege"
            :key="menu2.code"
            :index="menu2.code"
            :route="{ path: menu2.privilegeUri }"
          >
            <span style="margin-left: 9px">{{ menu2.name }}</span>
            <div
              class="menu-badge"
              v-if="
                badgeMenuCodes.includes(menu2.code) && badgeMenuNums[menu2.code]
              "
            >
              {{ badgeMenuNums[menu2.code] }}
            </div>
          </el-menu-item>
        </el-submenu>
      </el-menu>
      <!-- <el-menu
        v-if="menuList.length > 0"
        class="el-menu-vertical-demo"
        active-text-color="#705eff"
        text-color="#383b4a"
        router
        :default-active="curRoutePath"
      >
        <el-submenu
          v-for="menu1 in menuList1"
          :key="menu1.id"
          :index="menu1.nodeCode"
        >
          <template slot="title">
            <i :class="menu1.icon" style="color: red"></i>
            <span>{{ menu1.name }}</span>
          </template>

          <el-menu-item
            v-for="menu2 in menuList2(menu1)"
            :key="menu2.id"
            :index="menu2.ext5"
            :route="{ path: menu2.ext5 }"
          >
            <span style="margin-left: 9px">{{ menu2.name }}</span>
          </el-menu-item>
        </el-submenu>
      </el-menu> -->
    </div>

    <el-menu
      class="other-menus"
      active-text-color="#705eff"
      text-color="#383b4a"
      router
    >
      <el-menu-item
        @click="safeSetOpen"
        v-if="authButtons.includes('import_test_paper-safe')"
      >
        <i class="icon icon-safe"></i>
        <span> 安全设置 </span>
      </el-menu-item>
      <el-menu-item>
        <el-popover placement="right" width="180" trigger="hover">
          <div slot="reference">
            <i class="icon icon-fast"></i>
            <span> 快捷路径 </span>
          </div>
          <div>
            <div
              class="fast-menu-item"
              @click="$router.push('/questions/import_paper/0')"
            >
              导入试题
            </div>
            <div
              class="fast-menu-item"
              @click="$router.push('/questions/gen_paper/0')"
            >
              试卷列表
            </div>
          </div>
        </el-popover>
      </el-menu-item>
      <el-menu-item
        class="red"
        :index="'/questions/recycle'"
        :route="{ path: '/questions/recycle' }"
      >
        <i class="el-icon-delete" style="font-size: 16px"></i>
        <span> 回收站 </span>
      </el-menu-item>
    </el-menu>
    <question-safety-set-dialog
      ref="QuestionSafetySetDialog"
    ></question-safety-set-dialog>
  </div>
</template>

<script>
import { mapState, mapGetters } from "vuex";
import { QUESTION_API } from "@/constants/constants";
import QuestionSafetySetDialog from "@/modules/question/components/QuestionSafetySetDialog.vue";

const routesToMenu = [
  {
    path: "/basic",
    name: "基础信息",
    groupCode: "BASIC_MENUS",
  },
  {
    path: "/examwork",
    name: "考务管理",
    groupCode: "EXAM_WORK_MENUS",
  },
  {
    path: "/questions",
    name: "题库",
    groupCode: "QUESTIONS_WORK_MENUS",
  },
  {
    path: "/oe",
    name: "网考",
    groupCode: "NETEXAM_WORK_MENUS",
  },
  {
    path: "/marking",
    name: "阅卷",
    groupCode: "MARK_WORK_MENUS",
  },
  {
    path: "/portal",
    groupCode: "PORTAL_MENUS",
  },
  {
    path: "/print",
    name: "印刷管理",
    groupCode: "PRINT_MENUS",
  },
  {
    path: "/reports",
    name: "报表",
    groupCode: "REPORTS_MENUS",
  },
];
// const MENU_ICONS = {
//   base_info: "base",
//   course_manage: "course",
//   structure_manage: "create-paper",
//   question_bank: "question-book",
//   paper_manage: "paper-book",
//   ques_manage: "question",
// };

import { mapMutations } from "vuex";
import { UPDATE_CURRENT_PATHS } from "../../store/currentPaths";
import { UPDATE_MENU_LIST } from "../../store/menuList";
const localMenusConfig = {
  Recycle: ["回收站"],
  QuestionTypeStatistics: ["试题管理", "试题列表", "试题统计"],
  SourceDetailManage: ["试题管理", "试题列表", "题型管理"],
  gen_paper_detail: ["卷库管理", "试卷列表", "组卷"],
};
export default {
  name: "HomeSide",
  components: { QuestionSafetySetDialog },
  data() {
    return {
      group: null,
      menuList: [],
      curRoutePath: "",
      isCollapse: false,
      MENU_ICONS: ["base", "course", "question-book", "paper-book"],
      defaultActiveCode: "base_info",
      menuKey: Math.random() + "",
      badgeMenuCodes: [
        "check_duplicate_list",
        "paper_pending_trial",
        "exam_paper_pending_trial",
      ],
      badgeMenuNums: {
        check_duplicate_list: 0,
        paper_pending_trial: 0,
        exam_paper_pending_trial: 0,
      },
    };
  },
  computed: {
    ...mapState({ user: (state) => state.user }),
    ...mapGetters(["authButtons"]),
  },
  watch: {
    $route() {
      this.updatePath();
    },
    menuList() {
      this.updatePath();
    },
  },
  async created() {
    this.group = routesToMenu.find((v) => this.$route.path.startsWith(v.path));
    let list = await this.getUserPrivileges();
    let authButtons = [];

    list.forEach((level1) => {
      if (level1.subRolePrivilege?.length) {
        level1.subRolePrivilege.forEach((level2) => {
          if (level2.subRolePrivilege?.length) {
            level2.subRolePrivilege.forEach((level3) => {
              if (level3.privilegeType === "BUTTON" && level3.enable) {
                authButtons.push(level3.code);
              }
            });
          }
        });
      }
    });
    this.setAuthButtons(authButtons);
    console.log(this.$store.state.authButtons);
    this.menuList = list;
    this.UPDATE_MENU_LIST(this.menuList);
    this.updatePath();
    this.getBadge();
    this.$bus.on("updateBadge", () => {
      this.getBadge();
    });
  },
  methods: {
    ...mapMutations([UPDATE_CURRENT_PATHS, UPDATE_MENU_LIST, "setAuthButtons"]),
    getBadge() {
      this.$httpWithMsg
        .post(QUESTION_API + "/rolePrivilege/pending/count")
        .then((res) => {
          if (res.data) {
            this.badgeMenuNums["check_duplicate_list"] =
              res.data?.duplicateCount || 0;
            this.badgeMenuNums["paper_pending_trial"] =
              res.data?.questionAuditCount || 0;
            this.badgeMenuNums["exam_paper_pending_trial"] =
              res.data?.paperAuditCount || 0;
          }
        });
    },
    safeSetOpen() {
      this.$refs.QuestionSafetySetDialog.open();
    },
    toPage(path) {
      this.$router.push(path);
    },
    toggoleSidebar() {
      this.isCollapse = !this.isCollapse;
    },
    async getUserPrivileges() {
      var url = QUESTION_API + "/rolePrivilege/getUserPrivileges";
      const params = new URLSearchParams();
      params.append("full", false);
      const res = await this.$httpWithMsg.post(url, params, {
        headers: { "content-type": "application/x-www-form-urlencoded" },
      });

      return res.data;
    },
    updatePath() {
      // console.log("home update");
      let curRoutePath = this.$route.path;
      if (curRoutePath.endsWith("/1")) {
        curRoutePath = curRoutePath.slice(0, -2) + "/0";
      }
      this.curRoutePath = curRoutePath;
      let arr = [];
      loop: for (let i = 0; i < this.menuList.length; i++) {
        arr = [];
        let item = this.menuList[i];
        if (item.privilegeUri == curRoutePath) {
          arr.push(item.name);
          this.menuKey = Math.random() + "";
          break;
        } else {
          let sub = item.subRolePrivilege.find(
            (v) => v.privilegeUri == curRoutePath
          );
          if (sub) {
            arr.push(item.name, sub.name);
            this.defaultActiveCode = sub.code;
            this.menuKey = Math.random() + "";
            break loop;
          }
        }
      }
      if (!arr.length) {
        arr = localMenusConfig[this.$route.name] || [];
      }

      !!arr.length && this.UPDATE_CURRENT_PATHS(arr);
    },
  },
};
</script>
<style lang="scss" scoped>
.home-side {
  display: flex;
  flex-direction: column;
  .menu-wrap {
    flex: 1;
    overflow: auto;
  }
  .other-menus {
    margin-top: 30px;
    padding: 10px 0;
    position: relative;

    &:before {
      content: "";
      position: absolute;
      left: 0;
      top: 0;
      height: 1px;
      width: calc(100% - 48px);
      margin-left: 24px;
      background: #e5e5e5;
    }
    .el-menu-item {
      height: 40px;
      line-height: 40px;
      font-weight: bold;
      &:not(:last-child) {
        i {
          margin-right: 9px;
          margin-left: 20px;
        }
      }
      &.red {
        color: #f76560 !important;
        i {
          color: #f76560;
          margin-left: 16px;
        }
      }
    }
  }
}
</style>
<style lang="scss">
.fast-menu-item {
  height: 28px;
  line-height: 28px;
  cursor: pointer;
  padding-left: 10px;
  border-radius: 4px;
  &:hover {
    background-color: #f0f0f0;
  }
}
</style>
