<template>
  <div style="position: relative;">
    <transition name="fade">
      <div class="panel monitor" >
        <div class="panel-tit">
          视频监控
          <img
            class="setting"
            src="@/assets/setting.png"
            alt=""
            @click="open"
          />
        </div>
        <ul class="monitor-list" >

          <li v-for="(hls, index) in hls_video" :key="index" style="height:14vh">
            <video
              v-if="hls.boolhls"
              class="hlsVideo monitor-height"
              @click="hlsVideo(hls.name)"
              :ref="hls.ref"
              controls
              preload="true"
              muted
            ></video>
            <p style="width:90%;margin:6px 5%;font-size: 1.4rem">{{hls.name}}</p>
          </li>
        </ul>
        <div class="panel-footer"></div>

        <div class="panel monitor-setting" v-if="showModal">
          <div class="panel-tit">
            画面配置<img
              class="close"
              src="@/assets/close.png"
              alt=""
              @click="showModal = false"
            />
          </div>
          <div class="monitor-option">
            <el-form ref="form" :model="form" label-width="10rem">
              <el-form-item label="画面一：" >
                <el-select class="selectWrap"  v-model="selectVideoHc[0].url"  @change="handleChange(0,selectVideoHc[0].url)">
                  <el-option v-for="(item,index) in list" :key="index" :label="item.label" :value="item.url"   class="select1" />
                </el-select>
              </el-form-item>
              <el-form-item label="画面二：">
                <el-select class="selectWrap"  v-model="selectVideoHc[1].url"  @change="handleChange(1,selectVideoHc[1].url)">
                  <el-option v-for="(item,index) in list" :key="index" :label="item.label" :value="item.url"   class="select1" />
                </el-select>
              </el-form-item>
              <el-form-item label="画面三：">
                <el-select class="selectWrap"  v-model="selectVideoHc[2].url"  @change="handleChange(2,selectVideoHc[2].url)">
                  <el-option v-for="(item,index) in list" :key="index" :label="item.label" :value="item.url"   class="select1" />
                </el-select>
              </el-form-item>
              <el-form-item label="画面四：">
                <el-select class="selectWrap"  v-model="selectVideoHc[3].url"  @change="handleChange(3,selectVideoHc[3].url)">
                  <el-option v-for="(item,index) in list" :key="index" :label="item.label" :value="item.url"   class="select1" />
                </el-select>
              </el-form-item>
              <el-form-item label="画面五：">
                <el-select class="selectWrap"  v-model="selectVideoHc[4].url"  @change="handleChange(4,selectVideoHc[4].url)">
                  <el-option v-for="(item,index) in list" :key="index" :label="item.label" :value="item.url"   class="select1" />
                </el-select>
              </el-form-item>
              <el-form-item label="画面六：">
                <el-select class="selectWrap"  v-model="selectVideoHc[5].url" @change="handleChange(5,selectVideoHc[5].url)">
                  <el-option v-for="(item,index) in list" :key="index" :label="item.label" :value="item.url"   class="select1" />
                </el-select>
              </el-form-item>
              <el-form-item style="margin-left:-2rem">
                <el-button @click="cancel">取消</el-button>
                <el-button type="primary" @click="submit"
                  >保存</el-button
                >
              </el-form-item>
            </el-form>
          </div>
          <div class="panel-footer"></div>
        </div>
      </div>
    </transition>
    <iframe
      id="otherPage"
      align="middle"
      :src="iframe_Url"
      :style="'width:' + width + ';'"
    ></iframe>
    <el-dialog :visible.sync="videoS" @close='closeDialog'  width="600"   :modal="false">
        <div
          class="titleZise"
          style="font-size: 16px; color: #484848; font-weight: 700;margin:10px 0 0 20px;"
        >{{videoMsg.name}}
        </div>
      <video
        class="hlsVideo222 monitor-height"
        ref="hlsVideo222"
        style="width: 100%;margin-top:6px;z-index:9000"
         controls
              preload="true"
              muted
      ></video>
    </el-dialog>
  </div>
</template>
<script>
import Hls from "hls.js";
import { getLocalDeviceList, getLocalUnitNodes,  getLocalChannel } from "@/api/device/camera";
import api from "@/api/monitor";
import {  Message } from 'element-ui'
export default {
  name: "monitor",
  props: {
    width: String,
    required: true,
  },
  data() {
    return {
      hls2:"",
       videoS:false,
      configKey: undefined,
      configName: undefined,
      configId:undefined,
      video:false,
      selectVideo:[
        {
          label:undefined,
          url:undefined,
        },
        {
          label:undefined,
          url:undefined,
        },
        {
          label:undefined,
          url:undefined,
        },
        {
          label:undefined,
          url:undefined,
        },
        {
          label:undefined,
          url:undefined,
        },
        {
          label:undefined,
          url:undefined,
        },
      ],
      selectVideoHc:[
        {
          label:undefined,
          url:undefined,
        },
        {
          label:undefined,
          url:undefined,
        },
        {
          label:undefined,
          url:undefined,
        },
        {
          label:undefined,
          url:undefined,
        },
        {
          label:undefined,
          url:undefined,
        },
        {
          label:undefined,
          url:undefined,
        },
      ],
      expandOnClickNode: true,
      options:[],
      list:[],
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      showModal_tow: false,
      showModal: false,
      hls: "",
      form: {
        name: "",
        region: "",
        region2: "",
        region3: "",
        region4: "",
        region5: "",
        region6: "",
        date1: "",
        date2: "",
        delivery: false,
        type: [],
        resource: "",
        desc: "",
      },
      hls_video: [],
      hls_video2: [],
      iframe_Url: "",
      tableData:[],
      videoMsg:{

      }
    };
  },
  created(){
    this.getVideoUrl()
    this.getList()
  },
  mounted() {
    let _this = this;
    _this.iframe_Url = window.PLATFROM_IFRAME.iframeUrl;
    // _this.getLocalChannel();
    window.addEventListener(
      "message",
      function (event) {
        var isDOM = typeof event.data === "object";
        // // 监听父窗口发送过来的数据向服务器发送post请求
        var msg = event.data;
        if(msg?.param?.name){
          getLocalChannel({pageNo:1,pageSize:1000,name:msg.param.name,token:"d6790e9ac3c419f6fc8d48f8c2957afd"}).then(Response =>{
            if(Response.data.pageList.length>0){
              let data = {}
              for(let i =0;i<Response.data.pageList.length;i++){
                if(msg.param.name == Response.data.pageList[i].name){
                  data = Response.data.pageList[i]
                }
              }
              _this.videoMsg = data
              _this.videoS = true
              let url = "http://" + data.nvr_ip + ":" + data.hls_port + "/live/cameraid/" + data.deviceId + "%24" + data.id.split("$")[(data.id.split("$")).length-1]  + "/substream/1.m3u8"
              _this.hls_video2 = [
                {name:"hlsVideo222",ref:"hlsVideo222",hls:"hlsVideo222", boolhls: true,boolimg: false,}
              ]
              _this.loadVideoFn2(url)
            }else{
              _this.$message.error("设备未绑定"); //登录失败提示错误
            }
          })
        }
      },
      false
    );
  },
  methods: {
    //关闭弹框
    closeDialog(){
      this.destroyHls()
    },
    handleChange(id,val){
      this.selectVideoHc[id].label = this.list.find( item => item.url == val).label
    },

    //获取视频配置数据
    getList(){
       getLocalChannel({unitType:1,pageNo:1,pageSize:500,token:"d6790e9ac3c419f6fc8d48f8c2957afd"}).then(Response =>{
        if(Response.data.pageList.length>0){
          let data = Response.data.pageList
          let arr = []
          for(let i = 0;i<data.length;i++){
            arr[i] = {label:undefined,url:undefined}
            arr[i].label = data[i].name
            arr[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.list = arr
        }
      })
    },
    //增加视频参数
    addVideoUrl(){
      var video = {}
      video.video = this.selectVideo
      api.addVideoUrl(
        {
          configKey: "video.top.device",
          configName: "video",
          configValue: JSON.stringify(video)
        }
      ).then(Response =>{
        if(Response.status == "SUCCESS"){
          Message({
            message: "摄像头配置添加成功",
            type: 'success'
          })
        }
      })
    },
    //获取视频参数
    getVideoUrl(){
      api.getVideoUrl("video.top.device").then(Response =>{
        if(Response.status == "SUCCESS"){
          this.selectVideo = this.deepClone(JSON.parse(Response.data.configValue).video)
          this.selectVideoHc = this.deepClone(JSON.parse(Response.data.configValue).video)
          for(let i =0;i<this.selectVideo.length;i++){
            this.hls_video.push({
              ref: "hlsVideo" + (i),
              name: this.selectVideo[i].label,
              hls: "hlsVideo" + (i),
              url:this.selectVideo[i].url,
              boolhls: true,
              boolimg: false,
            });
            this.loadVideoFn(this.hls_video[i].url, this.hls_video[i].ref, i)
          }
        }
      })
    },
    //修改数据
    updateVideoUrl(){
      var video = {}
      video.video = this.selectVideoHc
      api.updateVideoUrl(
        {
          configId:11,
          configKey: "video.top.device",
          configName: "video",
          configValue: JSON.stringify(video)
        }
      ).then(Response =>{
        if(Response.status == "SUCCESS"){
          Message({
            message: "摄像头配置修改成功",
            type: 'success'
          })
        }
      })
    },
    //下拉点击
    handleNodeClick(data,type) {
      if(data.name){
        var x = document.getElementsByClassName("el-select-dropdown");
        var i;
        for (i = 0; i < x.length; i++) {
            x[i].style.display = "none"
        }
        this.selectVideoHc[type-1].url = data.url
        this.selectVideoHc[type-1].label = data.label
      }
    },

    //下拉取消
    cancel(){
      this.selectVideoHc = []
      this.showModal = false
    },
    deepClone(obj){  //可传入对象 或 数组
      //  判断是否为 null 或 undefined 直接返回该值即可,
      if(obj === null || !obj)return obj;
      // 判断 是要深拷贝 对象 还是 数组
      if(Object.prototype.toString.call(obj)==="[object Object]"){ //对象字符串化的值会为 "[object Object]"
        let target = {}; //生成新的一个对象
        const keys =  Object.keys(obj); //取出对象所有的key属性 返回数组 keys = [ ]
        //遍历复制值, 可用 for 循环代替性能较好
        keys.forEach(key=>{
          if(obj[key]&&typeof obj[key] === "object")
              //如果遇到的值又是 引用类型的 [ ] {} ,得继续深拷贝
            target[key] = this.deepClone(obj[key]);//递归
          else
            target[key] = obj[key];

        })
        return target  //返回新的对象
      }else if(Array.isArray(obj)){
        // 数组同理
        let arr = [];
        obj.forEach((item,index)=>{
          if(item&&typeof item === "object")
            arr[index] = this.deepClone(item);
          else
              arr[index] = item;
        })
        return arr
      }
    },
    //
    open(){
      this.selectVideoHc = this.deepClone(this.selectVideo)
      this.showModal = true
    },
    //下拉保存
    submit(){
      this.updateVideoUrl()
      setTimeout(()=>{
        this.$emit('monitorChange')
      },1000)

      this.showModal = false

    },
    //画面配置事件处理
    video_hmpz(video, i) {
      var _this = this;
      var ref_video = this.hls_video[i].ref;
      var hls_video = this.hls_video[i].hls;
      if ((ref_video, this.$refs[ref_video][0] != undefined)) {
        this.$refs[ref_video][0].pause();
        hls_video.destroy();
        hls_video = null;
      }
      _this.loadVideoFn(video, _this.hls_video[i].ref, i);
    },
    abnormal() {},
    hlsVideo(name) {
      var myframe = document.getElementById("otherPage"); //获取iframe
      myframe.contentWindow.postMessage({ name: name }, "*"); //childDomain是子页面的源（协议+主机+端口号）
    },

    loadVideoFn (url, ref, i) { //播放器
      var that = this;
      var ref = ref
      setTimeout(() =>{
        if (Hls.isSupported()) {
          that.hls_video[i].hls = new Hls();
          that.hls_video[i].hls.loadSource(url);
          that.hls_video[i].hls.attachMedia(that.$refs[ref][0]);
          that.hls_video[i].hls.on(Hls.Events.MANIFEST_PARSED, () => {
            that.hls_video[i].boolhls = true;
            that.hls_video[i].boolimg = false;
            that.$refs["hlsVideo" + i][0].play();
          });
          that.hls_video[i].hls.on(Hls.Events.ERROR, (event, data) => {
            if (data.type === "networkError") {
              // 监听出错事件
              console.log("加载失败");
              // that.hls_video[i].boolhls = false;
              // that.hls_video[i].boolimg = true;
            }
          });
        }
      },1000)
    },
    loadVideoFn2 (url) { //播放器
      setTimeout(() =>{
        if (Hls.isSupported()) {
          this.hls2 = new Hls();
          this.hls2.loadSource(url);
          this.hls2.attachMedia(this.$refs.hlsVideo222);
          this.hls2.on(Hls.Events.MANIFEST_PARSED, () => {
            console.log("加载成功");
            this.$refs.hlsVideo222.play();
          });

          this.hls2.on(Hls.Events.ERROR, (event, data) => {
            // console.log(event, data);
            // 监听出错事件
            console.log("加载失败");
          });
        }
      },1000)
    },
    //销毁hls 视频流
    destroyHls() {
      if(this.hls2){
        this.hls2.destroy();
        this.hls2 = null;
      }
      if(this.hls_video[0].hls){
        for(let i =0;i<6;i++){
          this.hls_video[i].hls.destroy();
          this.hls_video[i].hls = null;
        }
      }

      // if(id){
      //    if(this.hls_video2){
      //     for (let i = 0; i < this.hls_video2.length; i++) {
      //       var ref_video = this.hls_video2[i].ref;
      //       var hls_video = this.hls_video2[i].hls;
      //       if ((ref_video, this.$refs[ref_video][0] != undefined)) {
      //         this.$refs[ref_video][0].pause();
      //         hls_video.destroy();
      //         hls_video = null;
      //       }
      //     }
      //   }
      // }else{
      //    if(this.hls_video){
      //     for (let i = 0; i < this.hls_video.length; i++) {
      //       var ref_video = this.hls_video[i].ref;
      //       var hls_video = this.hls_video[i].hls;
      //       if ((ref_video, this.$refs[ref_video][0] != undefined)) {
      //         this.$refs[ref_video][0].pause();
      //         hls_video.destroy();
      //         hls_video = null;
      //       }
      //     }
      //   }
      // }

    },
    onSubmit() {
    },
  },
  destroyed(){
    this.destroyHls()
  }
};
</script>
<style lang="scss" scoped>
.el-input__inner{
 width:130% !important;
 margin-left:-20%;
}
.el-select__caret{
  margin-right:-20px
}

.scene {
  position: fixed;
  z-index: 2000;
  top: 0;
  width: 100%;
  height: 100%;
  -webkit-perspective: 600;
  perspective: 600;
  display: flex;
  align-items: center;
  justify-content: center;
}
.scene svg {
  width: 240px;
  height: 240px;
}

.dc-logo {
  position: fixed;
  right: 10px;
  bottom: 10px;
}

.dc-logo:hover svg {
  -webkit-transform-origin: 50% 50%;
  transform-origin: 50% 50%;
  -webkit-animation: arrow-spin 2.5s 0s cubic-bezier(0.165, 0.84, 0.44, 1)
    infinite;
  animation: arrow-spin 2.5s 0s cubic-bezier(0.165, 0.84, 0.44, 1) infinite;
}
.dc-logo:hover:hover:before {
  padding: 6px;
  font: 10px/1 Monaco, sans-serif;
  font-size: 10px;
  color: #00fffe;
  text-transform: uppercase;
  position: absolute;
  left: -70px;
  top: -30px;
  white-space: nowrap;
  z-index: 20px;
  box-shadow: 0px 0px 4px #222;
  background: rgba(0, 0, 0, 0.4);
}
.dc-logo:hover:hover:after {
  content: "Digital Craft";
  padding: 6px;
  font: 10px/1 Monaco, sans-serif;
  font-size: 10px;
  color: #6e6f71;
  text-transform: uppercase;
  position: absolute;
  right: 0;
  top: -30px;
  white-space: nowrap;
  z-index: 20px;
  box-shadow: 0px 0px 4px #222;
  background: rgba(0, 0, 0, 0.4);
  background-image: none;
}

@-webkit-keyframes arrow-spin {
  50% {
    -webkit-transform: rotateY(360deg);
    transform: rotateY(360deg);
  }
}

@keyframes arrow-spin {
  50% {
    -webkit-transform: rotateY(360deg);
    transform: rotateY(360deg);
  }
}

.monitor-setting1 {
  width: 35%;
  height: 45rem;
  position: fixed;
  left: 0;
  right: 0;
  top: 20rem;
  z-index: 15;
  margin: 0 auto;
}
.height_clone {
  height: 45rem;
}

.hlsVideo {
  width: 18.5rem;
  // width: 100%;
  border: none;
  margin: 0 auto;
  margin-left: 5%;
}
// .monitor-height {
//   height: 150px;
// }
//视频监控
.panel.monitor {
  margin-top: 2rem;
  z-index: 3;
  .panel-tit {
    position: relative;
  }
}
.monitor-list {
  padding: 1.2rem;
  height: calc(100vh - 51rem);
  overflow-y: scroll;
}
.monitor-list li {
  width: 50%;
  position: relative;
  display: block;
  float: left;
}
.monitor-list li img {
  width: 100%;

  display: block;
}

.monitor-tit {
  position: absolute;
  bottom: 0;
  width: 100%;
  left: 0;
  font-size: 1.2rem;
  line-height: 3rem;
  text-indent: 1rem;
  // display:none;

  background: rgba(0, 0, 0, 0.7);
}

.setting,
.close {
  position: absolute;
  width: 2rem;
  right: 1.5rem;
  top: 1.3rem;
  cursor: pointer;
  z-index: 1;
}
.close {
  width: 1.7rem;
  cursor: pointer;
}

.monitor-setting {
  position: absolute;
  left: 105%;
  width: 100%;
  top: 0;
  margin: 0 auto;
  text-align: center;
  .monitor-option {
    position: relative;
    padding: 2rem 1rem 1rem 2rem;
  }
}
::-webkit-scrollbar {
	    display: none
}
.el-popper{
  width:14.8%;
  overflow: hidden;
}
</style>
<style lang="scss">
.monitor-setting .el-form-item__label {
  font-size: 1.6rem;
  color: #fff;
  line-height: 3.4rem;
  text-align: left;
}
.monitor-setting .el-form-item__content {
  line-height: 3.4rem;
}
.monitor-setting .el-form-item {
  margin-bottom: 1.6rem;
}
.monitor-setting .el-input__inner {
  height: 3.4rem;
  line-height: 3.4rem;

  border-radius: 0;
  font-size: 1.4rem;
  background-color: rgba(0, 0, 0, 0);
  border: 1px solid #3486da;
}
.monitor-setting .el-input__icon {
  line-height: 2.4rem;
}
.monitor-setting .el-button {
  border-radius: 0;
  font-size: 1.6rem;
  padding: 1rem 2.3rem;
  margin-top: 3rem;
}
.monitor-setting .el-select .el-input .el-select__caret {
  color: #3486da;
  font-size: 1.6rem;
}
.monitor-setting .el-select:hover .el-input__inner {
  border: 1px solid #3486da;
  opacity: 0.7;
}

.main-select-el-tree .el-tree-node .is-current > .el-tree-node__content{font-weight: bold; color: #409eff;}
.main-select-el-tree .el-tree-node.is-current > .el-tree-node__content{font-weight: bold; color: #409eff;}
// .select1{
//   display:none;
// }
.selectWrap{
  width:90%;
}

.el-scrollbar{
  width:100%;
}
.el-scrollbar__bar.is-vertical { width: 0 !important }

.titleZise{
  position: absolute;
  top:0;
  left:0;
}
</style>
<style>
.el-scrollbar__wrap{
  width:100%;
  margin-bottom:-20px !important;
}
</style>
