<template>
  <div class="home" :class="isCollapse ? 'is-collapse' : ''">
    <div class="home-header">
      <div class="home-exam">
        <el-button text @click="toggleCollapse">
          <svg-icon name="icon-menu" />
        </el-button>
        <span v-if="curExamName" @click="toSwitchExam"
          >当前考试：{{ curExamName }}</span
        >
      </div>
      <div class="home-tips">
        <svg-icon name="icon-ai" />
        <span>AI检测预计耗时12小时35分后完成</span>
      </div>
      <div class="home-action">
        <el-popover popper-class="user-popover" placement="bottom-end">
          <template #reference>
            <el-button text>
              <svg-icon name="icon-user" />
              <span :title="userStore.name" style="margin-left: 6px"
                >{{ userStore.name }}（{{
                  dictFilter.role(userStore.role)
                }}）</span
              >
            </el-button>
          </template>
          <div>
            <el-button text @click="toUserInfo">用户信息 </el-button>
          </div>
          <div>
            <el-button text @click="toResetPwd">修改密码 </el-button>
          </div>
        </el-popover>
        <el-button text @click="toLogout">
          <svg-icon name="icon-notice" />
        </el-button>
        <el-tooltip content="退出登录" placement="bottom-end">
          <el-button text @click="toLogout">
            <svg-icon name="icon-logout" />
          </el-button>
        </el-tooltip>
      </div>
    </div>

    <div class="home-navs">
      <div class="home-title">
        <svg-icon name="icon-logo" />
        <h1>云阅卷</h1>
      </div>
      <el-menu
        v-if="appStore.appMenus && appStore.appMenus.length"
        class="el-menu-home"
        :default-active="curRouteName"
        :collapse="isCollapse"
        unique-opened
        @select="toMenuItem"
        @open="handleSubMenuOpen"
      >
        <template v-for="submenu in appStore.appMenus">
          <el-sub-menu
            v-if="submenu.children && submenu.children.length"
            :key="submenu.url"
            :index="submenu.url"
          >
            <template #title>
              <svg-icon v-if="submenu.icon" :name="submenu.icon" />
              <span>{{ submenu.name }}</span>
            </template>

            <el-menu-item
              v-for="nav in submenu.children"
              :key="nav.url"
              :index="nav.url"
            >
              <span>{{ nav.name }}</span>
            </el-menu-item>
          </el-sub-menu>
          <el-menu-item v-else :key="submenu.url + 'menu'" :index="submenu.url">
            <svg-icon v-if="submenu.icon" :name="submenu.icon" />
            <span>{{ submenu.name }}</span>
          </el-menu-item>
        </template>
      </el-menu>
      <div class="nav-footer">
        <el-button link> 自命题质量分析系统 </el-button>
        <svg-icon name="icon-jump" style="margin-left: 10px"></svg-icon>
      </div>
    </div>

    <div class="home-body">
      <div v-if="appStore.breadcrumbs.length" class="home-breadcrumb">
        <span class="breadcrumb-tips">
          <svg-icon name="icon-home" />
          <span>当前所在位置：</span>
        </span>
        <el-breadcrumb separator="/">
          <el-breadcrumb-item
            v-for="(bread, index) in appStore.breadcrumbs"
            :key="index"
          >
            {{ bread }}
          </el-breadcrumb-item>
        </el-breadcrumb>
      </div>

      <!-- home-view: page detail -->
      <router-view />
    </div>
  </div>

  <!-- ResetPwdDialog -->
  <ResetPwdDialog ref="resetPwdDialogRef" @modified="resetPwdModified" />
  <!-- UserInfoDialog -->
  <UserInfoDialog ref="userInfoDialogRef" :user-id="userStore.id" />
</template>

<script lang="ts" setup>
  import { computed, onMounted, ref, watch } from 'vue';
  import { useRoute, useRouter } from 'vue-router';
  import { useAppStore, useUserStore } from '@/store';
  import { modalConfirm } from '@/utils/ui';
  import { dictFilter } from '@/utils/filter';

  import ResetPwdDialog from '@/views/login/components/ResetPwdDialog.vue';
  import UserInfoDialog from '@/views/login/components/UserInfoDialog.vue';

  defineOptions({
    name: 'DefaultLayout',
  });

  const appStore = useAppStore();
  const userStore = useUserStore();
  const route = useRoute();
  const router = useRouter();

  const curRouteName = ref('');
  const resetPwdDialogRef = ref();
  const userInfoDialogRef = ref();
  const isCollapse = ref(false);

  const curExamName = computed(() => {
    return appStore.displayExamName;
  });

  function getRouteName() {
    let routerName = route.name as string;
    if (route.meta.relationRoutes && route.meta.relationRoutes.length) {
      routerName = route.meta.relationRoutes[0];
    }
    return routerName;
  }

  function initData() {
    curRouteName.value = getRouteName();
    // console.log(route.name);
  }

  function toggleCollapse() {
    isCollapse.value = !isCollapse.value;
  }

  function toSwitchExam() {
    router.push({
      name: 'SwitchExam',
      query: {
        backUrl: route.path,
      },
    });
  }

  function handleSubMenuOpen(val: string) {
    if (appStore.checkCurRouteInSubMenu(val, getRouteName())) {
      return;
    }
    const subMenuFirstRouter = appStore.getSubMenuFirstRouter(val);
    if (
      route.name === subMenuFirstRouter.name ||
      subMenuFirstRouter.name === val
    ) {
      return;
    }

    router.push({ name: subMenuFirstRouter.name });
  }

  function toMenuItem(val: string) {
    if (route.name === val) {
      return;
    }
    router.push({ name: val });
  }

  function toResetPwd() {
    resetPwdDialogRef.value?.open();
  }

  function toUserInfo() {
    userInfoDialogRef.value?.open();
  }

  function resetPwdModified() {
    setTimeout(() => {
      userStore.logout();
    }, 1000);
  }

  async function toLogout() {
    const confirm = await modalConfirm(`确定要退出登录吗？`, '提示').catch(
      () => false
    );
    if (!confirm) return;

    await userStore.logout();
  }

  onMounted(() => {
    initData();
  });

  watch(
    () => route.name,
    () => {
      initData();
    }
  );
</script>
