<template>
  <div class="livebox">
    <div class="top">
      <div class="top-left">
        <h1 class="title">
          {{ title }}
        </h1>
        <div class="time-message">
          <p>设定时长: {{ time }}分钟</p>
          <p v-if="startTime && endTime">
            总时长: {{ useTime }}
          </p>
          <p v-if="startTime && endTime">
            剩余时长: {{ loseTime }}
          </p>
        </div>
      </div>
      <div class="top-right">
        <img
          :src="isMicOn ? voiceSmallImg : voiceCloseImg"
          alt=""
          srcset=""
          class="icon"
          @click="taggleM"
        >
        <div
          class="close"
          @click="overFn"
        >
          结束会话
        </div>
      </div>
    </div>
    <div class="main">
      <div
        v-for="(item, index) of memberList"
        :key="index"
        class="viedo-wrapper"
      >
        <div class="text">
          <p>{{ item.name }}</p>
          <p>{{ item.role == 1 ? "问诊医生" : "接诊医生" }}:</p>
        </div>
        <div class="viedo">
          <div
            v-if="rtc && rtc.viewslist[index]"
            :id="rtc.viewslist[index].id"
          />
          <!-- 用户声音icon -->
          <img
            v-if="item.status == 2"
            :src="
              rtc && rtc.viewslist[index] && rtc.viewslist[index].vioce
                ? voiceSmallImg
                : voiceCloseImg
            "
            alt=""
            srcset=""
            class="user-icon"
          >

          <img
            v-else
            :src="setImg(item.status)"
            alt=""
            srcset=""
            class="video-icon"
          >
          <div
            v-if="rtc && rtc.viewslist[index] && rtc.viewslist[index].mask"
            class="mask"
          >
            <img
              :src="type == 1 ? voiceImg : noCameraImg"
              alt=""
              :class="{ vocie: type == 1 }"
            >
          </div>
        </div>
        <div class="time">
          <!-- //等待连接还是已经下麦 1为等待 2为进行中 3为下麦 -->
          <div class="time-content">
            <el-button
              class="call-btn"
              size="mini"
              :disabled="item.status == 2 && item.timeleft == 0"
              type="primary"
              :loading="item.timeleft > 0"
              @click="drivingCall(item)"
            >
              <span
                v-if="item.timeleft == 0"
              >呼叫{{ item.role == 1 ? "问诊医生" : "接诊医生" }}</span>
              <time-left
                v-else
                :timeleft="item.timeleft"
                @setItem="setItem($event, item)"
              />
            </el-button>
            <span>
              {{ showText(item.status, item.role, item) }}
            </span>
          </div>
        </div>
      </div>
    </div>

    <div
      class="out"
      @click="leave"
    >
      退出
    </div>
    <alert ref="alert" />
  </div>
</template>
<script>
  import {
    getLiveTimeText,
    countDown,
    getBroswer,
    laseTime,
    lastm,
  } from '@/utils/live';
  import RtcClient from '../../../utils/live/RtcClient.js';
  import { openLoading, closeLoading } from '@/utils/utils';
  import alert from '@/components/common/alert.vue';
  import timeLeft from '@/components/timeLeft';

  import {
    teamDetail,
    getSdkappid,
    streamParams,
    callDirect,
    usersigTrtc,
    diagnoseEndCall,
  } from '@/api/diagnosis';
  export default {
    components: {
      alert,
      timeLeft,
    },
    data() {
      return {
        closeCallImg: require('../../../assets/image/live/close-call.png'),
        voiceCloseImg: require('../../../assets/image/live/voice-close.png'),
        voiceSmallImg: require('../../../assets/image/live/voice-small.png'),
        voiceImg: require('../../../assets/image/live/voice.png'),
        waitingCallImg: require('../../../assets/image/live/waiting-call.png'),
        noCameraImg: require('../../../assets/image/live/no-camera.png'),
        roleAnchor: 'anchor', // 主播
        rtc: null,
        roomId: '',
        sdkAppId: '',
        userSig: '',
        userId: '',
        viedoParams: null,
        isMicOn: false,
        askTime: 0, // 问诊医生接入时长
        answerTime: 0, // 接诊医生接入时长
        useTime: 0, // 问诊时长
        loseTime: 0, // 问诊剩余时长
        askTimeFn: null,
        answerTimeFn: null,
        useTimeFn: null,
        loseTimeFn: null,
        type: 2, // 1: 语音 2: 视频
        startTime: 0,
        endTime: 0,
        time: 30, // 总时长
        memberList: [],
        tid: '', // 群id
        diagnoseLogId: '', // 问诊id
      };
    },
    computed: {
      title() {
        return this.type == 1 ? '音频问诊' : '视频问诊';
      },
    },
    created() {
      this.tid = this.$route.query.tid || '';
      this.diagnoseLogId = this.$route.query.diagnoseLogId || '';
      openLoading(this);
      this.init();
    },
    beforeDestroy() {
      this.clearTime();
    },
    methods: {
      init() {
        if (this.checkChrome()) {
          this.getViedoParams();
          this.getInfo();
        } else {
          this.$nextTick(() => {
            this.$refs.alert
              .init({
                confirmTxt: '我知道了',
                title: '请下载新版Chrome浏览器',
              })
              .then(() => {
                closeLoading(this);
                this.$router.go(-1);
              })
              .catch((err) => {
                closeLoading(this);
                this.$router.go(-1);
              });
          });
        }
      },
      // 设置item
      setItem(data, item) {
        item.timeleft = 0;
      },

      // 主动呼叫
      drivingCall(data) {
        const params = {
          imAccId: data.accId,
          imTeamId: this.tid,
          liveRoomId: this.roomId,
        };
        callDirect(params).then((res) => {
          if (res.code === '000000') {
            this.getInfo(data);
          } else {
            this.$message({
              message: res.message,
              type: 'warning',
            });
          }
        });
      },
      // 获取相关信息
      getInfo(data) {
        const role = data ? data.role : '';
        teamDetail({
          tid: this.tid,
        })
          .then((res) => {
            if (res.code == '000000') {
              const { liveInfo, memberList } = res.data;
              if (liveInfo) {
                this.startTime = liveInfo.startTimestamp;
                this.endTime = liveInfo.endTimestamp;
                this.time = lastm(this.startTime, this.endTime);
                this.roomId = Number(liveInfo.roomId);
                this.type = liveInfo.liveType;
              }
              if (memberList && memberList.length) {
                memberList.forEach((item) => {
                  if (role) {
                    if (item.role == 1) {
                      if (role == 1) {
                        this.memberList[0] = Object.assign(item, {
                          status: 1,
                          timeleft: 60,
                        });
                      }
                    // 等待连接还是已经下麦 1为等待 2为进行中 3为下麦
                    }
                    if (item.role == 2) {
                      if (role == 2) {
                        this.memberList[1] = Object.assign(item, {
                          status: 1,
                          timeleft: 60,
                        });
                      }
                    }
                  } else {
                    if (item.role == 1) {
                      this.memberList[0] = Object.assign(item, {
                        status: 1,
                        timeleft: 0,
                      });
                    // 等待连接还是已经下麦 1为等待 2为进行中 3为下麦
                    }
                    if (item.role == 2) {
                      this.memberList[1] = Object.assign(item, {
                        status: 1,
                        timeleft: 0,
                      });
                    }
                  }

                  // 在当前群组中的角色 1: 问诊医生 2: 接诊医生 3: 居民 4: 其他

                  if (item.role == 4) {
                    this.userId = item.liveUserId;
                  }
                });
              }
              this.getAppId();
            } else {
              this.getErr();
            }
          })
          .catch(() => {
            this.getErr();
          });
      },
      // 获取AppId
      getAppId() {
        const req = {};
        getSdkappid()
          .then((res) => {
            if (res.code == '000000') {
              this.sdkAppId = res.data.sdkAppId;
              this.getSing();
            } else if (res.code == '200006' || res.code == '200000') {
              if (this.rtc) {
                this.leave();
              }
              this.getErr();
            }
          })
          .catch((err) => {
            this.getErr();
          });
      },
      // 获取签名
      getSing() {
        const req = {
          sdkAppId: this.sdkAppId,
          userId: this.userId,
        };
        usersigTrtc(req)
          .then((res) => {
            if (res.code == '000000') {
              this.userSig = res.data.userSig;
              this.clientLogin();
            } else if (res.code == '200006' || res.code == '200000') {
              if (this.rtc) {
                this.leave();
              }
              this.getErr();
            }
          })
          .catch((err) => {
            this.getErr();
          });
      },
      // 创建trtcClient
      clientLogin() {
        const obj = {
          roomId: this.roomId,
          role: this.roleAnchor,
          sdkAppId: this.sdkAppId,
          userId: this.userId,
          userSig: this.userSig,
          vueInstance: this,
        };
        this.rtc = new RtcClient(obj);
        this.$nextTick(() => {
          this.$refs.alert
            .init({
              confirmTxt: '我知道了',
              title: '为了更好的体验,请保证您输出设备的正常使用',
            })
            .then(() => {
              Promise.all([this.rtc.join()]).then((res) => {
                this.ispending();
                const t = setTimeout(() => {
                  closeLoading(this);
                  this.muteLocalAudio();
                  clearTimeout(t);
                }, 1000);
              });
            })
            .catch((err) => {
              Promise.all([this.rtc.join()]).then((res) => {
                this.ispending();
                const t = setTimeout(() => {
                  closeLoading(this);
                  this.muteLocalAudio();
                  clearTimeout(t);
                }, 1000);
              });
            });
        });
      },
      // 获取视频参数
      getViedoParams() {
        streamParams()
          .then((res) => {
            if (res.code == '000000') {
              this.viedoParams = res.data;
            } else if (res.code == '200006' || res.code == '200000') {
              closeLoading(this);
              if (this.rtc) {
                this.leave();
              }
            }
          })
          .catch((err) => {
            console.log('获取视频参数数据失败');
          });
      },
      // 切换话筒
      taggleM() {
        if (this.isMicOn) {
          this.muteLocalAudio();
        } else {
          this.unmuteLocalAudio();
        }
      },
      // 关闭mc
      muteLocalAudio() {
        this.isMicOn = false;
        this.rtc.muteLocalAudio();
      },
      // 打开mc
      unmuteLocalAudio() {
        this.isMicOn = true;
        this.rtc.unmuteLocalAudio();
      },
      // 显示文案
      showText(status, role, item) {
        // 1 呼叫中 2 接入 3离线
        if (item.status == 2) {
          item.timeleft = 0;
        }
        let text = '';
        switch (status) {
        case 1:
          text = '呼叫中';
          break;
        case 3:
          text = '已离线';
          break;
        default:
          text = `已接入: ${role == 1 ? this.askTime : this.answerTime}`;
          break;
        }
        return text;
      },
      // 设置图像 1为等待 2为进行中 3为下麦
      setImg(status) {
        let img = null;
        switch (status) {
        case 1:
          img = this.waitingCallImg;
          break;
        case 3:
          img = this.closeCallImg;
          break;
        default:
          img = this.closeCallImg;
          break;
        }
        return img;
      },
      // 用户上线
      addNewMember(id) {
        this.memberList.forEach((item) => {
          if (item.liveUserId == id) {
            item.status = 2;
            this.setTime(item.role);
          }
        });
      },
      // 用户下线
      removeMember(id) {
        this.memberList.forEach((item) => {
          if (item.liveUserId == id) {
            item.status = 3;
          }
        });
      },
      // 设置进行时长 1表示为问诊 2为接诊 3为问诊开始  4为问诊结束
      setTime(flag) {
        let text = '';
        switch (flag) {
        case 1:
          text = 'askTime';
          break;
        case 2:
          text = 'answerTime';
          break;
        case 3:
          text = 'useTime';
          break;
        case 4:
          text = 'loseTime';
          break;
        default:
          break;
        }
        const t = 0;
        let liveTime = Number(sessionStorage.getItem(`TIME_${text}`) || t);

        this[`${text}Fn`] = setInterval(() => {
          liveTime += 1000;
          this[text] = getLiveTimeText(liveTime, text);
        }, 1000);
      },
      // 问诊是否进行中
      ispending() {
        if (this.startTime < new Date() < this.endTime) {
          this.setTime(3);
          this.loseTimeFn = setInterval(() => {
            this.loseTime = countDown(this.endTime);
            const timeObj = laseTime(this.endTime);
            if (
              (timeObj.leftm == 5 || timeObj.leftm == 3 || timeObj.leftm == 1) &&
              timeObj.lefts == 0 &&
              timeObj.lefth == 0
            ) {
              this.$nextTick(() => {
                this.$refs.alert
                  .init({
                    confirmTxt: '我知道了',
                    title: `距离会诊结束还剩不足${timeObj.leftm}分钟`,
                  })
                  .then(() => {})
                  .catch((err) => {});
              });
            }
          }, 1000);
        } else if (new Date() < this.startTime) {
          const t = setInterval(() => {
            if (new Date() > this.startTime) {
              clearInterval(t);
              this.ispending();
            }
          }, 1000);
        }
      },
      // 检查是否为chrome
      checkChrome() {
        return getBroswer().broswer == 'Chrome';
      },
      // client离开房间
      leave() {
        this.rtc.leave();
        this.clearSession();
        window.location.href = 'about:blank';
        window.close();
      },
      // 结束会话
      overFn() {
        this.$refs.alert
          .init({
            cancleTxt: '取消',
            confirmTxt: '我知道了',
            title: '确定要结束会话么？',
          })
          .then(() => {
            this.out();
          })
          .catch((err) => {});
      },
      out() {
        diagnoseEndCall({
          diagnoseLogId: this.diagnoseLogId,
        })
          .then((res) => {
            if (res.code == '000000') {
              this.leave();
            } else {
              this.$refs.alert
                .init({
                  confirmTxt: '我知道了',
                  title: '操作失败,请稍后重试',
                })
                .then(() => {})
                .catch((err) => {});
            }
          })
          .catch(() => {
            this.$refs.alert
              .init({
                confirmTxt: '我知道了',
                title: '操作失败,请稍后重试',
              })
              .then(() => {})
              .catch((err) => {});
          });
      },
      // 获取信息失败
      getErr() {
        closeLoading(this);
      },
      reloadfn(msg) {
        this.$nextTick(() => {
          this.$refs.alert
            .init({
              confirmTxt: '我知道了',
              title: '加入房间失败，重新加入',
            })
            .then(() => {
              location.reload();
            })
            .catch((err) => {
              location.reload();
            });
        });
      },
      clearTime() {
        clearInterval(this.askTimeFn);
        clearInterval(this.answerTimeFn);
        clearInterval(this.useTimeFn);
        clearInterval(this.loseTimeFn);
      },
      // 清除直播时间相关的seession
      clearSession() {
        sessionStorage.removeItem('TIME_askTime');
        sessionStorage.removeItem('TIME_answerTime');
        sessionStorage.removeItem('TIME_useTime');
        sessionStorage.removeItem('TIME_loseTime');
      },
    },
  };
</script>
<style lang="scss" scoped>
.livebox {
  display: flex;
  flex-direction: column;
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: #000000;
  .top {
    display: flex;
    margin-top: 5%;
    justify-content: space-between;
    .top-left {
      margin-left: 24px;
      .title {
        width: 72px;
        height: 22px;
        font-size: 18px;
        font-family: PingFangSC-Semibold, PingFang SC;
        font-weight: 700;
        color: #ffffff;
        line-height: 22px;
      }
      .time-message {
        margin-top: 20px;
        display: flex;
        height: 20px;
        font-size: 14px;
        font-family: PingFangSC-Regular, PingFang SC;
        font-weight: 400;
        color: #ffffff;
        line-height: 20px;
        p {
          margin-right: 20px;
        }
      }
    }
    .top-right {
      margin: 15px 25px 0 0;
      display: flex;
      align-items: center;
      justify-content: center;
      .icon {
        width: 32px;
        height: 32px;
        border-radius: 50%;
        cursor: pointer;
      }

      .close {
        width: 102px;
        height: 32px;
        background: #ff4d4f;
        border-radius: 2px;
        font-size: 14px;
        color: #ffffff;
        line-height: 32px;
        text-align: center;
        margin-left: 20px;
        cursor: pointer;
      }
    }
  }
  .main {
    margin-top: 24px;
    display: flex;
    flex: 1;
    .viedo-wrapper {
      display: flex;
      width: 49%;
      height: 50vh;
      background: #2d2d2d;
      &:first-of-type {
        margin-right: 2%;
      }
      .text {
        display: flex;
        flex-direction: column-reverse;
        width: 112px;
        margin-left: 24px;
        color: #fff;
        padding-bottom: 20px;
      }
      .time {
        display: flex;
        flex-direction: column-reverse;
        padding-bottom: 20px;
        width: 100px;
        margin-right: 24px;
        margin-left: 5px;
        color: #fff;
        .time-content {
          .call-btn {
            display: flex;
            justify-content: center;
            align-items: center;
            min-width: 100px;
            margin-bottom: 5px;
          }
          font-size: 12px;
          display: flex;
          flex-direction: column;
          justify-content: flex-start;
          align-items: flex-end;
        }
      }
      .viedo {
        flex: 1;
        display: flex;
        justify-content: center;
        align-items: center;
        position: relative;
        .user-icon {
          position: absolute;
          right: 0;
          bottom: 20px;
          display: block;
          width: 32px;
          height: 32px;
          z-index: 100;
        }
        & > div {
          height: 100%;
          width: 100%;
          video {
            width: 100%;
            height: 100%;
          }
        }
        .video-icon {
          width: 96px;
          height: 96px;
        }
        .mask {
          position: absolute;
          top: 0;
          left: 0;
          right: 0;
          bottom: 0;
          background: #2d2d2d;
          display: flex;
          justify-content: center;
          align-items: center;
          img {
            display: block;
            width: 93px;
            height: 125px;
          }
          .vocie {
            width: 93px;
            height: 93px;
          }
        }
      }
    }
  }

  .out {
    width: 102px;
    height: 32px;
    border-radius: 2px;
    border: 1px solid #ffffff;
    font-size: 14px;
    font-family: PingFangSC-Regular, PingFang SC;
    font-weight: 400;
    color: #ffffff;
    text-align: center;
    line-height: 32px;

    cursor: pointer;
    margin: 15px auto 6%;
  }
}
</style>
