<template>
    <div class="rtcPlayer">
        <video ref="webrtcPlayer" class='webRtcPlayerBox' controls autoplay style="text-align:left;">
            Your browser is too old which doesn't support HTML5 video.
          </video>
    </div>
</template>

<script>
import ZLMRTCClient from "@/assets/ZLMRTCClient";
import {webrtcEvent} from "@/map/eventMap";


// let  = null;
export default {
    name: 'rtcPlayer',
    data() {
        return {
          timer: null,
          webrtcPlayer: null,
        };
    },
    props: {
      videoUrl:{
        type: String,
        default: null
      },
      hasAudio:{
        type: Boolean,
        default: false
      },
      fps:{
        type: Number,
        default: 30
      },
      enableDebug:{
        type: Boolean,
        default: false
      },
    },
    mounted () {
      let paramUrl = decodeURIComponent(this.$route.params.url)
       this.$nextTick(() =>{
         if (typeof (this.videoUrl) == "undefined") {
           this.videoUrl = paramUrl;
         }
         // console.log("初始化时的地址为: " + this.videoUrl)
         this.play(this.videoUrl)
        })
    },
    watch:{
        videoUrl(newData, oldData){
          console.log("播放地址为: " + newData);
            this.pause();
            this.play(newData, this.hasAudio, this.fps, true);
        },
        immediate:true
    },
    methods: {
        play(url,hasAudio,fps,enableDebug = false) {
          // this.enableDebug = enableDebug;
          if(enableDebug){
            console.log("播放地址为: " + url);
          }

          // 获取ref webrtcPlayer
          let webrtcPlayer = this.$refs.webrtcPlayer;
          if(!webrtcPlayer){
            console.log("无法获取到对应的 dom");
            return
          }
          // console.log(webrtcPlayer);
          webrtcPlayer.addEventListener("pause", () => {
            if(enableDebug){
              console.log("暂停");
            }
            this.eventCallback(webrtcEvent.paused.code, "暂停")
          });

          webrtcPlayer.addEventListener("error", (e)=>{
            console.log('播放异常');
            console.log(e);
          })
          this.webrtcPlayer = new ZLMRTCClient.Endpoint({
                element: webrtcPlayer,// video 标签
                debug: enableDebug,// 是否打印日志
                zlmsdpUrl: url,//流地址
                simulecast: false,
                useCamera: false,
                audioEnable: true,
                videoEnable: true,
                recvOnly: true,
            });

          this.webrtcPlayer.setLog('info',(tag, msg) => {

              console.log('收到zlm log');
              if(enableDebug){
                  console.log(tag, msg);
              }
          })
          this.webrtcPlayer.on(ZLMRTCClient.Events.CONNECT_FAIL, (err) => {
              if(enableDebug){console.log('error', err);}
                this.eventCallback(webrtcEvent.apiFail.code, err)
            });
          this.webrtcPlayer.on(ZLMRTCClient.Events.WEBRTC_ICE_CANDIDATE_ERROR,(e)=>{// ICE 协商出错
                if(enableDebug){console.error('ICE 协商出错')}
                this.eventCallback(webrtcEvent.iceError.code, "ICE 协商出错")
            });

            this.webrtcPlayer.on(ZLMRTCClient.Events.WEBRTC_ON_REMOTE_STREAMS,(e)=>{//获取到了远端流，可以播放
                if(enableDebug){console.log('播放成功',e.streams)}
                this.eventCallback(webrtcEvent.played.code, "播放成功")
                webrtcPlayer.play();
            });

            this.webrtcPlayer.on(ZLMRTCClient.Events.WEBRTC_OFFER_ANWSER_EXCHANGE_FAILED,(e)=>{// offer anwser 交换失败
                if(enableDebug){console.error('offer anwser 交换失败',e)}

                this.eventCallback(webrtcEvent.sdpFail.code, "offer anwser 交换失败")
                if (e.code ==-400 && e.msg=="流不存在"){
                    if(enableDebug){console.log("流不存在")}
                    this.timer = setTimeout(()=>{
                        this.webrtcPlayer.close();
                    }, 100)

                }
            });

            this.webrtcPlayer.on(ZLMRTCClient.Events.WEBRTC_ON_LOCAL_STREAM,(s)=>{// 获取到了本地流

                // document.getElementById('selfVideo').srcObject=s;
                this.eventCallback(webrtcEvent.localStream.code, "获取到了本地流")
            });

        },
        pause: function () {
            if (this.webrtcPlayer != null) {
                this.webrtcPlayer.close();
                this.webrtcPlayer = null;
            }

        },
        eventCallback: function(type, message) {
          if(this.enableDebug) {
            console.log("player 事件回调")
            console.log(type)
            console.log(message)
          }
          this.$emit("eventCallback", type, message);
        }
    },
    destroyed() {
        clearTimeout(this.timer);
    },
}
</script>

<style>
    .LodingTitle {
        min-width: 70px;
    }
    .rtcPlayer{
        width: 100%;
        height: 100%;
    }
    .rtcPlayer > video{
        width: auto;
        height: 100%;
    }


</style>
