<script lang="ts" setup>
import { computed, onMounted, watch } from "vue";
import { store } from "@/store/store";
import {
  appDownloadApi,
  appEnableApi,
  studentClientMenuApi,
} from "@/api/mainLayout";
import { useRoute, useRouter } from "vue-router";
import QM_LOGO from "./qm-logo.png";
import VueQrcode from "@chenfengyuan/vue-qrcode";
import SiteMessageNotification from "@/features/SiteMessage/SiteMessageNotification.vue";
import { MenuSubItem, getMenuDict, parseMapLine } from "./menuConfig";

const router = useRouter();
const route = useRoute();

const user = store.user;

// computed
const customMenuLogo = computed(() =>
  store.QECSConfig.IS_CUSTOM_MENU_LOGO
    ? store.QECSConfig.CUS_MENU_LOGO_FILE_URL
    : QM_LOGO
);
const bindUserQrcodeUrl = computed(() => {
  const { rootOrgId, studentCodeList, identityNumber } = store.user;
  return JSON.stringify({
    rootOrgId,
    studentCode: studentCodeList.join(),
    identityNumber,
  });
});

let appDownloadUrl = $ref("");
let appEnable = $ref(false);
// 页面初始化
async function initData() {
  const res1 = await appEnableApi(user.rootOrgId);
  appEnable = res1.data;
  if (appEnable) {
    const res2 = await appDownloadApi();
    appDownloadUrl = res2.data;
  }
}
// 菜单相关
interface MenuOption {
  id: string;
  name: string;
  routeName: string;
}

let curMenu = $ref("");
let menuOptions = $ref<MenuOption[]>([]);
let curMenuOption = $ref<MenuOption | undefined>();
let breadcrumbs = $ref<MenuSubItem[]>([]);

async function getMenus() {
  const res = await studentClientMenuApi(store.user.rootOrgId);
  const menuDict = getMenuDict();
  menuOptions = res.data
    .sort((a, b) => b.weight - a.weight)
    .map((item) => {
      return {
        id: item.id,
        name: item.name,
        routeName: menuDict[item.routeCode.toUpperCase()],
      };
    });
}
function switchMenu(menu: MenuOption) {
  // console.log(menu.routeName);
  void router.push({ name: menu.routeName });
}

// route change
function routerChange() {
  breadcrumbs = parseMapLine(route.name as string);
  curMenu = breadcrumbs[0]?.routeName;
  curMenuOption = menuOptions.find((item) => item.routeName === curMenu);
}

function toModifyPwd() {
  logger({
    cnl: ["console"],
    pgn: curMenuOption?.name,
    act: "点击",
    stk: "修改密码",
  });

  void router.push({ name: "ChangePassword" });
}
function toLogout() {
  logger({
    cnl: ["console", "server"],
    pgn: curMenuOption?.name,
    act: "点击",
    stk: "退出登录",
  });
  void router.push({ name: "UserLogin" });
}

onMounted(async () => {
  void initData();
  await getMenus();

  if (menuOptions.length && route.name === "MainLayout") {
    void router.push({ name: menuOptions[0].routeName });
    return;
  }
  routerChange();
});

watch(
  () => route.name,
  (val) => {
    if (val === "MainLayout") return;
    routerChange();
  }
);
</script>

<template>
  <div class="home">
    <!-- header -->
    <div class="home-header">
      <div class="header-infos">
        <div v-if="appEnable" class="header-info">
          <n-popover placement="bottom" trigger="hover">
            <template #trigger>
              <p class="header-info-cont">手机端登录</p>
            </template>
            <div class="qr-list">
              <n-tabs type="segment">
                <n-tab-pane name="app" tab="下载云考APP">
                  <div class="qr-code">
                    <vue-qrcode
                      :value="appDownloadUrl"
                      :options="{ width: 200 }"
                    ></vue-qrcode>
                  </div>
                </n-tab-pane>
                <n-tab-pane name="bindUser" tab="绑定用户">
                  <div class="qr-code">
                    <vue-qrcode
                      :value="bindUserQrcodeUrl"
                      :options="{ width: 200 }"
                    ></vue-qrcode>
                  </div>
                </n-tab-pane>
              </n-tabs>
            </div>
          </n-popover>
        </div>
        <div class="header-info">
          <n-popover placement="bottom" trigger="hover">
            <template #trigger>
              <p class="header-info-cont">{{ user.displayName }}</p>
            </template>
            <div class="user-info">
              <div class="user-info-item">
                <span>底照</span>
                <img
                  class="user-avatar"
                  :src="user.photoPath"
                  :alt="user.displayName"
                />
              </div>
              <div class="user-info-item">
                <span>学号</span>
                <span>{{ user.studentCodeList.join() }}</span>
              </div>
              <div class="user-info-item">
                <span>身份证号</span>
                <span>{{ user.identityNumber }}</span>
              </div>
              <div class="user-info-item">
                <span>学习中心</span>
                <span>{{ user.orgName }}</span>
              </div>
              <div class="user-info-item">
                <n-button type="success" block @click="toModifyPwd"
                  >修改密码</n-button
                >
              </div>
            </div>
          </n-popover>
        </div>
        <div class="header-info">
          <n-button type="error" text @click="toLogout">退出登录</n-button>
        </div>
      </div>
    </div>
    <!-- navs -->
    <div class="home-navs">
      <div class="home-logo">
        <img :src="customMenuLogo" />
      </div>
      <div class="home-menu">
        <div v-for="menu in menuOptions" :key="menu.id" class="home-menu-item">
          <div
            :class="[
              'home-menu-content',
              { 'is-active': curMenu === menu.routeName },
            ]"
            @click="switchMenu(menu)"
          >
            <span>{{ menu.name }}</span>
            <n-badge
              v-if="
                menu.routeName === 'SiteMessage' &&
                store.siteMessage.unreadCount
              "
              class="qm-ml-10 -tw-mt-1"
              :value="store.siteMessage.unreadCount"
              :max="99"
            />
          </div>
        </div>
      </div>
    </div>
    <!-- body -->
    <div class="home-body">
      <div class="home-breadcrumb">
        <span class="breadcrumb-tips">
          <span>当前所在位置：</span>
        </span>
        <div class="breadcrumb-body">
          <n-breadcrumb>
            <n-breadcrumb-item
              v-for="bread in breadcrumbs"
              :key="bread.routeName"
            >
              {{ bread.name }}
            </n-breadcrumb-item>
          </n-breadcrumb>
        </div>
      </div>
      <!-- main -->
      <div class="home-main">
        <router-view></router-view>
      </div>
    </div>
  </div>
  <SiteMessageNotification />
</template>

<style scoped>
.home {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: auto;
  min-height: 100vh;
}
/* home-header */
.home-header {
  position: absolute;
  width: 100%;
  height: 50px;
  top: 0;
  left: 0;
  z-index: 99;
  padding-left: 180px;
  background-color: var(--app-color-white);
  overflow: hidden;
}
.header-infos {
  color: var(--app-color-text-light);
  font-size: 0;
  padding: 15px;
  line-height: 20px;
  text-align: right;
}
.header-info {
  display: inline-block;
  vertical-align: middle;
  font-size: var(--app-font-size);
  position: relative;
  padding: 0 20px;
  cursor: pointer;
}
.header-info-cont:hover {
  color: var(--app-color-primary);
}
.header-info:not(:last-child)::after {
  content: "";
  display: block;
  position: absolute;
  height: 16px;
  width: 0;
  border-left: 1px solid var(--app-color-border-dark);
  right: 0;
  top: 50%;
  margin-top: -8px;
}
.user-info {
  width: 280px;
}
.user-info-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 12px 0;
}
.user-info-item:not(:last-child) {
  border-bottom: 1px solid var(--app-color-border);
}
.user-avatar {
  display: block;
  width: 80px;
  height: 80px;
  box-shadow: 0 0 1px var(--app-color-border-dark);
}
.qr-list {
  width: 240px;
}
.qr-code {
  width: 200px;
  height: 200px;
  margin: 0 auto;
  padding: 0 0 20px;
}
.qr-code > img {
  display: block;
  width: 100%;
  height: 100%;
}

/* home-navs */
.home-navs {
  position: absolute;
  width: 180px;
  top: 0;
  left: 0;
  bottom: 0;
  z-index: 100;
  overflow: auto;
  background-color: var(--app-color-header-bg);
}
.home-logo {
  width: 80px;
  min-height: 62px;
  max-height: 100px;
  margin: 30px auto;
  border-radius: var(--app-border-radius);
}
.home-logo > img {
  display: block;
  width: 100%;
  height: auto;
}
.home-menu {
  color: var(--app-color-white);
}
.home-menu-item {
  margin: 0;
}
.home-menu-content {
  padding: 10px 20px 10px 45px;
  line-height: 20px;
  cursor: pointer;
  position: relative;
}
.home-menu-content::before {
  content: "";
  display: block;
  position: absolute;
  width: 8px;
  height: 8px;
  top: 17px;
  left: 30px;
  border-radius: 50%;
  border: 2px solid var(--app-color-white);
  opacity: 0.5;
}
.home-menu-content:hover,
.home-menu-content.is-active {
  background-color: rgba(255, 255, 255, 0.5);
}
.home-menu-content:hover::before,
.home-menu-content.is-active::before {
  opacity: 1;
}

/* home-body */
.home-body {
  position: absolute;
  left: 0;
  top: 50px;
  right: 0;
  bottom: 0;
  overflow: auto;
  background: var(--app-color-white);
  z-index: 98;
  padding-left: 180px;
}
.home-breadcrumb {
  background-color: var(--app-color-body-bg);
  padding: 10px 20px;
  line-height: 30px;
  color: var(--app-color-text-light);
}
.breadcrumb-body {
  display: inline-block;
}
.home-main {
  padding: 20px 20px 50px;
}
</style>
