<template>
    <van-row class="recordList">
      <van-row class="titleWrap">
        <span class="line"></span>
        <span class="title">实时视频</span>
        <div  class="videoSelect" v-if="videoSelect">
          <el-select @change="videoSelect1" v-model="video1" placeholder="请选择摄像头" class="videoSelect1">
              <el-option
              v-for="item in videoSelect"
              :key="item.url"
              :label="item.name"
              :value="item.url"
              >
              </el-option>
          </el-select>
          <!-- <el-select @change="videoSelect2" v-model="video2" placeholder="请选择摄像头2" class="videoSelect2">
              <el-option
              v-for="item in videoSelect"
              :key="item.url"
              :label="item.name"
              :value="item.url"
              >
              </el-option>
          </el-select> -->
      </div>
    </van-row>
    <el-row class="videoList" :gutter="20">
      <el-col class="video" :span="24" v-if="isIos">
        <div id="videobox" ref="video">
          <easyPlayer :videoUrl="url" autoplay :live="true" :poster="poster" ></easyPlayer>
          <div class="videoTitle">{{name1}}</div>
          <!-- <video id="videoPlayer" class="video-js" style="width: 100%; height: 100%;"></video> -->
          <!-- <video id="my-video" class="video-js vjs-default-skin" controls="" preload="none" x5-playsinline="" playsinline="" webkit-playsinline="" poster="" x-webkit-airplay="allow" >
            <source src="" type="application/x-mpegURL">
          </video> -->
          <!-- <video ref="videoPlayer" class="video-js"></video> -->
         <!-- <video id="myVideo" class="video-js vjs-default-skin vjs-big-play-centered" controls preload="auto" :poster="poster" width="100%"  ref="video" >
            <source id="source" :src="url" type="application/x-mpegURL">
          </video> -->
          <!-- <div class="videoTitle">{{name1}}</div> -->
            <!-- <video id="myVideo" 
                
                class="hlsVideo monitor-height"
                ref="hlsvideo"
                style="width: 100%"
                :poster="poster"
                controls
                >
                <source id="source" src="http://videocdn.didano.com/school765class0channelId2761namedingdangm/playlist.m3u8" type="application/x-mpegURL">
            </video> -->
        </div>
            <!-- <video id="myVideo1" 
                preload="true"
                autoplay="autoplay" 
                class="hlsVideo monitor-height"
                ref="hlsVideo1"
                style="width: 100%"
                :poster="poster"
                controls
                muted>
               <source id="source" :src="url1" type="application/x-mpegURL">
              </video> -->
             <!-- <div class="videoTitle">{{name1}}</div> -->
        </el-col>
        <el-col class="video" :span="24" v-if="isAndroid">
            <video 
                preload="true"
                autoplay="autoplay" 
                class="hlsVideo monitor-height"
                ref="hlsVideo1"
                style="width: 100%"
                :poster="poster"
                controls
                muted
            ></video>
             <div class="videoTitle">{{name1}}</div>
        </el-col>
    </el-row>
    </van-row>
</template>
<script>
import "videojs-flash";
import EasyPlayer from '@easydarwin/easyplayer'

import poster from "@/assets/image/poster.jpg";
import 'video.js/dist/video-js.css'
import Hls from "hls.js";
import videojs from 'video.js'
import 'videojs-contrib-hls'
export default {
  props:['info'],
  components: {
    EasyPlayer
  },
  data() {
    return {
      videoSelect:true,
      hls1:undefined,
      hls2:undefined,
      video1:undefined,
      video2:undefined,
      name1:undefined,
      name2:undefined,
      poster:poster,
      url:"http://10.208.64.8:7086/live/cameraid/1000001%240/substream/1.m3u8",
      // url:"http://10.208.64.8:7086/live/cameraid/1000001%240/substream/1.m3u8",
      url2:"https://video.hua.com/publicity_video_2020_m.mp4",
      isAndroid:false,
      isIos:false,
      options: {
        playsInline:true,
        poster: poster,//封面图
        fluid: true, // 自适应宽高
        autoplay: true, // 设置自动播放
        muted: true, // 设置了它为true，才可实现自动播放,同时视频也被静音（Chrome66及以上版本，禁止音视频的自动播放）
        preload: 'auto', // 预加载
        controls: true, // 显示播放的控件
        aspectRatio: '16:9', // 将播放器置于流畅模式，并在计算播放器的动态大小时使用该值。值应该代表一个比例 - 用冒号分隔的两个数字（例如"16:9"或"4:3"）
      },
      player: null,
    };
  },
  created(){
    this.init()
    //this.isTerminal()
  },
  
  mounted() {
    videojs.addLanguage('zh-CN', {
      "You aborted the media playback": "视频播放被终止",
      "A network error caused the media download to fail part-way.": "网络错误导致视频下载中途失败。",
      "The media could not be loaded, either because the server or network failed or because the format is not supported.": "视频因格式不支持或者服务器或网络的问题无法加载。",
      "The media playback was aborted due to a corruption problem or because the media used features your browser did not support.": "由于视频文件损坏或是该视频使用了你的浏览器不支持的功能，播放终止。",
      "No compatible source was found for this media.": "无法找到此视频兼容的源。",
    });
  },
  methods: {
 
     // 销毁
    beforeDestroy () {
      if (this.player) {
        this.player.dispose()
      }
    },
    creatVideo() {
      this.options = {
        poster: this.poster, // 视频封面图地址
        autoplay: true, // 如果true,浏览器准备好时开始播放。
        muted: true, // 默认情况下将会消除任何音频。
        loop: true, // 导致视频一结束就重新开始。
        preload: 'auto', // auto浏览器选择最佳行为,立即开始加载视频（如果浏览器支持）
        language: 'zh-CN',  //汉化
        fluid: true, // 当true时，播放器将拥有流体大小。换句话说，它将按比例缩放以适应其容器。
        sources: [{
            type: 'application/x-mpegURL',
            src: this.url  //视频播放地址
        }],
        notSupportedMessage: '此视频暂无法播放，请稍后再试', // 无法播放媒体源时显示的默认信息。
        controlBar: {
          timeDivider: true,
          durationDisplay: true,  //视频时长时间显示
          remainingTimeDisplay: false,  //剩余时间显示
          fullscreenToggle: true // 全屏按钮
        },
        errorDisplay: false,  //错误显示
        posterImage: false,  //视频的预览海报图片显示
        bigPlayButton: true,  //视频中间的播放按钮显示
        textTrackDisplay: false
      }
      
      // 视频初始化
      setTimeout(()=>{
        this.player = this.$video(this.$refs.videoPlayer, this.options);
        this.player.play();
      },1000)
        
      
      // let video = document.createElement('video');
      // video.id = 'video';
      // video.style = 'width: 100%; height: 100%;';
      // video.controls = true;
      // // video.autoplay = true;
      // // video.setAttribute('playsinline', true) //IOS微信浏览器支持小窗内播放
      // // video.setAttribute('webkit-playsinline',true) //这个bai属性是ios 10中设置可以让视频在小du窗内播放，也就是不是全zhi屏播放的video标签的一个属性
      // // video.setAttribute('x5-video-player-type', 'h5') //安卓 声明启用同层H5播放器 可以在video上面加东西
      // let source = document.createElement('source');
      // source.src =  this.url; // 视频地址
      // source.type = 'application/x-mpegURL';
      // this.$nextTick(()=>{  
      //   let that = this;
      //   video.appendChild(source);
      //   this.$refs.video1.appendChild(video);
      //   //setTimeout(()=>{
      //       this.player = videojs('video', {
      //       poster: this.poster, // 视频封面图地址
      //       title: '',
      //       playbackRates: [0.7, 1.0, 1.5, 2.0], //播放速度
      //       autoDisable: true,
      //       preload: 'none', //auto - 当页面加载后载入整个视频 meta - 当页面加载后只载入元数据 none - 当页面加载后不载入视频
      //       language: 'zh-CN',
      //       fluid: true, // 自适应宽高
      //       muted: false, //  是否静音
      //       //aspectRatio: '16:9', // 将播放器置于流畅模式，并在计算播放器的动态大小时使用该值。值应该代表一个比例 - 用冒号分隔的两个数字（例如"16:9"或"4:3"）
      //       controls: true, //是否拥有控制条 【默认true】,如果设为false ,那么只能通过api进行控制了。也就是说界面上不会出现任何控制按钮
      //       autoplay: 'muted', //如果true,浏览器准备好时开始回放。 autoplay: "muted", // //自动播放属性,muted:静音播放
      //       loop: true, // 导致视频一结束就重新开始。 视频播放结束后，是否循环播放
      //       techOrder: ["html5", "flash"], //播放顺序
      //       sources: [{
	    //        src: this.url
	    //       }],
      //       //screenshot: true,
      //       controlBar: {
      //         // volumePanel: { //声音样式
      //         //   inline: false // 不使用水平方式
      //         // },
      //         // timeDivider: true, // 时间分割线
      //         // durationDisplay: true, // 总时间
      //         // progressControl: false, // 进度条
      //         // remainingTimeDisplay: true, //当前以播放时间
      //         // fullscreenToggle: true, //全屏按钮
      //         // pictureInPictureToggle: false, //画中画
      //       }
      //     }, function (){
      //       this.play()

      //       this.on("waiting", function ()
      //       {	
      //           this.addClass("vjs-custom-waiting");
      //       });
      //       this.on("playing", function ()
      //       {
      //           this.removeClass("vjs-custom-waiting");
      //       });
      //       this.on('loadeddata',function () {
      //       });
      //       this.on('error', function(err) {
      //         this.errorDisplay.close(); //不显示错误信息
      //         // 报错之后自动重新加载
      //         that.player.src([
      //           {
      //             src: that.url, //播放视频地址
      //             type: "application/x-mpegURL", // 告诉videojs,这是一个hls流
      //           },
      //         ]);
      //       })
      //     });
      //   //})
        
      // }) 
      
    },
    videoPlay(){
      setTimeout(()=>{
        var myvideo = document.getElementsByTagName("video")[0]
        var setTimeFlag = 1;//currentTime属性赋值次数

        this.$refs.video.play();
        //当目前的播放位置已更改时触发
        myvideo.timeupdate = 2

        myvideo.addEventListener("timeupdate", function(){
          // this.$refs.video.play();
          //   if(setTimeFlag == 1){
          //   //获取localStorage中记录的currentTime值，并给currentTime属性进行赋值
          //       if (localStorage.getItem('currentTime' + '{$study->study_id}') != null) {
          //           var time = localStorage.getItem('currentTime' + '{$study->study_id}');
          //           myvideo.currentTime = time;
            
          //       }
          //   setTimeFlag = 2;
          //   }
          //   //获取当前播放位置的秒数，并设置localStorage
          //   var currentTime = myvideo.currentTime;
          // localStorage.setItem('currentTime' + '{$study->study_id}', currentTime)
          
          //this.$refs.video.play();
        });
        
      },0)

    },
    isTerminal() {//终端判断
      
    },


    init(){ //初始化数据
      
        axios({
            method: 'post',
            url: 'http://10.21.39.1:8082/dhController/getLocalChannel',
            data:{
                pageNo: 1,
                pageSize: 300,
                unitType: 1,
            },
            timeout: 3000,
        }).then(res =>{
            if(res.data.data.pageList){
                let data = res.data.data.pageList
                this.videoSelect = data
                this.isTerminal()
                for(let i = 0; i<data.length; i++){
                    this.videoSelect[i].url = "http://" + data[i].nvr_ip + ":" + data[i].hls_port + "/live/cameraid/" + data[i].deviceId + "%24" + data[i].id.split("$")[(data[i].id.split("$")).length-1]  + "/substream/1.m3u8"
                    this.videoSelect[i].url = this.videoSelect[i].url +  ',' + data[i].name
                }
                this.video1 = this.videoSelect[0].url
                let u = navigator.userAgent;
                let isAndroid = u.indexOf("Android") > -1 || u.indexOf("Adr") > -1; //android终端
                let isIOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //
                setTimeout(()=>{
                  if (isIOS) {
                    this.isIos = true
                    
                    this.videoSelect1(this.videoSelect[0].url)
                    
                    
                    
                  } else {
                    this.isAndroid = true
                    this.videoSelect1(this.videoSelect[0].url)
                  }
                },1000)
                
            }
        }).catch(err =>{
        })
        
      },
      videoSelect1(value){
        let arr = value.split(',')
        this.name1 = arr[1]
        if(this.isIos){
          this.url = arr[0]
          this.beforeDestroy()
        }else{
          this.destroyHls(1)
          this.loadVideoFn(1,arr[0])
        }
        
      },
      videoSelect2(value){
        this.destroyHls(2)
        let arr = value.split(',')
        this.name2 = arr[1]
        this.loadVideoFn(2,arr[0])
      },

      destroyHls(id){//关闭视频拉取
          if (this.hls) {
              if(id=="1"){
                  this.$refs.hlsVideo1.pause();
                  this.hls1.destroy();
                  this.hls1 = null;
              }else{
                  this.$refs.hlsVideo2.pause();
                  this.hls2.destroy();
                  this.hls2 = null;
              }
              
          }
      },
      loadVideoFn(id,url) {//视频播放
          setTimeout(() =>{
              if (Hls.isSupported()) {
                  if(id == "1"){
                      this.hls1 = new Hls();
                      this.hls1.loadSource(url);
                      this.hls1.attachMedia(this.$refs.hlsVideo1);
                      this.hls1.on(Hls.Events.MANIFEST_PARSED, () => {
                          this.$refs.hlsVideo1.play();
                      });
                      this.hls1.on(Hls.Events.ERROR, (event, data) => {
                      });
                  }else{
                      this.hls2 = new Hls();
                      this.hls2.loadSource(url);
                      this.hls2.attachMedia(this.$refs.hlsVideo2);
                      this.hls2.on(Hls.Events.MANIFEST_PARSED, () => {
                          this.$refs.hlsVideo2.play();
                      });
                      this.hls2.on(Hls.Events.ERROR, (event, data) => {
                      });
                  }
              }
          },1000)
      },
  },
};
</script>

<style lang="scss" scoped>

  .title{
      width:80px;
      display: inline-block;
  }
  
  .videoList{
      margin:15px 0 0px;
      .video{
           margin:0 auto;
           position: relative;
           background-color: #fff;
          video{
              // height:200px;
          }
          .videoTitle{
          position: absolute;
          right:16px;
          bottom:20px;
          font-size: 14px;
          color: #fff;
          background-color: rgba(0,0,0,0.3);
          padding:4px 12px;
      }

      }
      
  }


::v-deep .el-input__inner {
  background-color: transparent !important;
  color: #fff;
  height: 36px;
}
/**修改边框和字体颜色 */
::v-deep .el-select {
  position: relative;
  width: 120px;
  display: inline-block;
  margin-left:2px;
  .el-input {
    input {
      height: 20px;
      border-color: #ccc;
      color: #ccc;
      font-size: 10px;
    }
  }
  
}
/**修改下拉图标颜色 */
::v-deep .el-input__suffix {
  .el-input__suffix-inner {
    .el-icon-arrow-up:before {
      color: #ccc;
      padding-left: 0.11rem;
      margin-top:10px;
    }
  }
}

.el-select-dropdown__item{
    padding:0 12px !important;
    font-size: 12px !important;
    height:20px !important;
    line-height: 20px !important;
    color:#fff;
}
.el-select-dropdown__item.hover{
    background-color: red;
}
::v-deep.el-input__icon{
    line-height: auto !important;
  }

</style>
<style >
.el-scrollbar{
    background-color: rgba(35,40,49,1);
} 
.el-scrollbar{
    border:1px solid rgba(35,40,49,1) !important;

}
.videoSelect{
    display: inline-block;
    float:right;
  }
  .el-input__icon{
    line-height: 0;
  }
.video-js{
  width:100%;
  height:auto;
}
.vjs-big-play-button{
left:50% !important;
top: 50% !important;
margin-top: -1em ;
margin-left: -1.5em ;

}
#videobox{
  width:100%;
  height:200px;
}
.easy-player-loading{
  display: none !important;
}
.el-input__prefix, .el-input__suffix{
margin-top:-3px !important;
}
</style>

