<template>
  <div class="app" :style="{ backgroundImage }">
    <el-config-provider :locale="zhCn" :zIndex="3000">
      <template v-if="!isNotHaedRoute && IS_TAURI">
        <!-- 标题栏 -->
        <app-head-bar style="position: fixed; top: 0; left: 0; z-index: 888; width: 100vw" :height="headHeight"></app-head-bar>
        <!-- 占位 -->
        <div :style="{ height: `${headHeight}px` }"></div>
      </template>
      <div id="app-body" style="position: relative; display: flex; flex: 1; flex-direction: column; overflow: hidden">
        <router-view #default="{ Component, route }">
          <component :is="Component" :key="route.path"></component>
        </router-view>
      </div>
      <!-- 检测更新 -->
      <app-dialog-updata></app-dialog-updata>
    </el-config-provider>
  </div>
</template>

<script setup lang="ts">
  import zhCn from 'element-plus/es/locale/lang/zh-cn';
  import { WebviewWindow } from '@tauri-apps/api/webviewWindow';
  import { RouterView, useRoute } from 'vue-router';
  import AppHeadBar from './components/app/app-head-bar/app-head-bar.vue';
  import bg1 from '@/assets/images/bg/bg-1.jpg';
  import bg2 from '@/assets/images/bg/bg-2.jpg';
  import { notHeadRoute } from './router/router';
  import { handlePlayClick } from '@/utils/prompt-tone';
  import { APP_HEADER_HEIGHT, tauri_floating_list_page_action } from '@/utils/constant';
  import AppDialogUpdata from './components/app/app-dialog-updata/app-dialog-updata.vue';
  import { checkUpdate } from '@/utils/tauri/updater-app';
  import type { FloatingListPageAction } from './utils/tauri/types';
  import { isTauri } from '@tauri-apps/api/core';

  const IS_TAURI = isTauri();
  const headHeight = ref(APP_HEADER_HEIGHT);
  const router = useRouter();
  const _route = useRoute();
  const userStore: UserStore = useUserStore();
  /** 判断当前页面是 智评会议，互动课堂还是其他页面 */
  const page = computed(() => (_route.path.startsWith('/tutorship') ? 'tutorship' : _route.path.startsWith('/interaction') ? 'interaction' : 'rest'));

  /** 页面背景 */
  const backgroundImage = ref<string | undefined>(undefined);
  /** 是否不需要背景和标题 */
  const isNotHaedRoute = ref(true);

  const webviewWindow = IS_TAURI ? WebviewWindow.getCurrent() : undefined;
  onMounted(() => {
    document.body.addEventListener('click', handlePlayClick);
    document.body.addEventListener('contextmenu', handleContextmenu);
    // 检测更新
    IS_TAURI && checkUpdate(false);
    nextTick(() => {
      if (_route.path && _route.path !== '/') {
        isNotHaedRoute.value = notHeadRoute.includes(_route.path);
        backgroundImage.value = isNotHaedRoute.value ? undefined : `url(${_route.path === '/login' ? bg1 : bg2})`;
      }
    });
    webviewWindow?.listen<FloatingListPageAction>(tauri_floating_list_page_action, ({ payload }) => {
      switch (payload) {
        case 'open-choice-topic':
          // 打开单选题
          openPage('/interaction/topic/choice-topic/choice-topic-index', '');
          break;
        case 'open-competition-topic':
          // 打开竞赛主观题
          openPage('/interaction/topic/competition-topic/competition-topic-index', '');
          break;
        case 'open-real-time-topic':
          // 打开实时主观题题
          openPage('/interaction/topic/real-time-topic/real-time-topic-index', '');
          break;
        case 'open-judge-topic':
          // 打开判断题
          openPage('/interaction/topic/judge-topic/judge-topic-index', '');
          break;
        case 'open-cloud-disk':
          // 打开云盘
          openPage('/interaction/cloud-disk/cloud-disk-list', '');
          break;
        case 'open-pk':
          // 打开判断题
          openPage('/interaction/pk/pk-index', '');
          break;
        case 'open-tutorship':
          // 打开辅导课程
          openPage('/tutorship/student-test-paper', '');
          break;
        case 'switch-courses':
          // 切换课程
          openPage('/select-classroom-type', `?type=${page.value === 'interaction' ? 'tutorship' : 'interaction'}`);
          break;
        case 'logout':
          // 登出账号
          userStore.logout();
          break;
        default:
          break;
      }
    });

    // setTimeout(() => {
    //   useRustWebSocket();
    // }, 1000);
  });

  onBeforeUnmount(() => {
    document.body.removeEventListener('click', handlePlayClick);
    document.body.removeEventListener('contextmenu', handleContextmenu);
  });

  /**
   * 屏蔽右键菜单
   */
  function handleContextmenu(event: MouseEvent) {
    if (IS_TAURI) {
      return;
    }
    const eventTarget = event.target as HTMLElement;
    // 判断点击的目标元素是否是输入框或文本域
    if (eventTarget.tagName === 'INPUT' || eventTarget.tagName === 'TEXTAREA') {
      // 如果是输入框，则不阻止默认行为，允许正常使用右键菜单
      return;
    }
    // 允许具有 'allow-right-click' 类的元素
    if (eventTarget.classList.contains('allow-right-click')) {
      return;
    }
    // 对于其他所有元素，阻止右键菜单弹出
    event.preventDefault();
  }

  watch(
    () => _route.path,
    (newPath) => {
      nextTick(() => {
        if (newPath) {
          // 处理背景图片
          isNotHaedRoute.value = notHeadRoute.includes(newPath);
          backgroundImage.value = isNotHaedRoute.value ? undefined : `url(${newPath === '/login' ? bg1 : bg2})`;
        }
      });
    }
  );

  /**
   * 打开页面
   */
  function openPage(path: string, param: string) {
    if (_route.path !== path) {
      router.replace(`${path}${param}`);
    }
  }
</script>

<style lang="scss">
  .app {
    display: flex;
    flex-direction: column;
    height: 100vh;
    overflow: hidden;
    background-attachment: fixed;
    background-size: 100% 100%;
  }

  .page-transform-enter-active,
  .page-transform-leave-active {
    transition: all 0.3s ease-out;
  }

  .page-transform-leave-active {
    position: absolute;
    z-index: 2;
  }

  .page-transform-enter-active {
    z-index: 3;
  }

  .page-transform-enter-from,
  .page-transform-leave-to {
    opacity: 0;
    transform: translateX(30%) skewX(-12deg);
  }
</style>
