<script setup>
import request from '~/utils/request';
// import CommonHeader from "@/components/CommonHeader/index.vue";;
import { ElMessage } from 'element-plus';
import AgoraRTC from "agora-rtc-sdk-ng"
import { user as loginUser } from '~/store/user';

const props = defineProps({
  id: String
})

let loading = $ref(true)
let detailInfo = $ref({})

let clientRemoteUsers = $ref([])
request({
  url: '/kzkt/ssyskc/detail',
  data: {
    ks_id: props.id
  }
}).then(async (res) => {
  if (res.code === '1') {
    detailInfo = res.data.one_info

    const options = {
      appId: detailInfo.rtc_appid,
      channel: detailInfo.ks_id,
      token: detailInfo.rtc_token,
      uid: loginUser.user_id
    }
    let client = rtc.client = AgoraRTC.createClient({ mode: "rtc", codec: "vp8" });
    clientRemoteUsers = rtc.client.remoteUsers
    rtc.client.remoteUsers.forEach(async user => {
      await client.subscribe(user, 'video');
      await client.subscribe(user, 'audio');

      const audioTrack = user.audioTrack;
      audioTrack.play();

      const videoTrack = user.videoTrack;
      videoTrack.play(remotePlayerContainer.value);

    });

    client.on("user-published", async (user, mediaType) => {
      clientRemoteUsers = rtc.client.remoteUsers
      // 发起订阅
      await client.subscribe(user, mediaType);

      // 如果订阅的是音频轨道
      if (mediaType === "audio") {
        const audioTrack = user.audioTrack;
        // 自动播放音频
        audioTrack.play();
      } else {
        const videoTrack = user.videoTrack;
        // 自动播放视频
        videoTrack.play(remotePlayerContainer.value);
      }
    });

    // rtc.client.setClientRole("host");
    await rtc.client.join(options.appId, options.channel, options.token, options.uid);
    // Create an audio track from the audio sampled by a microphone.
    rtc.localAudioTrack = await AgoraRTC.createMicrophoneAudioTrack();
    // Create a video track from the video captured by a camera.
    rtc.localVideoTrack = await AgoraRTC.createCameraVideoTrack();
    // Publish the local audio and video tracks to the channel.
    await rtc.client.publish([rtc.localAudioTrack, rtc.localVideoTrack]);

    rtc.localVideoTrack.play(localPlayerContainer.value);



    loading = false
  } else {
    ElMessage.error(res.msg)
  }
}).catch(err => {
  ElMessage.error(err)
})

let rtc = {
  // For the local audio and video tracks.
  localAudioTrack: null,
  localVideoTrack: null,
  client: null,
};

// let options = {
//   // Pass your app ID here.
//   appId: null,
//   // Set the channel name.
//   channel: null,
//   // Use a temp token
//   token: null,
// };

const localPlayerContainer = ref()
const remotePlayerContainer = ref()

onBeforeUnmount(async () => {
  // Close all the local tracks.
  rtc.localAudioTrack.close();
  rtc.localVideoTrack.close();
  // Traverse all remote users.
  // rtc.client.remoteUsers.forEach(user => {
  //   // Destroy the dynamically created DIV containers.
  //   const playerContainer = document.getElementById(user.uid);
  //   playerContainer && playerContainer.remove();
  // });

  // Leave the channel.
  await rtc.client.leave();
})

const wrapperContainer = $ref()

function requestFullscreen() {
  wrapperContainer.requestFullscreen()
}
function exitFullscreen() {
  document.exitFullscreen()
}

function toggleFullscreen() {
  if (document.fullscreenElement === null) {
    requestFullscreen()
  } else {
    exitFullscreen()
  }
}

const volume = $ref(50)
function handleChangeVolume(val) {
  clientRemoteUsers.forEach(remoteUser => {
    remoteUser.audioTrack.setVolume(val * 2);
  })
}

</script>

<template>
  <common-header />
  <div class="w-full flex items-center justify-center shadow h-60px bg-hex-fefefe">
    <div class="w-1400px flex items-center">
      <div class="text-lg text-hex-050026">内容</div>
      <el-divider direction="vertical" />
      <div class="text-sm">
        <span class="text-hex-949494">直播课堂</span>
        <span class="text-hex-949494"> - 双师一生</span>
        <span> - 内容</span>
      </div>
    </div>
  </div>

  <div class="w-full flex items-center justify-center shadow h-60px bg-hex-fefefe">
    <div class="w-1400px flex items-center">
      <div class="text-lg text-hex-050026">{{ detailInfo.ks_name }}</div>
    </div>
  </div>


  <div class="w-full flex items-center justify-center mt-4">
    <div ref="wrapperContainer" class="w-1400px h-730px flex flex-col relative">
      <div ref="remotePlayerContainer" class="w-full h-full bg-light-500"></div>
      <div ref="localPlayerContainer" class="w-1/4 h-1/4 bg-light-500 absolute top-0 left-0"></div>

      <div
        class="w-full h-36px absolute bottom-0 left-0 flex justify-end items-center text-xl text-white bg-black px-4 opacity-10 hover:opacity-60">
        <div class="w-140px flex items-center mr-4">
          <i-clarity:volume-up-solid />
          <el-slider v-model="volume" @change="handleChangeVolume" class="ml-2" />
        </div>

        <i-bx:fullscreen @click="toggleFullscreen" class="cursor-pointer" />
      </div>
    </div>
  </div>
</template>

