<template>
  <div class="livebox">
    <div class="top">
      <div class="top-left">
        <div class="time-message">
          <p class="msg-img">
            <img :src="currentChat.diagnoseType == 2 ? im_text : im_video">
          </p>
          <span>{{ diagnoseType }}</span>
        </div>
        <div
          v-if="currentChat.diagnoseType != 3"
          class="time-message ml10"
        >
          <p class="msg-img">
            <img
              :src="im_time"
              alt
            >
          </p>
          <p>设定时长: {{ time }}分钟 &nbsp;&nbsp;</p>
          <p v-if="startTime && endTime">
            总时长: {{ useTime }}&nbsp;&nbsp;
          </p>
          <p v-if="startTime && endTime">
            剩余时长: {{ loseTime }}
          </p>
        </div>
      </div>
    </div>
    <div
      v-if="currentChat.diagnoseType == 1 || currentChat.diagnoseType == 2"
      class="main"
    >
      <div
        v-for="(item, index) of memberList"
        :key="index"
        class="viedo-wrapper"
      >
        <div class="text">
          <div class="text-left">
            <img
              :src="item && item.avatarImageUrl"
              alt
            >
          </div>
          <div class="text-right">
            <p>
              <span class="text-name">{{ item.name }}</span>
              <span class="text-dep">{{
                item.role == 1 ? '助诊医生' : '接诊医生'
              }}</span>
            </p>
            <p class="text-num">
              {{
                item.role == 1
                  ? currentChat.userMobile
                  : currentChat.doctorMobile
              }}
            </p>
          </div>
        </div>
        <div
          :id="rtc.viewslist[index] ? rtc.viewslist[index].id : ''"
          :class="{ viedowrap: currentChat.diagnoseType == 2 }"
        />
        <div
          :id="rtc.viewslist[index] ? rtc.viewslist[index].id : ''"
          class="viedo-btn-wrap"
        >
          <el-button
            class="call-btn"
            :class="{
              calling1: item.role == 1 && doctorTrtcEntryStatus != 2,
              calling2: item.role == 2 && userTrtcEntryStatus != 2,
            }"
            @click="drivingCall(item)"
          >
            {{
              item.role == 1
                ? showText(doctorTrtcEntryStatus)
                : showText(userTrtcEntryStatus)
            }}
          </el-button>
        </div>
      </div>
      <div class="vedio-man">
        <p
          class="man-img"
          @click="toggleVol"
        >
          <img
            :src="isMuted ? im_man2 : im_man1"
            alt
          >
        </p>
        <p class="man-txt">
          {{ isMuted ? '已静音' : '已接入' }}
        </p>
      </div>
    </div>
    <alert ref="alert" />
  </div>
</template>
<script>
  import {
    getLiveTimeText,
    countDown,
    getBroswer,
    laseTime,
    lastm,
  } from '@/utils/live';
  import RtcClient from '../../utils/RtcClient.js';
  import { closeLoading } from '@/utils/utils';
  import alert from '@/components/common/alert.vue';

  import { createNamespacedHelpers } from 'vuex';
  const { mapState } = createNamespacedHelpers('main');
  import {
    teamDetailV2,
    getSdkappid,
    streamParams,
    callDirect,
    usersigTrtc,
    diagnoseEndCall,
  } from '@/api/diagnosis';

  export default {
    components: {
      alert,
    },
    props: {
      doctorImg: {
        type: [String, Number],
        default: '',
      },
    },
    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'),
        im_text: require('../../assets/image/IM/im_text.png'),
        im_video: require('../../assets/image/IM/im_video.png'),
        im_time: require('../../assets/image/IM/im_time.png'),
        im_man1: require('../../assets/image/IM/im_man1.png'),
        im_man2: require('../../assets/image/IM/im_man2.png'),
        roleAnchor: 'anchor', // 主播
        rtc: null,
        roomId: '',
        sdkAppId: '',
        userSig: '',
        userId: '',
        viedoParams: null,
        askTime: 0, // 问诊医生接入时长
        answerTime: 0, // 接诊医生接入时长
        useTime: 0, // 问诊时长
        loseTime: 0, // 问诊剩余时长
        askTimeFn: null,
        answerTimeFn: null,
        useTimeFn: null,
        loseTimeFn: null,
        type: 1, // 1: 语音 2: 视频
        startTime: 0,
        endTime: 0,
        time: 30, // 总时长
        memberList: [],
        tid: '', // 群id
        diagnoseLogId: '', // 问诊id
        isMuted: true,
        liveInfoSave: {},
        userTrtcEntryStatus: 2,
        doctorTrtcEntryStatus: 2,
      };
    },
    computed: {
      ...mapState({
        currentChat: (state) => state.currentChat,
      }),
      diagnoseType() {
        switch (this.currentChat.diagnoseType) {
        case 1:
          return '语音问诊';
        case 2:
          return '视频问诊';
        case 3:
          return '图文问诊';
        default:
          return '';
        }
      },
    },
    watch: {
      currentChat(newVal, oldVal) {
        if (newVal !== oldVal && newVal.imTeamId) {
          const { imTeamId, diagnoseLogId } = this.currentChat;
          this.tid = imTeamId;
          this.diagnoseLogId = diagnoseLogId;
          this.init();
        }
      },
    },
    created() {},

    beforeDestroy() {
      this.clearTime();
    },
    methods: {
      async init() {
        if (!this.checkChrome()) {
          this.$nextTick(() => {
            this.$refs.alert.init({
              confirmTxt: '我知道了',
              title: '请下载新版Chrome浏览器',
            });
          });
          return false;
        }
        // 获取视频参数
        this.getViedoParams();
        this.getInfo(); // 获取用户信息列表
      },
      toggleVol() {
        if (this.isMuted) {
          this.rtc.unmuteLocalAudio();
        } else {
          this.rtc.muteLocalAudio();
        }
        this.isMuted = !this.isMuted;
      },
      // 主动呼叫
      drivingCall(data) {
        if (data.role == 1 && this.doctorTrtcEntryStatus != 2) {
          return false;
        }
        if (data.role == 2 && this.userTrtcEntryStatus != 2) {
          return false;
        }
        console.log('--this.roomId', this.currentChat, data, this.roomId);
        const params = {
          imAccId: data.accId,
          imTeamId: this.currentChat.imTeamId,
          liveRoomId: this.roomId,
        };
        callDirect(params).then((res) => {
          if (res.code === '000000') {
            // this.getInfo(data);
            // this.rtc.join()
            this.$message({
              message: '呼叫成功',
              type: 'success',
            });
            if (data.role == 1) {
              this.doctorTrtcEntryStatus = 3;
            }
            if (data.role == 2) {
              this.userTrtcEntryStatus = 3;
            }
          } else {
            this.$message({
              message: res.message,
              type: 'warning',
            });
          }
        });
      },
      // 获取相关信息
      getInfo() {
        const { imTeamId, roomId, diagnoseLogId } = this.currentChat;
        teamDetailV2({
          tid: imTeamId,
          roomId: roomId,
          diagnoseLogId: diagnoseLogId,
        })
          .then((res) => {
            if (res.code == '000000') {
              const { liveInfo, memberList } = res.data;
              console.log('---liveInfo', liveInfo, memberList);
              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;
                this.userId = liveInfo.liveUserId;
              }
              if (memberList && memberList.length) {
                memberList.forEach((item) => {
                  // 在当前群组中的角色 1: 问诊医生 2: 接诊医生 3: 居民 4: 其他
                  if (item.role == 1) {
                    this.memberList[0] = item;
                  }
                  if (item.role == 2) {
                    this.memberList[1] = item;
                  }
                });
              }
              this.getAppId();
            }
          })
          .catch(() => {
            this.getErr();
          });
      },
      // 获取AppId
      getAppId() {
        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(() => {
            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();
              return false;
            }
          })
          .catch(() => {
            this.getErr();
          });
      },
      // 创建trtcClient
      clientLogin() {
        if (Number(this.currentChat.diagnoseType) === 3) {
          return false;
        }
        const obj = {
          roomId: this.roomId,
          role: this.roleAnchor,
          sdkAppId: this.sdkAppId,
          userId: this.userId,
          userSig: this.userSig,
          vueInstance: this,
        };
        this.rtc = new RtcClient(obj);
        window.rtc = this.rtc;
        this.$nextTick(() => {
          this.$refs.alert
            .init({
              confirmTxt: '我知道了',
              title: '为了更好的体验,请保证您输出设备的正常使用',
            })
            .then(() => {
              Promise.all([this.rtc.join()]).then(() => {
                this.ispending();
                const t = setTimeout(() => {
                  closeLoading(this);
                  this.muteLocalAudio();
                  clearTimeout(t);
                }, 1000);
              });
            })
            .catch(() => {
              Promise.all([this.rtc.join()]).then(() => {
                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(() => {
            console.log('获取视频参数数据失败');
          });
      },
      // 关闭mc
      muteLocalAudio() {
        this.isMuted = true;
        this.rtc.muteLocalAudio();
      },
      // 打开mc
      unmuteLocalAudio() {
        this.isMuted = false;
        this.rtc.unmuteLocalAudio();
      },
      // 显示文案
      showText(status) {
        let text = '';
        switch (status) {
        case 1:
          text = '已接入';
          break;
        case 2:
          text = '呼叫医生';
          break;
        case 3:
          text = '呼叫中';
          break;
        default:
          text = '呼叫医生';
          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);
            if (item.role == 1) {
              this.doctorTrtcEntryStatus = 1;
            }
            if (item.role == 2) {
              this.userTrtcEntryStatus = 1;
            }
          }
        });
        console.log('---this.addNewMember', this.memberList, id);
      },
      // 用户下线
      removeMember(id) {
        this.memberList.forEach((item) => {
          if (item.liveUserId == id) {
            item.status = 3;
            if (item.role == 1) {
              this.doctorTrtcEntryStatus = 2;
            }
            if (item.role == 2) {
              this.userTrtcEntryStatus = 2;
            }
          }
        });
        console.log('---this.removeMember', this.memberList, id);
      },
      // 设置进行时长 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(() => {});
              });
            }
          }, 1000);
        } else if (new Date() < this.startTime) {
          const t = setInterval(() => {
            if (new Date() > this.startTime) {
              clearInterval(t);
              this.ispending();
            }
          }, 1000);
        }
      },
      // client离开房间
      leave() {
        this.muteLocalAudio();
        this.rtc.leave();
        this.clearSession();
        window.location.href = 'about:blank';
        window.close();
      },
      // 结束会话
      overFn() {
        this.$refs.alert
          .init({
            cancleTxt: '取消',
            confirmTxt: '我知道了',
            title: '确定要结束会话么？',
          })
          .then(() => {
            this.out();
          })
          .catch(() => {});
      },
      out() {
        diagnoseEndCall({
          diagnoseLogId: this.diagnoseLogId,
        })
          .then((res) => {
            if (res.code == '000000') {
              this.leave();
            } else {
              this.$refs.alert
                .init({
                  confirmTxt: '我知道了',
                  title: '操作失败,请稍后重试',
                })
                .then(() => {})
                .catch(() => {});
            }
          })
          .catch(() => {
            this.$refs.alert
              .init({
                confirmTxt: '我知道了',
                title: '操作失败,请稍后重试',
              })
              .then(() => {})
              .catch(() => {});
          });
      },
      // 获取信息失败
      getErr() {
        closeLoading(this);
      },
      reloadfn() {
        this.$nextTick(() => {
          this.$refs.alert
            .init({
              confirmTxt: '我知道了',
              title: '加入房间失败，重新加入',
            })
            .then(() => {
            // location.reload();
            })
            .catch(() => {
            // location.reload();
            });
        });
      },
      clearTime() {
        clearInterval(this.askTimeFn);
        clearInterval(this.answerTimeFn);
        clearInterval(this.useTimeFn);
        clearInterval(this.loseTimeFn);
        this.isMuted = true;
      },
      // 清除直播时间相关的seession
      clearSession() {
        this.isMuted = true;
        sessionStorage.removeItem('TIME_askTime');
        sessionStorage.removeItem('TIME_answerTime');
        sessionStorage.removeItem('TIME_useTime');
        sessionStorage.removeItem('TIME_loseTime');
      },
      // 检查是否为chrome
      checkChrome() {
        return getBroswer().broswer == 'Chrome';
      },
    },
  };
</script>
<style lang="scss" scoped>
.livebox {
  display: flex;
  flex-direction: column;
  background: #ffffff;
  padding: 15px 24px;
  padding-top: 0px;
  .top {
    .top-left {
      text-align: left;
      display: flex;
      .time-message {
        display: flex;
        height: 24px;
        line-height: 24px;
        background: #f0f2f5;
        border-radius: 23px;
        color: #6a7990;
        font-size: 14px;
        padding: 0px 15px;
        .msg-img {
          width: 12px;
          height: 12px;
          margin-right: 10px;
          img {
            width: 100%;
            height: 100%;
          }
        }
      }
      .ml10 {
        margin-left: 10px;
      }
    }
    .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: 25px;
    display: flex;
    flex: 1;
    .viedo-wrapper {
      width: 224px;
      // height: 240px;
      background: #f0f2f5;
      border-radius: 18px;
      padding: 15px;
      margin-right: 2%;
      position: relative;
      .text {
        display: flex;
        .text-left {
          width: 36px;
          height: 36px;
          background: #dddddd;
          border-radius: 36px;
          img {
            width: 100%;
            height: 100%;
          }
        }
        .text-right {
          margin-left: 5px;
          text-align: left;
          white-space: nowrap;
          .text-name {
            font-size: 18px;
            color: #063948;
            font-weight: bold;
          }
          .text-dep {
            margin-left: 5px;
            font-size: 14px;
            color: #063948;
          }
          .text-num {
            font-size: 14px;
            color: #6a7990;
          }
        }
      }
      .time {
        display: flex;
        flex-direction: column-reverse;
        padding-bottom: 20px;
        width: 100px;
        margin-right: 24px;
        margin-left: 5px;
        color: #fff;
        .time-content {
          font-size: 12px;
          display: flex;
          flex-direction: column;
          justify-content: flex-start;
          align-items: flex-end;
        }
      }
      .viedo-btn-wrap {
        .call-btn {
          width: 173px;
          height: 38px;
          background: #449284;
          border-radius: 23px;
          color: #ffffff;
          margin-top: 15px;
          border: none;
        }
        .calling1,
        .calling2 {
          background: #9fc8c0;
        }
        .viedo-container {
          width: 100px;
          height: 100px;
          margin: auto;
          margin-top: 15px;
          // position: absolute;
          // top: 0;
          // left: 0;
          // right: 0;
          // bottom: 0;
          // margin:  auto;
        }
      }
      .viedowrap {
        height: 180px;
      }
    }
    .vedio-man {
      width: 120px;
      height: 120px;
      background: #f0f2f5;
      border-radius: 18px;
      padding: 9px;
      .man-img {
        width: 61px;
        height: 61px;
        border-radius: 61px;
        background: #449284;
        text-align: center;
        margin: 0 auto;
        img {
          width: 100%;
        }
      }
      .man-txt {
        margin-top: 18px;
        color: #449284;
        font-size: 14px;
      }
    }
  }

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