<template>
  <common-header />
  <nav class="nav">
    <div class="content" style="display: flex; align-items: center">
      <h3 class="font-size-16 lh60">详情</h3>
      <h3 class="line mh20"></h3>
      <h4 class="font-size-14 lh60">
        <span class="color-94">智慧教研</span> -
        <span class="color-94">协同备课</span> - 详情
      </h4>
    </div>
  </nav>
  <div class="content pb-80px">
    <div class="d-flex pt20">
      <div class="left">
        <div class="live-box">
          <div class="live-board pt30 pr">
            <h3 class="m-0 icon-live"></h3>
            <button
              type="button"
              class="live-btn d-block m-30"
              :disabled="
                !courseDetail.rtc_token || courseDetail.rtc_token === ''
              "
              @click="launchRtc"
            >
              发起音视频
            </button>
            <ul
              class="mt25 live-teacher-list ph15 clearfix"
              v-if="teacherList.length > 0"
            >
              <li v-for="item in teacherList">
                <h3 class="shot-img small d-in-block v-mid">
                  <img :src="item.avatar" alt="" />
                </h3>
                <h4 class="d-in-block v-mid ml5 font-size-13 lh24">
                  {{ item.user_name }}
                </h4>
              </li>
            </ul>
            <div id="board" class="board" v-if="showBoard">
              <div
                ref="wrapperContainer"
                class="flex flex-col relative"
                style="height: 326px"
              >
                <div
                  ref="remotePlayerContainer"
                  class="w-full h-full bg-5"
                ></div>
                <div
                  ref="localPlayerContainer"
                  class="w-1/4 h-1/4 bg-5 absolute top-0 left-0"
                ></div>
                <div class="full-screen" @click="toggleFullscreen"></div>
                <div class="leave-rtc" @click="leaveRtc">退出</div>
              </div>
            </div>
          </div>
        </div>
        <ul class="file-list">
          <li
            v-for="item in resource_list"
            :class="preview_res.ykz_id == item.ykz_id ? 'selected' : ''"
          >
            <div
              class="file-choose pr"
              :class="chooseCheck.includes(item.ykz_id) ? 'selected' : ''"
            >
              <div
                class="file-ico ppt"
                v-if="item.ykz_ext == 'ppt' || item.ykz_ext == 'pptx'"
              ></div>
              <div
                class="file-ico word"
                v-else-if="
                  item.ykz_ext == 'doc' ||
                  item.ykz_ext == 'docx' ||
                  item.ykz_ext == 'wps' ||
                  item.ykz_ext == 'wpt'
                "
              ></div>
              <div class="file-ico pdf" v-else-if="item.ykz_ext == 'pdf'"></div>
              <div
                class="file-ico excel"
                v-else-if="
                  item.ykz_ext == 'xls' ||
                  item.ykz_ext == 'xlsx' ||
                  item.ykz_ext == 'csv'
                "
              ></div>
              <div
                class="file-ico image"
                v-else-if="
                  item.ykz_ext == 'jpg' ||
                  item.ykz_ext == 'jpeg' ||
                  item.ykz_ext == 'png' ||
                  item.ykz_ext == 'gif'
                "
              ></div>
              <div
                class="file-ico video"
                v-else-if="item.ykz_ext == 'mp4'"
              ></div>
              <div
                class="file-ico audio"
                v-else-if="item.ykz_ext == 'mp3'"
              ></div>
              <div class="file-ico common" v-else></div>
              <p class="list-check hand">
                <input
                  type="checkbox"
                  :id="item.ykz_id"
                  :value="item.ykz_id"
                  name="lesson"
                  class="choose-check"
                  v-model="chooseCheck"
                />
                <label :for="item.ykz_id"></label>
              </p>
            </div>

            <div class="flex-1 w-250 pl10" @click="switchFile(item)">
              <h3 class="font-size-14 text-overflow">{{ item.ykz_title }}</h3>
              <div class="mt5 clearfix">
                <h3 class="fl font-size-12 lh24">{{ item.create_dateline }}</h3>
                <h4 class="fl ml10 font-size-12 lh24 text-overflow mw130">
                  上传者：{{ item.ykz_realname }}
                </h4>
              </div>
            </div>
            <span class="arrow"></span>
          </li>
        </ul>
        <div class="mt30 text-center pr">
          <div class="d-in-block pr">
            <button type="button" class="op-btn green">
              <span class="d-in-block v-mid icon-add mr5"></span>
              <span class="d-in-block v-mid">上传附件</span>
            </button>
            <input
              type="file"
              class="upload"
              id="uploadFile"
              accept="image/*,.doc,.docx,.wps,.wpt,.xls,.xlsx,.csv,.ppt,.pptx,.pdf,.mp3,.mp4,.enbx"
              @change="uploadFile(2)"
              v-loading.fullscreen.lock="fullscreenLoading"
            />
          </div>
          <button
            type="button"
            class="ml20 op-btn red"
            :disabled="chooseCheck.length === 0"
            @click="delFile"
          >
            删除附件
          </button>
        </div>
      </div>
      <div v-if="preview_type != ''" class="right">
        <iframe
          v-if="preview_type == 'document'"
          class="doc-box"
          :src="preview_link"
        ></iframe>
        <img :src="preview_link" v-if="preview_type == 'image'" alt="" />
        <video
          :src="preview_link"
          controls
          v-if="preview_type == 'video'"
        ></video>
        <audio
          :src="preview_link"
          controls
          v-if="preview_type == 'audio'"
        ></audio>
      </div>
      <div v-else class="right">
        <h4 class="font-size-16 color-1 text-center">
          暂无文件预览，请先上传附件！
        </h4>
      </div>
    </div>
    <div class="d-flex mt20">
      <div class="discuss-box">
        <h3 class="dis-title pl20">讨论区</h3>
        <ChatBlock :id="zx_id" />
      </div>
      <div class="comment-box p20 ml20">
        <h3 class="title pr">
          <i>评价</i>
          <span></span>
        </h3>
        <div class="mt15">
          <div>
            <el-rate v-model="rateValue" allow-half size="large" />
          </div>
          <button
            type="button"
            :disabled="rateValue == ''"
            class="rate-btn mt15"
            @click="rateSubmit"
          >
            评价
          </button>
        </div>
        <div v-if="rateList.length > 0">
          <ul class="mt20 rate-list" v-if="rateList.length > 0">
            <li v-for="item in rateList">
              <h3>
                <span class="font-size-15 text-black">{{
                  item.zxke_user_realname
                }}</span>
                <span class="font-size-13 ml10 color-803">{{
                  item.create_dateline
                }}</span>
              </h3>
              <div class="mt15">
                <el-rate v-model="item.zxke_star" disabled />
              </div>
            </li>
          </ul>
          <div class="mt15 text-center d-flex flex-right">
            <el-pagination
              small
              background
              layout="prev, pager, next"
              @current-change="handleCurrentChange"
              :current-page="r_page"
              :total="r_total"
              :page-size="2"
            />
          </div>
        </div>

        <div v-else class="pv20">
          <div class="no-data m-0"></div>
          <h4 class="mt10 font-size-16 color-1 text-center">暂无评论！</h4>
        </div>
      </div>
    </div>
  </div>
  <common-footer />
</template>

<script setup>
// import CommonHeader from "@/components/CommonHeader/index.vue";
import ChatBlock from "./chat.vue";
import { useRoute } from "vue-router";
import AgoraRTC from "agora-rtc-sdk-ng";
import { ElMessage } from "element-plus";
import {
  rate_list,
  rate_add,
  course_detail,
  file_list,
  file_add,
  file_del,
} from "@/pages/zhjy/zhjyxtbk/nrxq/api.js";
import { REQUEST } from "~/utils/request";
const route = useRoute();
let rateValue = $ref("");
// let loading = $ref(true)
let zx_id = route.params.id;
let r_page = $ref(1);
let limit = $ref(10);
let r_total = $ref(0);
let rateList = $ref([]);
let userInfo = user;
let courseDetail = $ref({});
let clientRemoteUsers = $ref([]);
let teacherList = $ref([]);
let chooseCheck = $ref([]);
let resource_list = $ref([]);
let fullscreenLoading = $ref(false);
let preview_type = $ref("");
let preview_link = $ref("");
let preview_res = $ref({});

let rtc = {
  // For the local audio and video tracks.
  localAudioTrack: null,
  localVideoTrack: null,
  client: null,
};
let showBoard = $ref(false);

function getCourseDetail() {
  let data = {
    zx_id: zx_id,
  };
  course_detail(data).then((res) => {
    if (res.code == 1) {
      courseDetail = res.data.one_info;
      // loading = false;
      if (
        res.data.one_info.zx_bkjs_json &&
        res.data.one_info.zx_bkjs_json.length > 0
      ) {
        res.data.one_info.zx_bkjs_json.forEach((item) => {
          if (item.avatar) {
            return (item.avatar = GLOBAL_CONFIG.oss + "/" + item.avatar);
          }
        });
        teacherList = res.data.one_info.zx_bkjs_json;
      }
    }
  });
}

function getRateList() {
  let data = {
    page: r_page,
    limit: "2",
    zx_id: zx_id,
  };
  rate_list(data).then((res) => {
    if (res.code == 1) {
      rateList = res.data.page_data;
      r_page = res.data.page_now;
      r_total = Number(res.data.total_rows);
    }
  });
}

function rateSubmit() {
  let data = {
    zxke_user_realname: userInfo.user_realname,
    zxke_star: rateValue,
    zx_id: zx_id,
  };
  rate_add(data).then((res) => {
    if (res.code == 1) {
      ElMessage({
        message: "评价成功！",
        type: "success",
        showClose: true,
        duration: "1000",
        onClose: () => {
          rateValue = "";
          getRateList();
        },
      });
    }
  });
}

function handleCurrentChange(val) {
  r_page = val;
  getRateList();
}

async function launchRtc() {
  showBoard = true;
  const options = {
    appId: courseDetail.rtc_appid,
    channel: "zhjyxbkc" + courseDetail.zx_id,
    token: courseDetail.rtc_token,
    uid: userInfo.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) => {
    // console.log('published')
    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);
}

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();
  }
}

async function leaveRtc() {
  rtc.localAudioTrack.close();
  rtc.localVideoTrack.close();

  // Leave the channel.
  rtc.client.leave();
  showBoard = false;
}

const volume = $ref(50);

function handleChangeVolume(val) {
  clientRemoteUsers.forEach((remoteUser) => {
    remoteUser.audioTrack.setVolume(val * 2);
  });
}

function getResourceList() {
  let data = {
    zx_id: zx_id,
  };
  file_list(data).then((res) => {
    if (res.code == 1) {
      resource_list = res.data.page_data;
      if (res.data.page_data.length > 0) {
        preview_res = res.data.page_data[0];
        getFilePreview();
      }
    }
  });
}

function uploadFile(type) {
  let file = "";
  if (type == "1") {
    file = document.getElementById("uploadDefault").files[0];
  } else {
    file = document.getElementById("uploadFile").files[0];
  }
  fullscreenLoading = true;
  if (file.size > 200 * 1024 * 1024) {
    ElMessage({
      message: "文件大小不能超过200M!",
      type: "warning",
      showClose: true,
      duration: "1500",
    });
    file = "";
    fullscreenLoading = false;
  }
  REQUEST["upload"]({
    url: "upload/main/file",
    data: {
      filedata: file,
    },
    timeout: 1000 * 180,
  }).then(({ code, data }) => {
    if (code == "1") {
      document.getElementById("uploadFile").value = "";
      const { url: url, file_name, ext } = data;
      let v_data = {
        issubmit: "1",
        zx_id: zx_id,
        ykz_ext: data.ext,
        ykz_title: data.file_name,
        yzk_bddz: data.url,
        ykz_realname: userInfo.user_realname,
      };
      file_add(v_data).then((res) => {
        if (res.code == 1) {
          fullscreenLoading = false;
          ElMessage({
            message: "附件添加成功！",
            type: "success",
            showClose: true,
            duration: "1000",
          });
          getResourceList();
        }
      });
    } else {
      return Promise.reject();
    }
  });
}

function delFile() {
  let data = {
    ykz_id: chooseCheck,
  };
  ElMessageBox.confirm("确认要删除这些附件？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      fullscreenLoading = true;
      file_del(data).then((res) => {
        fullscreenLoading = false;
        if (res.code === "1") {
          ElMessage({
            message: "附件删除成功！",
            type: "success",
            showClose: true,
            duration: "1000",
          });
          chooseCheck = [];
          getResourceList();
        } else {
          ElMessage({
            message: res.msg,
            type: "error",
            showClose: true,
            duration: "1000",
          });
        }
      });
    })
    .catch(() => {
      fullscreenLoading = false;
    });
}

function getFilePreview() {
  let document_type = "doc,docx,wps,wpt,xls,xlsx,csv,ppt,pptx,pdf";
  let image_type = "jpeg,jpg,png,gif";
  let video_type = "mp4";
  let audio_type = "mp3";
  if (document_type.includes(preview_res.ykz_ext)) {
    preview_type = "document";
    preview_link = preview_res.file_preview;
  } else if (image_type.includes(preview_res.ykz_ext)) {
    preview_type = "image";
    preview_link = GLOBAL_CONFIG.oss + "/" + preview_res.yzk_bddz;
  } else if (video_type.includes(preview_res.ykz_ext)) {
    preview_type = "video";
    preview_link = GLOBAL_CONFIG.oss + "/" + preview_res.yzk_bddz;
  } else if (audio_type.includes(preview_res.ykz_ext)) {
    preview_type = "audio";
    preview_link = GLOBAL_CONFIG.oss + "/" + preview_res.yzk_bddz;
  }
}

function switchFile(item) {
  preview_res = item;
  getFilePreview();
}

getRateList();
getCourseDetail();
getResourceList();
</script>
<style lang="scss" scoped>
@import "@/styles/mixin.scss";
</style>
<style lang="scss" scoped>
.nav {
  width: 100%;
  height: 60px;
  background: #ffffff;
  box-shadow: 0 1px 10px rgba(17, 46, 74, 0.1);

  .line {
    width: 1px;
    height: 20px;
    background: #f6f6fa;
  }
}

.content {
  width: 1400px;
  margin: 0 auto;
}

.left {
  width: 580px;
}

.live-box {
  width: 100%;
  background: #f9fbff;

  .live-board {
    width: 100%;
    height: 326px;
  }

  .icon-live {
    width: 150px;
    height: 126px;
    background: url("/images/live/live.png") center no-repeat;
    background-size: 150px 126px;
  }

  .live-btn {
    width: 100px;
    height: 32px;
    background: #ffffff;
    border-radius: 16px;
    box-shadow: 0 2px 6px #007dff;
    font-size: 14px;
    color: #007dff;
    text-align: center;
    &:disabled {
      color: #ccc;
      box-shadow: 0 2px 6px #ccc;
      cursor: default;
    }
  }
}

.board {
  position: absolute;
  right: 0;
  top: 0;
  width: 100%;
  height: 334px;
  z-index: 100;
}

.full-screen {
  position: absolute;
  right: 10px;
  top: 10px;
  width: 30px;
  height: 30px;
  z-index: 100;
  background: url("/images/live/icon-fullScreenEnter.png") center no-repeat;
  background-size: 30px 30px;
  cursor: pointer;
}

.leave-rtc {
  position: absolute;
  right: 10px;
  bottom: 10px;
  width: 40px;
  height: 40px;
  z-index: 100;
  border-radius: 50%;
  background: #1f3e85;
  font-size: 16px;
  color: #fff;
  line-height: 40px;
  text-align: center;
  cursor: pointer;
}

.file-list {
  width: 100%;

  li {
    margin-top: 15px;
    position: relative;
    width: 100%;
    height: 100px;
    border: 1px solid rgba(0, 0, 0, 0.05);
    border-radius: 12px;
    background: #fff;
    display: flex;
    align-items: center;
    padding: 0 15px 0 0;
    cursor: pointer;

    &.selected {
      box-shadow: 0 3px 8px 0 rgba(0, 0, 0, 0.1);

      .arrow {
        display: block;
      }
    }

    .arrow {
      display: none;
      position: absolute;
      right: -25px;
      top: 50%;
      margin-top: -11px;
      width: 18px;
      height: 21px;
      background: url("/images/live/icon-triangle.png") center no-repeat;
    }

    .file-choose {
      width: 80px;
      height: 100px;
      display: flex;
      align-items: center;
      justify-content: center;

      &:hover,
      &.selected {
        .list-check {
          display: block;
        }
      }
    }
  }

  .file-ico {
    min-width: 45px;
    width: 45px;
    height: 45px;

    &.word {
      background: url("/images/course/doc.png") center no-repeat;
      background-size: 45px 45px;
    }

    &.ppt {
      background: url("/images/course/ppt.png") center no-repeat;
      background-size: 45px 45px;
    }

    &.pdf {
      background: url("/images/course/pdf.png") center no-repeat;
      background-size: 45px 45px;
    }

    &.excel {
      background: url("/images/course/xls.png") center no-repeat;
      background-size: 45px 45px;
    }

    &.image {
      background: url("/images/course/jpg.png") center no-repeat;
      background-size: 45px 45px;
    }

    &.video {
      background: url("/images/course/mp4.png") center no-repeat;
      background-size: 45px 45px;
    }

    &.audio {
      background: url("/images/course/mp3.png") center no-repeat;
      background-size: 45px 45px;
    }

    &.common {
      background: url("/images/course/common.png") center no-repeat;
      background-size: 45px 45px;
    }
  }
}

.right {
  flex: 1;
  margin-left: 30px;
  min-height: 800px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #f9fbff;

  .doc-box {
    width: 100%;
    height: 100%;
  }

  img {
    display: block;
    max-width: 100%;
  }

  video {
    width: 100%;
    height: 100%;
    background: #000;
  }

  audio {
    width: 100%;
  }
}

.discuss-box {
  width: 580px;
  // height: 478px;
  background: #ffffff;
  border-radius: 12px;
  box-shadow: 2px 10px 24px rgba(161, 153, 168, 0.18);

  .dis-title {
    font-size: 16px;
    color: #171721;
    line-height: 48px;
    border-bottom: 1px solid #f0f0f0;
  }
}

.comment-box {
  flex: 1;
  width: 100%;
  background: #ffffff;
  border-radius: 12px;
  box-shadow: 2px 10px 24px rgba(161, 153, 168, 0.18);

  .title {
    width: 50px;
    font-size: 16px;
    color: #222;
    text-align: center;

    i {
      position: relative;
      z-index: 30;
    }

    span {
      position: absolute;
      left: 0;
      bottom: 0;
      width: 50px;
      height: 6px;
      opacity: 0.2;
      background: #6c5dd3;
      border-radius: 3px;
    }
  }
}

.rate-btn {
  width: 111px;
  height: 32px;
  background: linear-gradient(90deg, #00a3ff 1%, #57c38f);
  border-radius: 38px;
  font-size: 14px;
  color: #fff;

  &:disabled {
    background: #ccc;
  }
}

.rate-list {
  width: 100%;

  li {
    width: 100%;
    padding: 20px;
    border-bottom: 1px dashed rgba(110, 88, 197, 0.5);
  }
}

.list-check {
  position: absolute;
  left: 0;
  top: 0;
  z-index: 50;
  width: 100%;
  height: 100%;
  display: none;

  label {
    position: absolute;
    left: 0;
    top: 0;
    width: 100%;
    height: 100%;
    border-radius: 12px 0 0 12px;
    cursor: pointer;
  }

  input[type="checkbox"] {
    display: block;
    width: 80px;
    height: 100px;
    cursor: pointer;

    & + label {
      background: rgba(0, 0, 0, 0.25) url("/images/live/icon-check.png") center
        no-repeat;
      background-size: 32px 32px;
    }

    &:checked + label {
      background: rgba(0, 0, 0, 0.25) url("/images/live/icon-checked.png")
        center no-repeat;
      background-size: 32px 32px;
    }
  }
}

.upload {
  position: absolute;
  left: 50%;
  top: 0;
  margin-left: -50px;
  width: 100px;
  height: 32px;
  z-index: 30;
  opacity: 0;
  cursor: pointer;

  &.default {
    width: 95px;
    height: 40px;
    left: auto;
    right: 0;
    top: 50%;
    margin-left: 0;
    margin-top: -20px;
  }
}

.live-teacher-list {
  li {
    float: left;
    margin: 0 20px 15px 0;
  }
}

.shot-img {
  width: 44px;
  height: 44px;
  border-radius: 50%;
  overflow: hidden;

  &.offline {
    img {
      opacity: 0.5;
      -webkit-filter: grayscale(100%);
      -moz-filter: grayscale(100%);
      -o-filter: grayscale(100%);

      filter: grayscale(100%);
    }
  }

  &.small {
    width: 30px;
    height: 30px;
  }

  &.big {
    width: 48px;
    height: 48px;
  }

  img {
    width: 100%;
    height: 100%;
    border-radius: 50%;
  }
}
</style>
