<template>
  <div class="live">
    <back title="オンライン授業"></back>
    <div id="liveContent" class="liveContent" ref="liveContent">
      <div id="screenAudio" style="display: none" ref="screenAudio"></div>
      <div class="live-status" v-show="liveStatus == 'scheduled'">
        <svg
          t="1733991622296"
          class="icon"
          viewBox="0 0 1024 1024"
          version="1.1"
          xmlns="http://www.w3.org/2000/svg"
          p-id="7587"
          width="38"
          height="38"
          data-spm-anchor-id="a313x.search_index.0.i3.59a33a81UKNXHQ"
        >
          <path
            d="M526.933333 288c-23.466667 0-42.666667 19.2-42.666666 42.666667v213.333333c0 23.466667 19.2 42.666667 42.666666 42.666667s42.666667-19.2 42.666667-42.666667v-213.333333c0-23.466667-17.066667-42.666667-42.666667-42.666667zM526.933333 629.333333c-12.8 0-21.333333 4.266667-29.866666 12.8-8.533333 8.533333-12.8 17.066667-12.8 29.866667 0 12.8 4.266667 23.466667 12.8 29.866667 8.533333 8.533333 19.2 12.8 29.866666 12.8 12.8 0 21.333333-4.266667 29.866667-12.8s12.8-19.2 12.8-32-4.266667-23.466667-12.8-29.866667c-6.4-6.4-17.066667-10.666667-29.866667-10.666667z"
            p-id="7588"
            fill="#ffffff"
          ></path>
          <path
            d="M526.933333 74.666667c-234.666667 0-426.666667 192-426.666666 426.666666s192 426.666667 426.666666 426.666667 426.666667-192 426.666667-426.666667-189.866667-426.666667-426.666667-426.666666z m0 768c-187.733333 0-341.333333-153.6-341.333333-341.333334s153.6-341.333333 341.333333-341.333333 341.333333 153.6 341.333334 341.333333-151.466667 341.333333-341.333334 341.333334z"
            p-id="7589"
            fill="#ffffff"
          ></path>
        </svg>
        オンライン授業未开始
      </div>
      <div class="live-status" v-show="liveStatus == 'finished'">
        <svg
          t="1733991622296"
          class="icon"
          viewBox="0 0 1024 1024"
          version="1.1"
          xmlns="http://www.w3.org/2000/svg"
          p-id="7587"
          width="38"
          height="38"
          data-spm-anchor-id="a313x.search_index.0.i3.59a33a81UKNXHQ"
        >
          <path
            d="M526.933333 288c-23.466667 0-42.666667 19.2-42.666666 42.666667v213.333333c0 23.466667 19.2 42.666667 42.666666 42.666667s42.666667-19.2 42.666667-42.666667v-213.333333c0-23.466667-17.066667-42.666667-42.666667-42.666667zM526.933333 629.333333c-12.8 0-21.333333 4.266667-29.866666 12.8-8.533333 8.533333-12.8 17.066667-12.8 29.866667 0 12.8 4.266667 23.466667 12.8 29.866667 8.533333 8.533333 19.2 12.8 29.866666 12.8 12.8 0 21.333333-4.266667 29.866667-12.8s12.8-19.2 12.8-32-4.266667-23.466667-12.8-29.866667c-6.4-6.4-17.066667-10.666667-29.866667-10.666667z"
            p-id="7588"
            fill="#ffffff"
          ></path>
          <path
            d="M526.933333 74.666667c-234.666667 0-426.666667 192-426.666666 426.666666s192 426.666667 426.666666 426.666667 426.666667-192 426.666667-426.666667-189.866667-426.666667-426.666667-426.666666z m0 768c-187.733333 0-341.333333-153.6-341.333333-341.333334s153.6-341.333333 341.333333-341.333333 341.333333 153.6 341.333334 341.333333-151.466667 341.333333-341.333334 341.333334z"
            p-id="7589"
            fill="#ffffff"
          ></path>
        </svg>
        オンライン授業が終わる
      </div>
      <div
        class="watermark-container"
        v-if="isVisible"
        @animationend="onAnimationEnd"
        :key="animationKey"
      >
        {{ loginInfo.member_realname }}_{{ loginInfo.member_passport }}
      </div>
      <div id="teacherCamera" class="teacherCamera" ref="teacherCamera"></div>
      <!-- <div class="custom-controls" v-show="showControlBar">
        <div class="teacherAudioList" v-show="teacherAudioList.length > 0">
          <div v-for="(teacherAudio, index) in teacherAudioList" class="teacherAudio">
            {{ teacherAudio.name }}
            <div
              class="teacherAudioControl"
              @mouseenter="showVolumeControl(index)"
              @mouseleave="hideVolumeControl(index)"
            >
              <svg
                t="1738985833209"
                class="icon"
                viewBox="0 0 1024 1024"
                version="1.1"
                xmlns="http://www.w3.org/2000/svg"
                p-id="4264"
                width="18"
                height="18"
                v-show="!teacherAudio.isMute"
                @click="changeTeacherAudio(index)"
              >
                <path
                  d="M810.666667 384a42.666667 42.666667 0 0 1 42.666666 42.666667v85.333333a341.376 341.376 0 0 1-298.624 338.688L554.666667 938.666667h128a42.666667 42.666667 0 0 1 0 85.333333H341.333333a42.666667 42.666667 0 0 1 0-85.333333h128v-87.978667A341.376 341.376 0 0 1 170.666667 512v-85.333333a42.666667 42.666667 0 1 1 85.333333 0v85.333333a256 256 0 0 0 246.4 255.829333L512 768a256 256 0 0 0 255.829333-246.4L768 512v-85.333333a42.666667 42.666667 0 0 1 42.666667-42.666667z m-298.666667-384a170.666667 170.666667 0 0 1 170.666667 170.666667v341.333333a170.666667 170.666667 0 1 1-341.333334 0V170.666667a170.666667 170.666667 0 0 1 170.666667-170.666667z m0 85.333333a85.333333 85.333333 0 0 0-85.12 78.933334L426.666667 170.666667v341.333333a85.333333 85.333333 0 0 0 170.453333 6.4L597.333333 512V170.666667a85.333333 85.333333 0 0 0-85.333333-85.333334z"
                  fill="#ffffff"
                  p-id="4265"
                ></path>
              </svg>
              <svg
                t="1738986502466"
                class="icon"
                viewBox="0 0 1024 1024"
                version="1.1"
                xmlns="http://www.w3.org/2000/svg"
                p-id="3695"
                width="18"
                height="18"
                v-show="teacherAudio.isMute"
                @click="changeTeacherAudio(index)"
              >
                <path
                  d="M68.953316 9.064877l4.010252 3.540967 938.569681 938.569681a42.662258 42.662258 0 0 1-56.314181 63.865401l-4.010252-3.540968-229.864247-229.821585A339.591576 339.591576 0 0 1 554.74845 850.705907L554.74845 938.675484h127.986775a42.662258 42.662258 0 0 1 0 85.324516H341.437159a42.662258 42.662258 0 0 1 0-85.324516h127.986775v-87.969577A341.340728 341.340728 0 0 1 170.788126 512.052901v-85.324516a42.662258 42.662258 0 1 1 85.324517 0v85.324516a255.973549 255.973549 0 0 0 246.374541 255.802901L512.086192 768.026451c55.290287 0 106.442334-17.491526 148.29401-47.312445L12.639135 72.930277A42.662258 42.662258 0 0 1 68.953316 9.064877zM810.722 384.066127a42.662258 42.662258 0 0 1 42.662258 42.662258v170.649033a42.662258 42.662258 0 0 1-85.324516 0v-170.649033a42.662258 42.662258 0 0 1 42.662258-42.662258z m-298.635808-383.960325a170.649033 170.649033 0 0 1 170.649033 170.649033v255.97355a42.662258 42.662258 0 0 1-85.324516 0V170.754835a85.324516 85.324516 0 0 0-85.324517-85.324516c-42.832907 0-78.285244 31.570071-84.599258 78.199919L426.761676 170.754835a42.662258 42.662258 0 0 1-85.025881 4.991485L341.437159 170.754835a170.649033 170.649033 0 0 1 170.649033-170.649033z"
                  fill="#ffffff"
                  p-id="3696"
                ></path>
              </svg>
              <div
                class="teacherAudioRangeContainer"
                v-show="teacherAudio.showVolumeControl"
              >
                <input
                  type="range"
                  min="0"
                  max="1"
                  step="0.01"
                  value="1"
                  class="teacherAudioRange"
                  @change="changeTeacherVolume($event, index)"
                />
              </div>
            </div>
          </div>
        </div>

        <div class="screenAudio">
          <svg
            fill="Window"
            height="24"
            viewBox="0 0 24 24"
            width="24"
            xmlns="http://www.w3.org/2000/svg"
            v-show="!audioMute"
            @click="changeAudio()"
          >
            <path
              d="M3 9v6h4l5 5V4L7 9H3zm13.5 3c0-1.77-1.02-3.29-2.5-4.03v8.05c1.48-.73 2.5-2.25 2.5-4.02zM14 3.23v2.06c2.89.86 5 3.54 5 6.71s-2.11 5.85-5 6.71v2.06c4.01-.91 7-4.49 7-8.77s-2.99-7.86-7-8.77z"
            />
            <path d="M0 0h24v24H0z" fill="none" />
          </svg>
          <svg
            fill="Window"
            height="24"
            viewBox="0 0 24 24"
            width="24"
            xmlns="http://www.w3.org/2000/svg"
            v-show="audioMute"
            @click="changeAudio()"
          >
            <path
              d="M16.5 12c0-1.77-1.02-3.29-2.5-4.03v2.21l2.45 2.45c.03-.2.05-.41.05-.63zm2.5 0c0 .94-.2 1.82-.54 2.64l1.51 1.51C20.63 14.91 21 13.5 21 12c0-4.28-2.99-7.86-7-8.77v2.06c2.89.86 5 3.54 5 6.71zM4.27 3L3 4.27 7.73 9H3v6h4l5 5v-6.73l4.25 4.25c-.67.52-1.42.93-2.25 1.18v2.06c1.38-.31 2.63-.95 3.69-1.81L19.73 21 21 19.73l-9-9L4.27 3zM12 4L9.91 6.09 12 8.18V4z"
            />
            <path d="M0 0h24v24H0z" fill="none" />
          </svg>
          <input
            type="range"
            min="0"
            max="1"
            step="0.01"
            value="1"
            @change="changeVolume($event)"
            style="width: 100px"
          />
        </div>
        <div class="fullScreen" id="fullScreen" @click="requestFullScreen()">
          <svg
            fill="Window"
            height="24"
            viewBox="0 0 24 24"
            width="24"
            xmlns="http://www.w3.org/2000/svg"
            v-show="!isfullScreen"
          >
            <path d="M0 0h24v24H0z" fill="none" />
            <path
              d="M7 14H5v5h5v-2H7v-3zm-2-4h2V7h3V5H5v5zm12 7h-3v2h5v-5h-2v3zM14 5v2h3v3h2V5h-5z"
            />
          </svg>
          <svg
            fill="Window"
            height="24"
            viewBox="0 0 24 24"
            width="24"
            xmlns="http://www.w3.org/2000/svg"
            v-show="isfullScreen"
          >
            <path d="M0 0h24v24H0z" fill="none" />
            <path
              d="M5 16h3v3h2v-5H5v2zm3-8H5v2h5V5H8v3zm6 11h2v-3h3v-2h-5v5zm2-11V5h-2v5h5V8h-3z"
            />
          </svg>
        </div>
      </div> -->
    </div>
    <div class="menubar">
      <div class="menubar-one">
        <div class="menubar-name" @click="goMenubar(1)">チャット</div>
        <div class="current-select" v-show="isCurrentMenubar == 1"></div>
      </div>
      <div class="menubar-one">
        <div class="menubar-name" @click="goMenubar(2)">紹介</div>
        <div class="current-select" v-show="isCurrentMenubar == 2"></div>
      </div>
    </div>
    <div class="bottom-content">
      <div class="chat-content" v-show="isCurrentMenubar == 1">
        <div class="message-content">
          <transition-group name="message" tag="div">
            <div v-for="(message, index) in messages" :key="message.id" class="message">
              <img :src="message.avatar" alt="avatar" class="avatar" />
              <div class="message-body">
                <div class="message-header">
                  <span class="message-sender"
                    ><span
                      class="teacher-tag"
                      v-if="message.sender.slice(0, 7) === 'teacher'"
                      >講師</span
                    >{{ message.sender }}</span
                  >
                  <span class="message-time">{{
                    "\u00A0\u00A0\u00A0" + formatTimestamp(message.time)
                  }}</span>
                </div>
                <div class="message-text">{{ message.text }}</div>
              </div>
            </div>
          </transition-group>
          <!-- 用于滚动到该元素 -->
          <div ref="scrollAnchor"></div>
        </div>
        <div class="message-input">
          <input
            v-model="newMessage"
            @keyup.enter="sendMessage"
            placeholder="メッセージを入力..."
          />
          <button @click="sendMessage">送信</button>
        </div>
      </div>
      <div class="info-content" v-show="isCurrentMenubar == 2">
        <div class="info-content-item">
          <div class="info-content-item-title">コース名</div>
          <div class="info-content-item-value">{{ liveInfo.title }}</div>
        </div>
        <div class="info-content-item">
          <div class="info-content-item-title">講義の先生</div>
          <div class="info-content-item-value">{{ liveInfo.teacher }}</div>
        </div>
        <div class="info-content-item">
          <div class="info-content-item-title">開始時間</div>
          <div class="info-content-item-value">{{ liveInfo.start_time }}</div>
        </div>
        <div
          class="info-content-item"
          v-show="liveInfo.end_time != '' && liveInfo.end_time != null"
        >
          <div class="info-content-item-title">終了時間</div>
          <div class="info-content-item-value">{{ liveInfo.end_time }}</div>
        </div>
        <div class="info-content-item" style="">
          <div class="info-content-item-title">詳細</div>
          <div
            class="info-content-item-value"
            style="
              display: flex;
              flex-direction: column;
              align-items: center;
              padding-top: 10px;
            "
          >
            <svg
              t="1733988199430"
              class="icon"
              viewBox="0 0 1024 1024"
              version="1.1"
              xmlns="http://www.w3.org/2000/svg"
              p-id="6925"
              data-spm-anchor-id="a313x.search_index.0.i0.14ef3a81TzRpck"
              width="64"
              height="64"
              xmlns:xlink="http://www.w3.org/1999/xlink"
            >
              <path
                d="M892.5 304.6L689.4 101.4c-22.7-22.7-52.8-35.1-84.9-35.1H218.7c-66.2 0-120 53.8-120 120v654.1c0 66.2 53.8 120 120 120h589c66.2 0 120-53.8 120-120v-451c0-32-12.5-62.2-35.2-84.8zM667.7 192.9l123.4 123.4h-83.4c-22.1 0-40-17.9-40-40v-83.4z m140 687.5h-589c-22.1 0-40-17.9-40-40V186.3c0-22.1 17.9-40 40-40h369v130c0 66.2 53.8 120 120 120h140v444.1c0 22-17.9 40-40 40z"
                p-id="6926"
                fill="#8a8a8a"
              ></path>
              <path
                d="M310 378.1h177.1c22.1 0 40-17.9 40-40s-17.9-40-40-40H310c-22.1 0-40 17.9-40 40s17.9 40 40 40zM716.4 473.3H310c-22.1 0-40 17.9-40 40s17.9 40 40 40h406.4c22.1 0 40-17.9 40-40s-17.9-40-40-40zM716.4 648.6H310c-22.1 0-40 17.9-40 40s17.9 40 40 40h406.4c22.1 0 40-17.9 40-40s-17.9-40-40-40z"
                p-id="6927"
                fill="#8a8a8a"
              ></path>
            </svg>
            詳細なし
          </div>
        </div>
      </div>
    </div>
    <div id="studentCamera" class="studentCamera" ref="studentCamera"></div>
  </div>
</template>

<script>
import QNRTC, { QNLogLevel } from "qnweb-rtc";
import Back from "../common/Back";
import { getStore } from "@/utils/storage";
import { mapState } from "vuex";
import { MessageBox } from "mint-ui";
import { v4 as uuidv4 } from "uuid";
// QNRTC.setLogLevel(QNLogLevel.NONE);
export default {
  components: { Back },
  data() {
    return {
      myClient: null,
      liveTitle: "オンライン授業",
      liveInfo: {
        description: "",
        title: "",
        room: "",
        start_time: "",
        status: "",
        teacher: "",
        end_time: "",
      },
      liveContent: "", //放置直播video

      externalUrl: "",
      localTracks: null,
      isfullScreen: false,
      audioMute: false,
      roomName: "",
      showControlBar: false,
      controlarTimeout: null,
      isVisible: false,
      isStop: false,
      animationKey: 0,
      liveStatus: "scheduled",
      liveId: null,
      isCurrentMenubar: 1,
      messages: [],
      newMessage: "",
      teacherAudioList: [],
    };
  },
  mounted() {
    this.roomName = this.$route.query.roomName;
    console.log("房间名：", this.roomName);
    if (this.roomName === undefined) {
      MessageBox({
        title: "ヒント",
        message: "番号の獲得できません、オンライン教室に再び入室してください",
        confirmButtonText: "確定",
      });
      return;
    }
    this.liveContent = this.$refs.liveContent;
    this.addVideoEventListeners(this.liveContent);
    // console.log("current version is", QNRTC.VERSION);
    this.initRoom();
    MessageBox({
      title: "ヒント",
      message: "オンライン授業に参加する際に、カメラをオンにします",
      confirmButtonText: "確定",
    });
  },
  methods: {
    initRoom() {
      // const roomName = "jiangtang360";
      this.getData("/MemberVideo/getRoomToken", {
        token: getStore("token"),
        roomName: this.roomName,
        passport: this.loginInfo.member_passport,
      }).then((res) => {
        if (res.code === 1) {
          this.liveStatus = res.data.status;
          this.liveTitle = res.data.title;
          this.liveId = res.data.live_id;
          this.liveInfo = res.data;
          // console.log("直播信息:", res.data);

          this.joinRoom(res.data.roomToken);
        } else {
          MessageBox.close(false);
          MessageBox({
            title: "ヒント",
            message: res.msg,
            confirmButtonText: "確定",
          });
        }
      });
    },
    async joinRoom(roomToken) {
      const myRoom = QNRTC.createClient();
      this.myClient = myRoom;
      // 提前订阅
      this.autoSubscribe(myRoom);

      await myRoom.join(roomToken);
      console.log("加入房间成功");
      // 发布本地音视频
      await this.publish(myRoom);
    },
    async publish(myRoom) {
      try {
        this.localTracks = await QNRTC.createCameraVideoTrack({ tag: "video" });
      } catch (error) {
        console.log("获取摄像头轨道报错：", error);
        MessageBox.close(false);
        MessageBox({
          title: "ヒント",
          message: "カメラを開けませんでした",
          confirmButtonText: "確定",
        });
        return;
      }
      // console.log("我的本地轨道：", this.localTracks);
      await myRoom.publish(this.localTracks);
      console.log("发布成功");
      // 获取页面上的一个元素作为播放画面的父元素
      this.localTracks.play(this.$refs.studentCamera, {
        mirror: true,
      });
    },

    async subscribe(myRoom, tracks, userId) {
      if (userId.slice(0, 7) === "teacher") {
        this.liveStatus = "live";
        // 传入 Track 对象数组调用订阅方法发起订阅，异步返回成功订阅的 Track 对象。
        const { audioTracks, videoTracks } = await myRoom.subscribe(tracks);
        for (let index = 0; index < audioTracks.length; index++) {
          if (audioTracks[index].tag === "screenaudio") {
            const audioElements = this.$el.querySelectorAll(".screenAudio > audio");
            // console.log("存在屏幕共享声音，，，，：：：：", audioElements);

            if (audioElements.length > 0) {
              audioElements.forEach((audio) => {
                audio.remove(); // 移除 <video> 元素
              });
            }
            audioTracks[index].play(this.$refs.screenAudio);
          } else {
            this.teacherAudioList.push({
              name: audioTracks[index].userID,
              isMute: false,
              showVolumeControl: false,
            });
            // console.log("teacherAudioList:", this.teacherAudioList);

            audioTracks[index].play(this.liveContent);
          }
        }

        for (let index = 0; index < videoTracks.length; index++) {
          if (videoTracks[index].tag === "screenvideo") {
            // 获取所有子元素中的 <video> 标签
            const videoElements = this.$el.querySelectorAll(".liveContent > video");
            // 如果存在 <video> 标签，则遍历并移除它们
            // console.log("存在屏幕共享：：：：", videoElements);

            if (videoElements.length > 0) {
              videoElements.forEach((video) => {
                video.remove(); // 移除 <video> 元素
              });
            }
            videoTracks[index].play(this.liveContent);

            // 使用 setTimeout 确保视频元素完全创建后再设置控件
            setTimeout(() => {
              const videos = document.querySelectorAll(
                "video.qnrtc-video-player.qnrtc-stream-player"
              );
              // 遍历这些元素并添加 controls 属性
              for (let i = 0; i < videos.length; i++) {
                videos[i].controls = true;
                // 确保控件可见
                videos[i].style.pointerEvents = "auto";
                //关闭画中画
                videos[i].disablePictureInPicture = true;
                // 打破视频宽高比，全部填充
                videos[i].style.objectFit = "contain";
                // 关闭右键菜单
                videos[i].addEventListener("contextmenu", function (e) {
                  e.preventDefault();
                });
                //添加水印
                setTimeout(() => {
                  this.isStop = false;
                  this.isVisible = true;
                }, 10000);
              }
            }, 100);
          } else if (videoTracks[index].tag === "video") {
            const teacherCameraElement = this.$refs.teacherCamera;
            // 获取所有子元素中的 <video> 标签
            const videoElements = teacherCameraElement.querySelectorAll("video");

            // 如果存在 <video> 标签，则遍历并移除它们
            if (videoElements.length > 0) {
              videoElements.forEach((video) => {
                video.remove(); // 移除 <video> 元素
              });
            }
            videoTracks[index].play(teacherCameraElement);
          }
        }
      }
    },

    // 这里的参数 myRoom 是指刚刚加入房间时初始化的 Session 对象, 同上
    autoSubscribe(myRoom) {
      var _this = this;
      // 监听远程轨道
      myRoom.on("user-published", (userId, tracks) => {
        // console.log("监听获取远程轨道", userId, tracks);
        this.subscribe(myRoom, tracks, userId)
          .then(() => console.log("订阅成功!"))
          .catch((e) => console.error("订阅失败", e));
      });

      // 监听远程轨道断开
      myRoom.on("user-unpublished", (userID, track) => {
        // console.log("user-unpublished取消丁月月呃呃呃呃呃呃", userID, track);
        if (userID.slice(0, 7) === "teacher") {
          for (let index = 0; index < track.length; index++) {
            if (track[index].tag === "screenvideo") {
              // 获取所有子元素中的 <video> 标签
              const videoElements = _this.$el.querySelectorAll(".liveContent > video");
              if (videoElements.length <= 0) {
                _this.isStop = true;
                _this.isVisible = false;
              }
            } else if (track[index].tag === "audio") {
              _this.teacherAudioList = _this.teacherAudioList.filter(
                (item) => item.name !== userID
              );
            }
          }
        }
      });

      // 监听远程用户离开
      myRoom.on("user-left", (userID) => {
        // console.log("user-left用户离开", userID);
        if (userID.slice(0, 7) === "teacher") {
          //查看直播状态
          _this
            .getData("/MemberVideo/getLivestatus", {
              token: getStore("token"),
              liveId: _this.liveId,
            })
            .then((res) => {
              _this.liveStatus = res.data.status;
            });
        }
      });

      myRoom.on("ended", () => {
        // console.log(`track: ${track.tag} ended!`);
        // 后续逻辑
        // 1. 通知用户
        // 2. 自动重新采集
        // 3. 其他等...
      });

      myRoom.on("connection-state-changed", function (connectionState, info) {
        // console.log("连接状态改变：", connectionState);
        // myRoom.leave();
        if (connectionState === myRoom.DISCONNECTED) {
          // 监控断开原因
          switch (info.reason) {
            // 当异常断开时
            case myRoom.ERROR:
              console.log("异常断开。。。。。。");

              myRoom.leave();
              break;
            // 当被踢出房间时
            case myRoom.KICKED_OUT:
              break;
            // 当调用接口，主动离开房间时
            case myRoom.LEAVE:
              console.log("主动离开房间............");
              myRoom.leave();
              break;
          }
        }
      });

      // 监听消息
      myRoom.on("message-received", (message) => {
        // console.log("收到消息：", message);
        // 找到最后一个“--”的位置
        const lastIndex = message.content.lastIndexOf("--");

        // 获取最后一个“--”后面的名字
        const name = message.content.substring(lastIndex + 2);

        // 获取去掉最后一个“--”以及名字的字符串
        const newStr = message.content.substring(0, lastIndex);

        this.messages.push({
          id: message.ID,
          sender: message.userID.slice(0, 7) === "teacher" ? message.userID : name,
          text: newStr,
          avatar:
            "data:image/svg+xml;base64," +
            btoa(`
          <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="40" height="40">
            <circle cx="12" cy="12" r="10" fill="#ccc"/>
            <circle cx="12" cy="10" r="4" fill="#fff"/>
            <path d="M12 14c-4 0-6 2-6 4v1h12v-1c0-2-2-4-6-4z" fill="#fff"/>
          </svg>
        `), // 默认头像
          time: message.timestamp,
        });
        this.$nextTick(() => {
          this.scrollToBottom();
        });
      });
    },

    changeTeacherAudio(index) {
      // 获取所有子元素中的 <audio> 标签
      const videoElements = this.$el.querySelectorAll(".liveContent > audio");
      // 如果存在 <audio> 标签，则遍历并移除它们
      // console.log("存在老师audio元素：：：：", videoElements);

      if (videoElements[index] !== undefined) {
        videoElements[index].muted = !videoElements[index].muted;
        this.teacherAudioList[index].isMute = videoElements[index].muted;
      }
    },

    showVolumeControl(index) {
      this.teacherAudioList[index].showVolumeControl = true;
    },
    hideVolumeControl(index) {
      this.teacherAudioList[index].showVolumeControl = false;
    },
    changeAudio() {
      const screenAudioElenets = this.$refs.screenAudio;
      const audioElements = screenAudioElenets.querySelectorAll("audio");
      if (this.audioMute) {
        if (audioElements.length > 0) {
          audioElements.forEach((audio) => {
            audio.muted = false;
          });
        }
      } else {
        if (audioElements.length > 0) {
          audioElements.forEach((audio) => {
            audio.muted = true;
          });
        }
      }
      this.audioMute = !this.audioMute;
    },

    changeTeacherVolume(e, index) {
      const videoElements = this.$el.querySelectorAll(".liveContent > audio");
      if (videoElements[index] !== undefined) {
        videoElements[index].volume = e.target.value;
      }
    },
    changeVolume(e) {
      const screenAudioElenets = this.$refs.screenAudio;
      const audioElements = screenAudioElenets.querySelectorAll("audio");
      if (audioElements.length > 0) {
        // console.log("changeVolume木木", e.target.value);
        audioElements.forEach((audio) => {
          audio.volume = e.target.value;
        });
      }
    },

    addVideoEventListeners(videoElement) {
      videoElement.addEventListener("mouseenter", this.showControls);
      videoElement.addEventListener("mousemove", this.onMouseMove);
      videoElement.addEventListener("mouseleave", this.hideControls);
    },

    removeVideoEventListeners(videoElement) {
      videoElement.removeEventListener("mouseenter", this.showControls);
      videoElement.removeEventListener("mousemove", this.onMouseMove);
      videoElement.removeEventListener("mouseleave", this.hideControls);
    },
    // Show controls on mouse enter
    showControls() {
      this.showControlBar = true;
    },
    // Hide controls after a delay
    hideControls() {
      clearTimeout(this.controlBarTimeout);
      this.controlBarTimeout = setTimeout(() => {
        this.showControlBar = false;
      }, 3000);
    },
    // Show controls when mouse moves
    onMouseMove() {
      this.showControls();
      this.hideControls();
    },

    //进入全屏状态
    requestFullScreen() {
      const fullscreen = this.$refs.liveContent;
      // const fullscreens = document.querySelectorAll(
      //   "video.qnrtc-video-player.qnrtc-stream-player"
      // );
      // const fullscreen = fullscreens[0]

      if (!document.fullscreenElement) {
        const videoElement = fullscreen.querySelector("video");

        // 针对 iOS 设备的特殊处理
        if (
          videoElement &&
          /iPad|iPhone|iPod/.test(navigator.userAgent) &&
          !window.MSStream
        ) {
          if (videoElement.webkitEnterFullscreen) {
            videoElement.webkitEnterFullscreen();
            this.isfullScreen = true;
            return;
          }
        }
        //当前元素没有全屏
        if (fullscreen.requestFullscreen) {
          fullscreen.requestFullscreen();
        } else if (fullscreen.mozRequestFullScreen) {
          fullscreen.mozRequestFullScreen();
        } else if (fullscreen.webkitRequestFullscreen) {
          fullscreen.webkitRequestFullscreen();
        } else if (fullscreen.msRequestFullscreen) {
          fullscreen.msRequestFullscreen();
        }
        this.isfullScreen = true;
      } else {
        if (document.exitFullscreen) {
          document.exitFullscreen();
        } else if (document.mozCancelFullScreen) {
          // Firefox
          document.mozCancelFullScreen();
        } else if (document.webkitExitFullscreen) {
          // Chrome, Safari and Opera
          document.webkitExitFullscreen();
        } else if (document.msExitFullscreen) {
          // IE/Edge
          document.msExitFullscreen();
        }
        this.isfullScreen = false;
      }
    },
    onAnimationEnd() {
      if (this.isStop) return;
      this.isVisible = false;
      setTimeout(() => {
        this.isVisible = true;
        this.animationKey++;
      }, 60000);
    },
    getRandomTopPosition() {
      // 随机生成上下位置 (假设容器高度为 800px)
      return Math.random() * (window.innerHeight - 100); // 100 是水印的高度
    },

    goMenubar(index) {
      this.isCurrentMenubar = index;
    },

    sendMessage() {
      if (this.newMessage.trim() === "") return;
      const uuid = uuidv4();

      const nowTimeStamp = Math.floor(Date.now() / 1000);
      this.messages.push({
        id: uuid,
        sender: this.loginInfo.member_realname + "( 自分 )",
        text: this.newMessage,
        avatar:
          "data:image/svg+xml;base64," +
          btoa(`
          <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="40" height="40">
            <circle cx="12" cy="12" r="10" fill="#ccc"/>
            <circle cx="12" cy="10" r="4" fill="#fff"/>
            <path d="M12 14c-4 0-6 2-6 4v1h12v-1c0-2-2-4-6-4z" fill="#fff"/>
          </svg>
        `), // 默认头像
        time: nowTimeStamp,
      });
      this.myClient.sendMessage(
        uuid,
        this.newMessage + "--" + this.loginInfo.member_realname,
        []
      );
      // 存到数据库
      this.getData("/MemberVideo/saveMessage", {
        token: getStore("token"),
        liveId: this.liveId,
        passport: this.loginInfo.member_passport,
        commentText: this.newMessage,
      });

      this.newMessage = "";
      this.$nextTick(() => {
        this.scrollToBottom();
      });
    },
    formatTimestamp(timestamp) {
      // 将秒级时间戳转换为毫秒级时间戳
      const date = new Date(timestamp * 1000);

      // 获取月份、日期、小时、分钟和秒
      const month = String(date.getMonth() + 1).padStart(2, "0"); // 月份从0开始，需要加1
      const day = String(date.getDate()).padStart(2, "0");
      const hours = String(date.getHours()).padStart(2, "0");
      const minutes = String(date.getMinutes()).padStart(2, "0");
      const seconds = String(date.getSeconds()).padStart(2, "0");

      // 格式化为 MM-DD HH:MM:SS
      return `${month}-${day} ${hours}:${minutes}:${seconds}`;
    },
    scrollToBottom() {
      const scrollAnchor = this.$refs.scrollAnchor;
      if (scrollAnchor) {
        scrollAnchor.scrollIntoView({ behavior: "smooth" });
      }
    },
  },
  beforeDestroy() {
    this.removeVideoEventListeners(this.liveContent);
    this.myClient.leave();
    // const videos = document.querySelectorAll(
    //   "video.qnrtc-video-player.qnrtc-stream-player"
    // );
    // // 遍历这些元素并添加 controls 属性
    // for (let i = 0; i < videos.length; i++) {
    //   this.removeVideoEventListeners(videos[i]);
    // }
  },
  computed: {
    ...mapState(["loginInfo"]),
  },
};
</script>

<style lang="scss" scoped>
.live {
  display: flex;
  flex-direction: column;
  height: 100vh;
  position: relative;
}

.liveContent {
  width: 100%;
  position: relative;
  height: 35vh;
  background-color: gray;
  overflow: hidden;
  margin: auto;
  margin-top: 5rem;
}

.live-status {
  width: 100%;
  height: 100%;
  color: white;
  font-size: 18px;
  text-shadow: 2px 2px black;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

.teacherCamera {
  position: absolute;
  width: 150px;
  height: 120px;
  left: 1vh;
  bottom: 3vh;
}

.studentCamera {
  position: absolute;
  width: 150px;
  height: 120px;
  right: 2vh;
  bottom: 20vh;
}

.custom-controls {
  position: absolute;
  width: 100%;
  height: 50px;
  bottom: 0;
  left: 0;
  right: 0;
  // background: rgba(0, 0, 0, 0.5);
  // color: white;
  // display: flex;
  // justify-content: center;
  // align-items: center;
  // padding: 5px 0;
  opacity: 1;
  transition: opacity 0.7s;
  background: linear-gradient(to top, rgba(0, 0, 0, 0.5), rgba(0, 0, 0, 0));
}

.custom-controls .fullScreen:hover {
  // background: rgba(0, 0, 0, 0.5);
  // border-radius: 50%;
  transform: scale(1.2);
}

// .custom-controls {
//   opacity: 1;
// }
.teacherAudio {
  display: flex;
  flex-direction: row;
  align-items: center;
  color: white;
  padding: 0px 10px;
}

.teacherAudioControl {
  position: relative;
  padding: 10px 0px;
}

.teacherAudioRangeContainer {
  width: 80px;
  height: 20px;
  transform: rotate(-90deg);
  position: absolute;
  bottom: 50px;
  left: -31px;
  display: flex;
  background-color: #a6c6ffd1;
  border-radius: 1px;
  margin: 20px 0px;
}

.teacherAudioRange {
  transform: rotate(0deg) scale(0.5);
  position: relative;
  left: -25px;
}

.teacherAudioList,
.screenAudio,
.fullScreen {
  height: 20px;
  position: absolute;
  bottom: 10px;
  z-index: 1000;
  display: flex;
  flex-direction: row;
  align-items: center;
}

.screenAudio {
  right: 50px;
}

.fullScreen {
  right: 16px;
  // transform: rotate(90deg);
}

.watermark-container {
  position: absolute;
  bottom: 10px;
  /* 应用滑动动画 */
  animation: slide-left 20s linear forwards;
  /* 动画持续时间为5秒 */
  white-space: nowrap;
  /* 防止文本换行 */
  overflow: hidden;
  /* 隐藏溢出的文本 */
  text-overflow: ellipsis;
  /* 当文本溢出时用省略号表示 */
  display: inline-block;
  /* 或者 'inline'，根据需要 */
}

/* 动画定义 */
@keyframes slide-left {
  from {
    left: 100%;
    /* 从父容器右侧开始 */
  }

  to {
    left: -200px;
    /* 移动到父容器左侧外 */
  }
}

.menubar {
  width: 100%;
  height: 40px;
  background-color: white;
  display: flex;
  flex-direction: row;
  justify-content: space-around;
}

.menubar-one {
  width: 100%;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

.menubar-name {
  // width: 20%;
  font-size: 16px;
  font-weight: bold;
  cursor: pointer;
}

.current-select {
  width: 20%;
  height: 4px;
  background-color: blue;
  border-radius: 50px;
  margin-top: 3px;
  margin-bottom: -3px;
}

.bottom-content {
  flex-grow: 1;
  background-color: #f5f5f5;
}

.bottom-content::-webkit-scrollbar {
  display: none;
}

.info-content {
  height: 100%;
  display: flex;
  flex-direction: column;
  font-size: 18px;
  padding: 10px 20px;
  border: 1px solid #ddd;
}

.info-content-item {
  display: flex;
  flex-direction: column;
  padding: 5px;
  text-align: left;
}

.info-content-item-title {
  font-size: 18px;
}

.info-content-item-value {
  font-size: 16px;
  padding-top: 5px;
  padding-left: 3px;
  color: #5e5e5e;
}

.chat-content {
  height: 100%;
  overflow-y: auto;
  padding: 10px;
  background-color: #f9f9f9;
  border: 1px solid #ddd;
  display: flex;
  flex-direction: column;
}

.message {
  display: flex;
  align-items: flex-start;
  margin-bottom: 15px;
  animation: fadeIn 0.5s ease;
}

.avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  margin-right: 10px;
}

.message-body {
  // background-color: #fff;
  // padding: 10px;
  // border-radius: 5px;
  // box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  max-width: 80%;
}

.message-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 5px;
}

.teacher-tag {
  background-color: #007bff;
  /* 蓝色背景 */
  color: #fff;
  /* 白色文字 */
  padding: 2px 5px;
  border-radius: 3px;
  margin-right: 5px;
  font-size: 0.8em;
}

.message-sender {
  display: flex;
  align-items: center;
  font-weight: bold;
  color: #333;
}

.message-time {
  font-size: 0.8em;
  color: #999;
}

.message-text {
  text-align: left;
  background-color: #fff;
  padding: 10px;
  border-radius: 5px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  // max-width: 80%;
  color: #555;
  float: left;
  word-break: break-all;
}

.message-content {
  flex-grow: 1;
  overflow-y: auto;
  height: 100px;
}

.message-input {
  width: 100%;
  display: flex;
  align-items: center;
  padding: 10px;
  border-top: 1px solid #ddd;
  background-color: #f9f9f9;

  width: 97%;
  // position: absolute;
  bottom: 2px;
}

.message-input input {
  flex: 1;
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 5px;
  margin-right: 10px;
}

.message-input button {
  padding: 10px 20px;
  border: none;
  background-color: #007bff;
  color: #fff;
  border-radius: 5px;
  cursor: pointer;
}

.message-input button:hover {
  background-color: #0056b3;
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(10px);
  }

  to {
    opacity: 1;
    transform: translateY(0);
  }
}
</style>
