<template>
  <div class="menu-container">
    <div
      style="box-sizing: border-box; width: 100%; padding: 10px; cursor: pointer"
      @click="toggleFold()"
      @mousedown="handleMouseDown"
      @touchstart="handleTouchStart"
    >
      <div style="width: 100%; height: 6px; background: rgba(255, 255, 255, 0.6); border-radius: 4px"></div>
    </div>
    <div class="time-container">
      <div class="time-box">
        <span class="time-text">{{ timeData.hour }}:{{ timeData.minute }}</span>
      </div>
    </div>
    <template v-if="isShowInteraction">
      <div class="menu-item" @click="openChoiceTopic()">
        <img class="menu-icon" src="@/assets/images/floating-list-window/icon_01_01.png" />
        <span class="menu-text">选择题</span>
      </div>
      <div class="menu-item" @click="openRealTimeTopic()">
        <img class="menu-icon" src="@/assets/images/floating-list-window/icon_01_02.png" />
        <span class="menu-text">实时题</span>
      </div>
      <div class="menu-item" @click="openCompetitionTopic()">
        <img class="menu-icon" src="@/assets/images/floating-list-window/icon_01_03.png" />
        <span class="menu-text">竞赛题</span>
      </div>
      <div class="menu-item" @click="openJudgeTopic()">
        <img class="menu-icon" src="@/assets/images/floating-list-window/icon_01_04.png" />
        <span class="menu-text">判断题</span>
      </div>
      <div class="menu-item" @click="openCloudDisk()">
        <img class="menu-icon" src="@/assets/images/floating-list-window/icon_01_05.png" />
        <span class="menu-text">云盘</span>
      </div>
      <!--
        <div class="menu-item" @click="openPk()">
        <img class="menu-icon" src="@/assets/images/floating-list-window/icon_01_06.png" />
        <span class="menu-text">PK赛</span>
        </div> 
      -->
    </template>
    <template v-if="isShowTutorship">
      <div style="width: calc(100% - 12px); height: 1px; margin: 9px 10px; background: rgba(180, 180, 180, 0.6)"></div>
      <div class="menu-item tutorship-item" @click="openTutorship()">
        <img class="menu-icon" style="width: 32px; height: 32px; margin-bottom: 2px" src="@/assets/images/floating-list-window/icon_02_01.png" />
        <span class="menu-text">评讲</span>
      </div>
      <div class="menu-item tutorship-item" @click="openMeeting()">
        <img class="menu-icon" src="@/assets/images/floating-list-window/icon_02_02.png" />
        <span class="menu-text">会议控制</span>
      </div>
      <div class="menu-item tutorship-item" @click="openSubtitle()">
        <img class="menu-icon" src="@/assets/images/floating-list-window/icon_02_03.png" />
        <span class="menu-text">实时字幕</span>
      </div>
    </template>
    <div style="width: calc(100% - 12px); height: 1px; margin: 9px 10px; background: rgba(180, 180, 180, 0.6)"></div>
    <div class="menu-item" @click="openDrawingBoard()">
      <img class="menu-icon" src="@/assets/images/floating-list-window/icon_03_01.png" />
      <span class="menu-text">画板</span>
    </div>
    <div class="menu-item" @click="switchCourses()">
      <img class="menu-icon" src="@/assets/images/floating-list-window/icon_03_03.png" />
      <span class="menu-text">切换课程</span>
    </div>
    <div class="menu-item" @click="logout()">
      <img class="menu-icon" src="@/assets/images/floating-list-window/icon_03_04.png" />
      <span class="menu-text">退出登录</span>
    </div>
  </div>
</template>

<script setup lang="ts">
  import { ref, watch } from 'vue';
  import { emitTo } from '@tauri-apps/api/event';
  import { createDrawingBoardWindow, createMainWindow, createMeetingWindow, createSubtitleWindow } from '@/utils/tauri/windows-action';
  import { windowLabel } from '@/utils/tauri/windows-util';
  import { tauri_floating_list_page_action } from '@/utils/constant';
  import { handleMouseDown, handleTouchStart, startWindowX, startWindowY } from '../move-window';

  import { LogicalSize, getCurrentWindow } from '@tauri-apps/api/window';
  import { useTauriSessionStorage } from './use-tauri-session-storage';
  import { playPromptTone } from '@/utils/prompt-tone';
  import type { FloatingListPageAction } from '@/utils/tauri/types';
  const isFold = defineModel<boolean>();

  const timeData = ref({ hour: '00', minute: '00' });
  let timer: NodeJS.Timeout | null = null;

  const currentWindow = getCurrentWindow();
  const isShowInteraction = ref(false);
  const isShowTutorship = ref(false);

  const { userInfo, currTutorship, currCourse, updateBaseDate } = useTauriSessionStorage();

  watch(
    () => [currTutorship.value, currCourse.value, userInfo.value],
    ([_currTutorship, _currCourse, _userInfo]) => {
      let item_num = 4;
      if (_userInfo) {
        if (currCourse.value) {
          isShowInteraction.value = true;
          item_num += 5;
        } else {
          isShowInteraction.value = false;
        }

        if (_currTutorship) {
          isShowTutorship.value = true;
          item_num += 3;
        } else {
          isShowTutorship.value = false;
        }
      } else {
        isShowInteraction.value = false;
        isShowTutorship.value = false;
      }

      // 总高度 =  item高度 * 项目数 + 额外用于移动按钮和时间部分的高度
      const popup_height = 64 * item_num + 60;
      const popup_width = 60;
      currentWindow.setSize(new LogicalSize(popup_width, popup_height));
    }
  );

  onMounted(() => {
    setInterval(() => {
      updateBaseDate();
    }, 2000);
    updateTime(); // 初始化时立即更新
    scheduleNextUpdate(); // 设置后续更新
    updateBaseDate();
  });

  onBeforeUnmount(() => {
    timer && clearTimeout(timer);
  });

  /**
   * 计算到下一秒的毫秒数
   */
  function getDelayToNextSecond(): number {
    const now = new Date();
    const delay = 1000 - now.getMilliseconds();
    return delay;
  }

  /**
   * 设置下一个更新周期
   */
  function scheduleNextUpdate() {
    const delay = getDelayToNextSecond();
    timer = setTimeout(() => {
      updateTime();
      scheduleNextUpdate(); // 递归调用以继续更新
    }, delay);
  }

  /**
   * 更新当前时间数据和格式化字符串
   */
  function updateTime() {
    const now = new Date();
    timeData.value = {
      hour: now.getHours().toString().padStart(2, '0'),
      minute: now.getMinutes().toString().padStart(2, '0'),
    };
  }

  /**
   * 切换折叠状态
   */
  async function toggleFold() {
    // 获取缩放因子和窗口物理位置
    const [factor, windowPhysicalPosition] = await Promise.all([currentWindow.scaleFactor(), currentWindow.outerPosition()]);
    // 转换为逻辑像素位置
    const windowPosition = windowPhysicalPosition.toLogical(factor);

    const newX = windowPosition.x - startWindowX.value;
    const newY = windowPosition.y - startWindowY.value;
    if (Math.abs(newX) < 4 && Math.abs(newY) < 4) {
      playPromptTone();
      isFold.value = !isFold.value;
    }
  }

  /**
   * 打开选择题
   */
  async function openChoiceTopic() {
    playPromptTone();
    await createMainWindow();
    sendtPageActionEmit('open-choice-topic');
  }

  /**
   * 实时主观题
   */
  async function openRealTimeTopic() {
    playPromptTone();
    await createMainWindow();
    sendtPageActionEmit('open-real-time-topic');
  }

  /**
   * 竞赛主观题
   */
  async function openCompetitionTopic() {
    playPromptTone();
    await createMainWindow();
    sendtPageActionEmit('open-competition-topic');
  }

  /**
   * 判断题
   */
  async function openJudgeTopic() {
    playPromptTone();
    await createMainWindow();
    sendtPageActionEmit('open-judge-topic');
  }

  /**
   * 打开辅导课程
   */
  async function openTutorship() {
    playPromptTone();
    await createMainWindow();
    sendtPageActionEmit('open-tutorship');
  }

  /**
   * 打开云盘
   */
  async function openCloudDisk() {
    playPromptTone();
    await createMainWindow();
    sendtPageActionEmit('open-cloud-disk');
  }
  /**
   * 打开PK赛
   */
  // async function openPk() {
  //   playPromptTone();
  //   await createMainWindow();
  //   sendtPageActionEmit('open-pk');
  // }

  /**
   * 切换课程
   */
  async function switchCourses() {
    playPromptTone();
    await createMainWindow();
    sendtPageActionEmit('switch-courses');
  }

  /**
   * 打开会议
   */
  async function openMeeting() {
    playPromptTone();

    await createMeetingWindow(2, currTutorship.value?.id);
  }

  /**
   * 打开字幕
   */
  async function openSubtitle() {
    playPromptTone();
    await createSubtitleWindow();
  }

  /**
   * 打开画板
   */
  async function openDrawingBoard() {
    playPromptTone();
    await createDrawingBoardWindow();
  }

  /**
   * 退出登录
   */
  async function logout() {
    playPromptTone();
    await createMainWindow();
    sendtPageActionEmit('logout');
  }

  /**
   * 向某个窗口发送消息
   */
  function sendtPageActionEmit(action: FloatingListPageAction) {
    emitTo<FloatingListPageAction>(windowLabel.main, tauri_floating_list_page_action, action);
  }
</script>

<style scoped lang="scss">
  body {
    width: 100vw;
    height: 100vh;
    padding: 0;
    margin: 0;
  }

  div,
  span,
  img {
    user-select: none;
    -webkit-user-drag: none;
  }

  .time-container {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    margin-bottom: 10px;

    .time-box {
      display: flex;
      align-items: flex-end;
      justify-content: center;
      width: 100%;
      margin-bottom: 2px;
      line-height: 1;

      .time-text {
        font-size: 18px;
        font-weight: bold;
        color: #ffffff;
        text-shadow:
          1px 1px 2px #000000,
          0 0 4px #000000;
      }

      .time-unit {
        margin-left: 2px;
        font-size: 12px;
        color: #ffffff;
        text-shadow:
          1px 1px 2px #000000,
          0 0 4px #000000;
      }
    }
  }

  .menu-container {
    box-sizing: border-box;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    width: 100vw;
    height: 100vh;
    padding: 10px 0;
    overflow: hidden;
    background: rgba(0, 0, 0, 0.2);
    border-radius: 6px;
  }

  .menu-container .menu-item {
    display: flex;
    flex: 1;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    width: 100%;
  }

  .menu-container .menu-item .menu-icon {
    width: 36px;
    height: 36px;
  }

  .menu-container .menu-item .menu-text {
    font-size: 12px;
    color: #ffffff;
    text-shadow: 2px 2px 4px #000000;
  }
</style>
