<template>
  <div class="video-communication">
    <div class="part-box-head">
      <div class="part-box-head-left"><h1>通话申请列表</h1></div>
      <div class="part-box-head-right">
        <el-radio-group size="small" v-model="pageType">
          <el-radio-button label="0">待处理</el-radio-button>
          <el-radio-button label="1">已处理</el-radio-button>
        </el-radio-group>
      </div>
    </div>
    <div class="student-list">
      <el-row :gutter="20">
        <el-col :md="6" :lg="6" :xl="4" v-for="item in students" :key="item.id">
          <div class="student-item">
            <div class="student-cover">
              <img :src="item.stdAvatar" :alt="item.stdName" />
            </div>
            <h4 class="student-name">{{ item.stdName }}</h4>
            <el-button round type="success" @click="answer(item, 0)"
              >语音通话</el-button
            >
            <br />
            <el-button round type="primary" @click="answer(item, 1)"
              >视频通话</el-button
            >
          </div>
        </el-col>
      </el-row>
    </div>

    <!-- 通话弹出层 -->
    <el-dialog
      custom-class="communication-dialog"
      :visible.sync="dialogVisible"
      width="600px"
      :show-close="false"
      :close-on-press-escape="false"
      :close-on-click-modal="false"
      append-to-body
      fullscreen
    >
      <div class="communication-box">
        <div class="communication-host" id="communication-host"></div>
        <div class="communication-guest" id="communication-guest"></div>
        <div class="communication-action">
          <el-button round type="danger" @click="hangup">结束通话</el-button>
        </div>
        <div class="communication-info">
          <span>当前网络状态良好</span>
          <span>持续时长：{{ durationTime }}</span>
        </div>
      </div>
      <span slot="footer" class="dialog-footer"> </span>
    </el-dialog>
  </div>
</template>

<script>
import TRTC from "trtc-js-sdk";
import { communicationList, communicationOver } from "@/api/invigilation";

export default {
  name: "video-communication",
  data() {
    return {
      pageType: "0",
      dialogVisible: false,
      students: [
        {
          id: 1,
          roomId: "8888",
          stdAvatar: "/img/avatars/1.jpg",
          stdName: "邹朵朵",
        },
        {
          id: 2,
          roomId: "2",
          stdAvatar: "/img/avatars/2.jpg",
          stdName: "罗图图",
        },
        {
          id: 3,
          roomId: "3",
          stdAvatar: "/img/avatars/3.jpg",
          stdName: "于梁",
        },
      ],
      setT: null,
      durationTime: "00:10:23",
      appId: "1400411036",
      videoUserSig:
        "eJyrVgrxCdYrSy1SslIy0jNQ0gHzM1NS80oy0zLBwsUGZlDh4pTsxIKCzBQlK0MTAwMTQ0MDYzOITGpFQWZRKlDc1NTUyMDAACJakpkLFrM0NzI0NLKEqi3OTAeaWmoeWZAd6O1h7B4YbhJoXOYdkeNmEebm5Z1R5JxXEmVhbOZkYWFQkZvjV26rVAsAYQkvlQ__",
      videoUserId: "s06",
      client: null,
      localStream: null,
    };
  },
  mounted() {
    this.initClinet();
    this.getCommunicationList();
  },
  methods: {
    async initClinet() {
      this.client = TRTC.createClient({
        mode: "rtc",
        sdkAppId: this.appId,
        userId: this.videoUserId,
        userSig: this.videoUserSig,
      });
    },
    async getCommunicationList() {
      const data = await communicationList().catch(() => {});
      this.students = data.records;

      // this.setT = setTimeout(() => {
      //   this.getCommunicationList();
      // }, 2000);
    },
    async answer(student, isVideo) {
      this.dialogVisible = true;
      // 结束学生的通话申请
      await communicationOver({ recordId: student.recordId });

      // 添加远程用户视频发布监听
      this.client.on("stream-added", (event) => {
        const remoteStream = event.stream;
        if (remoteStream.userId_ !== "s01") return;

        this.client
          .subscribe(remoteStream, { audio: true, video: true })
          .then(() => {
            console.log("订阅视频成功！");
          })
          .catch((error) => {
            console.log("订阅视频失败！", error);
          });
      });
      this.client.on("stream-subscribed", (event) => {
        const remoteStream = event.stream;
        remoteStream.play("communication-host", { objectFit: "contain" });
      });

      // 加入房间
      let roomJoinResult = true;
      await this.client
        .join({
          roomId: student.roomId,
          role: "audience",
          // role: "anchor"
        })
        .catch((error) => {
          roomJoinResult = false;
          console.log("加入房间失败！", error);
        });
      if (!roomJoinResult) return;

      // 切换角色，连麦互动
      let switchResult = true;
      await this.client.switchRole("anchor").catch((error) => {
        console.log("切换角色失败！", error);
        switchResult = false;
      });
      if (!switchResult) return;

      // 初始化stream
      this.localStream = TRTC.createStream({
        userId: this.videoUserId,
        audio: true,
        video: isVideo,
      });

      let initLocalStreamResult = true;
      await this.localStream.initialize().catch((error) => {
        console.log("初始化视频失败！", error);
        initLocalStreamResult = false;
      });
      if (!initLocalStreamResult) return;

      // 发布本地视频
      let publishStreamResult = true;
      this.client.publish(this.localStream).catch((error) => {
        console.log("发布本地视频失败！", error);
        publishStreamResult = false;
      });
      if (!publishStreamResult) return;

      // 播放本地视频
      this.localStream.play("communication-guest", { muted: true });
    },
    async hangup() {
      // 取消发布本地视频
      let unpublishStreamResult = true;
      this.client.unpublish(this.localStream).catch((error) => {
        console.log("取消发布本地视频失败！", error);
        unpublishStreamResult = false;
      });
      if (!unpublishStreamResult) return;

      this.localStream.close();
      this.localStream = null;

      let result = true;
      await this.client.leave().catch((error) => {
        console.log("离开房间失败！", error);
        result = false;
      });
      if (!result) return;

      this.client.off("*");
      this.dialogVisible = false;
    },
  },
  beforeDestroy() {
    if (this.setT) clearTimeout(this.setT);
    if (this.client) {
      this.client.leave();
      this.client.off("*");
    }
  },
};
</script>

<style lang="scss" scoped>
.student-list {
  .student-item {
    padding: 20px;
    background: #fff;
    border-radius: 10px;
    text-align: center;
    .el-button {
      margin-bottom: 12px;
    }
  }
  .student-cover {
    max-height: 200px;
    border-radius: 6px;
    overflow: hidden;
    img {
      display: block;
      width: 100%;
    }
  }
  .student-name {
    margin: 20px 0;
    font-size: 18px;
    line-height: 25px;
    color: #202b4b;
  }
}
</style>
