<template>
  <div class="warning-detail">
    <div class="warning-detail-head">
      <div class="warning-detail-title">
        <h2>预警详情</h2>
        <el-button size="mini" icon="el-icon-arrow-left">返回列表</el-button>
        <el-button
          @click="initSubscribeVideo"
          type="primary"
          size="mini"
          icon="el-icon-arrow-left"
          >开始视频</el-button
        >
        <el-button
          @click="closeSubscribeVideo"
          type="danger"
          size="mini"
          icon="el-icon-arrow-left"
          >关闭视频</el-button
        >
      </div>
      <div class="warning-detail-student">
        <div class="student-head">
          <div class="student-head-left">
            <p><i class="icon icon-user-act"></i></p>
            <p><span>姓名：</span><span>张龙龙</span></p>
            <p><span>证件号：</span><span>000000000000000008</span></p>
            <p><span>科目(代码)：</span><span>大学语文(1001)</span></p>
          </div>
          <div class="student-head-right">
            <el-button
              size="mini"
              type="primary"
              icon="el-icon-arrow-left"
            ></el-button>
            <el-button
              size="mini"
              type="primary"
              icon="el-icon-arrow-right"
            ></el-button>
          </div>
        </div>
        <div class="student-views">
          <div class="student-avatar">
            <img :src="curStudent.stdAvatar" alt="" />
          </div>
          <div class="student-video">
            <div class="student-video-item">
              <flv-media
                ref="FirstViewVideo"
                :data="firstViewVideo"
                v-if="firstViewVideoReady"
              ></flv-media>
              <div class="student-video-none" v-else>
                <i class="el-icon-video-camera-solid"></i>
              </div>
            </div>
            <div class="student-video-item">
              <flv-media
                ref="ThirdViewVideo"
                :data="secondViewVideo"
                v-if="secondViewVideoReady"
              ></flv-media>
              <div class="student-video-none" v-else>
                <i class="el-icon-video-camera-solid"></i>
              </div>
            </div>
          </div>
        </div>
        <div class="student-exception">
          <ul>
            <li v-for="(item, index) in exceptionList" :key="index">
              <i>{{ index + 1 }}</i>
              <h4>{{ item.title }}</h4>
              <p>{{ item.desc }}</p>
            </li>
          </ul>
        </div>
      </div>
    </div>

    <div class="warning-detail-body">
      <div class="warning-body-head clear-float">
        <div class="warning-body-head-action">
          <h3>考试轨迹</h3>
          <el-button type="primary" icon="icon icon-view"></el-button>
          <el-button type="primary" icon="icon icon-text"></el-button>
          <el-button type="primary" icon="icon icon-audio"></el-button>
          <el-popover
            class="warning-body-head-call"
            placement="bottom-start"
            trigger="click"
          >
            <el-button type="success" @click="answer(0)">语音通话</el-button>
            <el-button type="primary" @click="answer(1)">视频通话</el-button>
            <el-button type="primary" slot="reference">实时通话</el-button>
          </el-popover>
        </div>
        <div class="warning-body-head-info summary-line">
          <p class="summary-line-item">
            <i class="line-point line-point-danger"></i
            ><span class="line-name">系统预警</span><span>1次</span>
          </p>
          <p class="summary-line-item">
            <i class="line-point line-point-danger"></i
            ><span class="line-name">陌生人脸</span><span>1次</span>
          </p>
          <p class="summary-line-item">
            <i class="line-point line-point-danger"></i
            ><span class="line-name">异常处理</span><span>1次</span>
          </p>
          <p class="summary-line-item">
            <span></span><span>违纪状态：正常</span>
          </p>
          <el-button type="danger" icon="icon icon-stop">违纪处理</el-button>
          <el-button type="warning" icon="icon icon-forbide"
            >强制收卷</el-button
          >
        </div>
      </div>
      <div class="warning-body-main"></div>
    </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" v-show="!isWaiting">
        <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>
      <div class="communication-wait" v-show="isWaiting">
        <p class="communication-wait-tips">等待接听…</p>
        <div class="communication-wait-avatar">
          <img :src="curStudent.stdAvatar" :alt="curStudent.stdName" />
        </div>
        <p class="communication-wait-username">{{ curStudent.stdName }}</p>
        <div class="communication-wait-action">
          <el-button round type="danger" @click="hangup">取消通话</el-button>
        </div>
      </div>
      <span slot="footer" class="dialog-footer"> </span>
    </el-dialog>
  </div>
</template>

<script>
import TRTC from "trtc-js-sdk";
import FlvMedia from "./FlvMedia";
import { warningStudentDetail } from "@/api/invigilation";

export default {
  name: "warning-detail",
  components: { FlvMedia },
  data() {
    return {
      recordId: "777",
      exceptionList: [
        {
          title: "身份验证不通过",
          desc: "系统发现该考生身份识别多次不通过，请监考老师关注！",
        },
        {
          title: "疑似：有违规动作",
          desc:
            "系统发现该考生至少有多次以上持续1分钟以上的违规动作，且违规动作的持续时间已超出合理范围，请监考老师关注！",
        },
        {
          title: "疑似：启用虚拟摄像头",
          desc: "系统检测到考生可能使用了虚拟摄像头，请监考老师关注！",
        },
      ],
      curStudent: {
        stdAvatar: "/img/avatars/2.jpg",
        stdCardNo: "000000000000000008",
        stdName: "张龙龙",
        subjectName: "大学英语",
        subjectCode: "10006",
        roomId: "8888",
      },
      firstViewVideo: {
        id: "111",
        src: "http://live.qmth.com.cn/live/8888_mobile_first.flv",
        name: "第一视角",
      },
      secondViewVideo: {
        id: "222",
        src: "http://live.qmth.com.cn/live/8888_mobile_second.flv",
        name: "第二视角",
      },
      firstViewVideoReady: false,
      secondViewVideoReady: false,
      // communication
      durationTime: "00:10:23",
      appId: "1400411036",
      videoUserSig:
        "eJyrVgrxCdYrSy1SslIy0jNQ0gHzM1NS80oy0zLBwsUGZlDh4pTsxIKCzBQlK0MTAwMTQ0MDYzOITGpFQWZRKlDc1NTUyMDAACJakpkLFrM0NzI0NLKEqi3OTAeaWmoeWZAd6O1h7B4YbhJoXOYdkeNmEebm5Z1R5JxXEmVhbOZkYWFQkZvjV26rVAsAYQkvlQ__",
      videoUserId: "s06",
      client: null,
      localStream: null,
      dialogVisible: false,
      isWaiting: true,
      setT: null,
    };
  },
  mounted() {
    // this.initClinet();
    // this.initData();
  },
  methods: {
    initClinet() {
      this.client = TRTC.createClient({
        mode: "rtc",
        sdkAppId: this.appId,
        userId: this.videoUserId,
        userSig: this.videoUserSig,
      });
    },
    async initData() {
      const data = await warningStudentDetail({ recordId: this.recordId });
      const records = data.records.map((item) => {
        item.src = `http://live.qmth.com.cn/live/${item.liveUrl}.flv`;
        item.name = item.source;
        return item;
      });
      this.firstViewVideo = records[0] || {};
      this.secondViewVideo = records[1] || {};

      if (records.length) this.initSubscribeVideo();
    },
    initSubscribeVideo() {
      if (this.firstViewVideo.id) this.firstViewVideoReady = true;
      if (this.secondViewVideo.id) this.secondViewVideoReady = true;
    },
    closeSubscribeVideo() {
      this.firstViewVideoReady = false;
      this.secondViewVideoReady = false;
    },
    async answer(isVideo) {
      this.closeSubscribeVideo();
      this.dialogVisible = true;

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

        // 延迟订阅视频
        this.setT = setTimeout(() => {
          this.client
            .subscribe(remoteStream, { audio: true, video: true })
            .then(() => {
              console.log("订阅视频成功！");
            })
            .catch((error) => {
              console.log("订阅视频失败！", error);
            });
        }, 5000);
      });
      this.client.on("stream-subscribed", (event) => {
        const remoteStream = event.stream;
        if (remoteStream.userId_ !== "s01") return;

        this.isWaiting = false;
        this.$nextTick(() => {
          remoteStream.play("communication-host", { objectFit: "contain" });
        });
      });

      // 加入房间
      let roomJoinResult = true;
      await this.client
        .join({
          roomId: this.curStudent.roomId,
          role: "audience",
        })
        .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() {
      if (this.setT) clearTimeout(this.setT);

      // 取消发布本地视频
      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;
      this.localStream = null;
      this.isWaiting = true;
      // this.initSubscribeVideo();
    },
  },
  beforeDestroy() {
    if (this.setT) clearTimeout(this.setT);
    if (this.client) {
      this.client.leave();
      this.client.off("*");
    }
  },
};
</script>

<style lang="scss" scoped>
.warning-detail {
  &-head {
    margin: -30px -30px 0;
    padding: 30px;
    background: #fff;
    border: 1px solid #f0f4f9;
  }
  &-title {
    overflow: hidden;
    padding-bottom: 20px;
    border-bottom: 1px solid #f0f4f9;
    > h2 {
      float: left;
      font-weight: 600;
      font-size: 18px;
      line-height: 28px;
      margin: 0;
    }
    > .el-button {
      float: right;
    }
  }
}
.student-head {
  padding: 20px 0;
  overflow: hidden;
  &-left {
    float: left;
    > p {
      display: inline-block;
      vertical-align: middle;
      margin: 0;
      line-height: 28px;
      height: 28px;
      margin-right: 15px;

      &:first-child {
        margin-right: 10px;
      }

      > span {
        color: #626a82;

        &:last-child {
          color: #202b4b;
          margin-left: 5px;
          font-weight: 600;
        }
      }
    }
  }
  &-right {
    float: right;
  }
}
.student-views {
  height: 240px;
  margin: 0 -15px;
}
.student-avatar {
  padding: 0 15px;
  width: 210px;
  height: 100%;
  float: left;
  > img {
    display: block;
    width: 100%;
    height: 100%;
    border-radius: 6px;
  }
}
.student-video {
  margin-left: 210px;
  height: 240px;
  font-size: 0;
  position: relative;

  &-item {
    position: relative;
    display: inline-block;
    vertical-align: top;
    font-size: 14px;
    padding: 0 15px;
    width: 50%;
    height: 100%;
  }
  video {
    display: block;
    width: 100%;
    height: 100%;
    border-radius: 6px;
    box-shadow: 0 0 1px #333;
    background: #606060;
  }

  &-main {
    position: absolute;
    top: 0;
    left: 15px;
    right: 15px;
    bottom: 0;
    z-index: 9;
    border-radius: 6px;
  }

  &-none {
    height: 100%;
    background: #606060;
    border-radius: 6px;
    font-size: 50px;
    text-align: center;
    padding-top: 90px;
    color: #202b4b;
  }
}
.student-exception {
  padding-top: 30px;
  overflow: auto;
  ul,
  li {
    margin: 0;
    padding: 0;
  }
  ul {
    white-space: nowrap;
    font-size: 0;
  }
  li {
    display: inline-block;
    vertical-align: top;
    font-size: 14px;
    position: relative;
    padding-left: 38px;
    width: 400px;

    > i {
      display: block;
      position: absolute;
      font-size: 29px;
      line-height: 1;
      color: #d9dfe8;
      top: 3px;
      left: 5px;
      z-index: 9;
      font-style: normal;

      &::after {
        content: "";
        display: block;
        position: absolute;
        background: #fff;
        width: 15px;
        height: 15px;
        transform: rotate(45deg);
        bottom: -2px;
        right: -10px;
        z-index: 9;
      }
    }

    &:not(:last-child):after {
      content: "";
      display: block;
      position: absolute;
      background-image: url(../../../assets/bg-split-line.png);
      background-position: 100% 100%;
      width: 30px;
      height: 52px;
      top: 6px;
      right: 10px;
      z-index: 9;
    }
    h4 {
      font-size: 16px;
      font-weight: 600;
      color: #202b4b;
      line-height: 22px;
      margin-bottom: 4px;
    }
    p {
      margin: 0;
      width: 304px;
      font-weight: 400;
      color: #626a82;
      line-height: 20px;
      white-space: normal;
    }
  }
}
.warning-detail-body {
  margin-top: 30px;
}
.warning-body-head {
  background: #fff;
  border-bottom: 1px solid #f0f4f9;
  padding: 20px;
  &-action {
    float: left;
    > h3 {
      line-height: 32px;
      display: inline-block;
      vertical-align: middle;
      font-size: 18px;
      font-weight: 600;
      margin: 0 30px 0 0;
    }

    i.icon {
      margin: 0;
    }
  }
  &-call {
    margin: 0 10px;
  }
  &-info {
    float: right;
    > p {
      height: 32px;
      line-height: 32px;
      margin-right: 20px;
    }
  }
}
.warning-body-main {
  min-height: 400px;
  background: #fff;
}
</style>
