<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';
import { timestamp2string } from '~/utils/string';
import { resolveSingleFileString, getFullUrl } from '~/utils/helper';

const props = defineProps({
  id: String
})

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

let clientAllUsers = $ref({})
let clientRemoteUsers = ref([])
let clientRemoteUsersNum = $ref(0)

const localPlayerContainer = ref()
const showingPlayerContainer = ref()
const remotePlayerContainer = ref([])

function getClientRemoteUsers(arr) {
  return arr.filter((user) => user.uid !== loginUser.user_id && user.uid !== loginUser.user_id + 'b')
}

request({
  url: '/zhjy/tbjy/detail',
  data: {
    zt_id: props.id
  }
}).then(async (res) => {
  console.log('res :>> ', res);
  if (res.code === '1') {
    detailInfo = res.data.one_info
    console.log('detailInfo :>> ', detailInfo);
    {
      options = {
        appId: detailInfo.rtc_appid,
        channel: detailInfo.zt_id,
        token: detailInfo.rtc_token,
        uid: loginUser.user_id
      }
      let client = rtc.client = AgoraRTC.createClient({ mode: "rtc", codec: "vp8" });
      clientRemoteUsers.value = getClientRemoteUsers(rtc.client.remoteUsers)
      clientRemoteUsersNum = clientRemoteUsers.value.length
      await nextTick()
      console.log('remotePlayerContainer', remotePlayerContainer.value);

      rtc.client.remoteUsers.forEach(async (user, idx) => {
        await client.subscribe(user, 'video');
        await client.subscribe(user, 'audio');

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

        const videoTrack = user.videoTrack;
        videoTrack.play(remotePlayerContainer.value[idx]);

        clientAllUsers[idx] = ({ user, _show: false })
      });

      client.on("user-published", async (user, mediaType) => {
        console.log('user-published :>> ', user.uid !== loginUser.user_id && user.uid !== loginUser.user_id + 'b');
        console.log('user-published :>> user', user);
        console.log('user-published :>> mediaType', mediaType);

        // 不订阅自己发布的
        if (user.uid !== loginUser.user_id && user.uid !== loginUser.user_id + 'b') {
          clientRemoteUsers.value = getClientRemoteUsers(rtc.client.remoteUsers)
          clientRemoteUsersNum = clientRemoteUsers.value.length

          // 发起订阅
          await client.subscribe(user, mediaType);

          // 如果订阅的是音频轨道
          if (mediaType === "audio") {
            const audioTrack = user.audioTrack;
            // 自动播放音频
            audioTrack.play();
          } else {
            await nextTick()
            clientAllUsers[clientRemoteUsers.value.length - 1] = ({ user, _show: false })
            console.log('user-published :>> ', user);
            console.log(remotePlayerContainer.value.length);

            const videoTrack = user.videoTrack;
            // 自动播放视频
            videoTrack.play(remotePlayerContainer.value[clientRemoteUsers.value.length - 1]);
          }
        }
      });

      // 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);
      clientAllUsers[-1] = ({ user: 'self', _show: false })

    }

    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,
  token2: null,
};




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();
  // });
  if (screenTrack) {
    screenTrack?.close()

  }
  // Leave the channel.
  await rtc?.client?.leave();
  await screenClient?.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.value.forEach(remoteUser => {
    remoteUser.audioTrack.setVolume(val * 2);
  })
}


function handleShowing(id) {
  const currentMode = clientAllUsers[id]._show
  if (currentMode) {
    if (id === -1) {
      rtc.localVideoTrack.play(localPlayerContainer.value);
    } else {
      clientRemoteUsers.value[id].videoTrack.play(remotePlayerContainer.value[id])
    }
  } else {
    if (id === -1) {
      rtc.localVideoTrack.play(showingPlayerContainer.value);
    } else {
      clientRemoteUsers.value[id].videoTrack.play(showingPlayerContainer.value)
    }
  }
  clientAllUsers[id]._show = !clientAllUsers[id]._show
}


let screenClient
let screenTrack
let shareBtnLoading = $ref(false)
let shareBtnState = $ref(false)
async function handleShareScreen() {
  if (shareBtnState) {
    await screenTrack.close();
    shareBtnState = false
  }
  else {
    if (shareBtnLoading === false) {
      shareBtnLoading = true
      const res = await request({
        url: '/zhjy/tbjy/rtc_token',
        data: {
          channelname: props.id
        }
      })
      console.log('handleShareScreen res :>> ', res);
      if (res.code === '1') {
        detailInfo = res.data.one_info

        const _options = {
          appId: detailInfo.rtc_appid,
          channel: props.id,
          token: detailInfo.rtc_token,
          uid: loginUser.user_id + 'b'
        }
        AgoraRTC.createScreenVideoTrack({
          // 配置屏幕共享编码参数，详情请查看 API 文档。
          encoderConfig: "1080p_1",
          // 设置视频传输优化策略为清晰优先或流畅优先。
          optimizationMode: "detail",//"motion"

          withAudio: 'disable'
        }).then(async localScreenTrack => {
          screenTrack = localScreenTrack
          /** ... **/
          if (!screenClient) {
            screenClient = AgoraRTC.createClient({ mode: "rtc", codec: "vp8" });
            await screenClient.join(_options.appId, _options.channel, _options.token, _options.uid);
          }
          localScreenTrack.on("track-ended", async () => {
            console.log('track-ended :>> ');
            if (screenTrack) {
              screenTrack.close();
            }
            shareBtnState = false
          })
          localScreenTrack.play(showingPlayerContainer.value)
          await screenClient.publish(localScreenTrack)
          shareBtnState = true
        });
      }
    }
    shareBtnLoading = false
  }
}


const tabVal = ref('jygw')


const queryCommentForm = reactive({
  limit: 10,
  page: 1
})
let commentData = $ref([])
let commentTotal = $ref(0)
function queryCommentList() {
  request({
    url: '/zhjy/tbjy_kcdg_jygw/index',
    data: {
      zt_id: props.id,
      ...queryCommentForm
    }
  }).then(res => {
    if (res.code === '1') {
      commentData = res.data.page_data
      commentTotal = res.data.total_rows * 1
    }
  })
}
queryCommentList()

const form_ztkj_gwnr = $ref('')
function handleSubmitComment() {
  if (form_ztkj_gwnr.length >= 20 && form_ztkj_gwnr.length <= 500) {
    request({
      url: '/zhjy/tbjy_kcdg_jygw/add',
      data: {
        zhjy_tbjy_kcdg_jygw: {
          ztkj_user_realname: loginUser.user_realname,
          zt_id: props.id,
          ztkj_gwnr: form_ztkj_gwnr
        }
      }
    }).then(res => {
      if (res.code === '1') {
        ElMessage.success('提交成功')
        form_ztkj_gwnr = ''
        queryCommentList()
      }
    })
  } else {
    ElMessage.warning('教研感悟至少20个字且不超过500个字')
  }
}


const queryFileForm = reactive({
  limit: 10,
  page: 1
})
let fileData = $ref([])
let fileTotal = $ref(0)
function queryFileList() {
  request({
    url: '/zhjy/tbjy_file/index',
    data: {
      zt_id: props.id,
      ...queryFileForm
    }
  }).then(res => {
    if (res.code === '1') {
      fileData = res.data.page_data
      fileTotal = res.data.total_rows * 1
    }
  })
}
queryFileList()

const form_file = $ref(undefined)
function handleSubmitFile() {
  console.log('form_file :>> ', form_file);
  console.log(resolveSingleFileString(form_file));
  const file = resolveSingleFileString(form_file)
  {
    request({
      url: '/zhjy/tbjy_file/add',
      data: {
        zhjy_tbjy_file: {
          zt_id: props.id,

          user_name: loginUser.user_realname,
          ztf_name: file.name,
          ztf_file: file.origin
        }
      }
    }).then(res => {
      if (res.code === '1') {
        ElMessage.success('提交成功')
        form_file = undefined
        queryFileList()
      }
    })
  }
}

function handleFileDelete(row) {
  request({
    url: '/zhjy/tbjy_file/delete',
    data: {
      ztf_id: row.ztf_id
    }
  }).then(res => {
    if (res.code === '1') {
      ElMessage.success('删除成功')
      queryFileList()
    }
  })
}
</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">
      <breadcrumb-text title="智慧教研-同步教研-详情"></breadcrumb-text>
    </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?.zt_name }}</div>
    </div>
  </div> -->


  <div class="w-full flex items-center justify-center mt-4">
    <div ref="wrapperContainer" class="w-1400px h-min-930px flex flex-col relative bg-light-500" v-loading="loading">
      <div
        class="w-full h-210px flex overflow-x-auto bg-light-700 p-2 _scrollbar scrollbar-thin scrollbar-thumb-rounded scrollbar-thumb-gray-300 scrollbar-track-transparent">
        <div class="w-280px h-full flex-none p-1" ref="localPlayerContainer" @click="handleShowing(-1)">
          <div class="w-full h-full bg-black text-white text-sm flex_center" v-show="clientAllUsers[-1]?._show">
            点击切换至小屏模式
          </div>
        </div>
        <div class="w-280px h-full flex-none p-1 " v-for="(_, idx) in clientRemoteUsersNum"
          :ref="(el)=>remotePlayerContainer[idx]=el" @click="handleShowing(idx)">
          <div class="w-full h-full bg-black text-white text-sm flex_center" v-show="clientAllUsers[idx]?._show">
            点击切换至小屏模式</div>

        </div>
      </div>
      <div ref="showingPlayerContainer" class="w-full h-full "></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">
        <span class="text-xs mr-4 cursor-pointer px-2 py-1 bg-dark-900" :class="shareBtnLoading&&'cursor-wait'"
          @click="handleShareScreen">{{shareBtnState?'退出共享':'屏幕共享'}}</span>

        <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>

  <div class="w-full flex flex-col items-center  my-8">
    <div class="w-1400px flex flex-col items-center shadow-md min-h-400px p-4">
      <div class="w-full">
        <el-tabs v-model="tabVal">
          <el-tab-pane label="教研感悟" name="jygw"></el-tab-pane>
          <el-tab-pane label="资源" name="zy"></el-tab-pane>
        </el-tabs>
      </div>

      <div v-show="tabVal==='jygw'" class="w-full flex flex-col justify-start items-start">
        <el-input v-model="form_ztkj_gwnr" maxlength="500" placeholder="至少20个字不超过500个字" show-word-limit type="textarea"
          rows="5" />
        <div
          class="mt-2 flex_center h-32px text-sm w-110px leading-26px px-4 bg-gradient-to-l from-green-400 to-blue-500 text-white rounded-14px cursor-pointer btn"
          @click="handleSubmitComment">
          评价</div>

        <div class="w-full divide-y divide-dashed divide-2px">
          <template v-if="commentData.length">
            <div class="text-hex-171721 text-sm py-5" v-for="i in commentData">
              <div class="flex items-end mb-3">
                <div class="">{{i.ztkj_user_realname}}</div>
                <div class="text-hex-8083A3 text-xs ml-8">{{timestamp2string(i.create_dateline*1000)}}</div>
              </div>
              <div class="indent">{{i.ztkj_gwnr}}</div>
            </div>
          </template>

          <div v-else class="flex justify-center w-full">
            <el-empty description="暂无数据" />
          </div>

        </div>

        <div class="w-full flex justify-end mt-8 mb-8">
          <el-pagination background layout="prev, pager, next" :total="commentTotal"
            v-model:current-page="queryCommentForm.page" />
        </div>
      </div>
      <div v-show="tabVal==='zy'" class="w-full flex flex-col justify-start items-center">
        <file-upload v-model:full="form_file" @compile="handleSubmitFile">
          <div
            class="mt-2 flex_center h-32px text-sm w-110px leading-26px px-4 bg-gradient-to-l from-green-400 to-blue-500 text-white rounded-14px cursor-pointer btn">
            上传附件</div>
          <template #file>
            <span class="w-0 h-0"></span>
          </template>
        </file-upload>


        <div class="w-full divide-y divide-dashed divide-2px">
          <template v-if="fileData.length">
            <div class="text-hex-171721 text-sm py-5" v-for="i in fileData">
              <div class="flex items-end mb-3">
                <div class="">{{i.user_name}}</div>
                <div class="text-hex-8083A3 text-xs ml-8">{{timestamp2string(i.create_dateline*1000)}}</div>
              </div>
              <div class="flex justify-between">
                <div class="" :href="getFullUrl(i.ztf_file)">{{i.ztf_name}}</div>
                <div>
                  <a :href="getFullUrl(i.ztf_file)">
                    <el-button type="primary" plain>下载
                    </el-button>
                  </a>
                  <el-button type="primary" plain @click="handleFileDelete(i)"
                    :disabled="loginUser.user_id!==i.create_user_id" class="ml-2">删除</el-button>
                </div>
              </div>
            </div>
          </template>

          <div v-else class="flex justify-center w-full">
            <el-empty description="暂无数据" />
          </div>

        </div>

        <div class="w-full flex justify-end mt-8 mb-8">
          <el-pagination background layout="prev, pager, next" :total="fileTotal"
            v-model:current-page="queryFileForm.page" />
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
:deep(.el-tabs__nav-wrap::after) {
  background-color: transparent;
}
</style>
