<template>
  <div class="video_box">
    <!-- 摄像头 -->
    <div id="divPlugin" class="plugin"></div>
  </div>
</template>

<script>
  import {
    WebVideoCtrl
  } from "@/api/webVideoCtrl.js";
  export default {
    name: "carNvrVideo",
    components: {},
    data() {
      return {
        szInfo: "",
        rowList: {},
        hkvInfo: {},
        mySelectWnd: 0, //当前选中的窗口
        g_bPTZAuto: false,
        iProtocol: 1,
        loginLoading: false,
        startPlayLoading: false,
        bZeroChannel: false,
        iRtspPort: 0,
        index: 0,
        iWndowType: null,
        videoData: [],
        ua: navigator.userAgent.toLocaleLowerCase(),
      };
    },
    created() {

      // this.videoData = JSON.parse(this.$route.query.videoData);
      // if (this.videoData.length <= 1) {
      //   this.iWndowType = 1;
      // } else if (this.videoData.length > 1 && this.videoData.length <= 4) {
      //   this.iWndowType = 2;
      // }

       if (this.ua.match(/msie/) != null || this.ua.match(/trident/) != null) {
            this.browserType = "IE";
            this.videoData = JSON.parse(this.$route.query.videoData);
            if (this.videoData.length <= 1) {
              this.iWndowType = 1;
            } else if (this.videoData.length > 1 && this.videoData.length <= 4) {
              this.iWndowType = 2;
            }
          } else {
            this.$notify({
              title: "失败",
              message: "请在ie模式下查看摄像头",
              type: "error",
            });
          }

    },
    mounted() {
      this.videoChange();
    },
    destroyed() {
      this.clickStopRealPlay();
      this.onLogout();
    },
    methods: {
      videoChange() {
        setTimeout(() => {
          this.videoInitPlugin(); // 初始化video界面
        }, 300);
      },
      handleSelectionChange() {},
      submitForm() {},
      cancel() {},
      // 登录
      async onLogin() {
        var that = this;
        that.loginLoading = true;
        // 登录设备
        WebVideoCtrl.I_Login(
          that.hkvInfo.ip,
          that.iProtocol,
          that.hkvInfo.port,
          that.hkvInfo.username,
          that.hkvInfo.password, {

            async: false,
            success: (xmlDoc) => {
              //TODO 获取通道信息
              that.getChannelInfo();
              that.getDevicePort(that.hkvInfo.ip + "_" + that.hkvInfo.port);
              that.loginLoading = false;
              this.clickStartRealPlay();
            },
            error: function() {
              that.loginLoading = false;
              alert("当前摄像头配置不对或不在线，登录失败");
              window.opener = null;
              window.open('', '_self');
              window.close();
            },
          }
        );
      },
      // 退出
      onLogout() {
        this.videoData.forEach((element) => {
          var szDeviceIdentify = element.ip + "_" + element.port;
          var iRet = WebVideoCtrl.I_Logout(szDeviceIdentify);
          if (0 == iRet) {
            //   this.$message({
            //     showClose: true,
            //     message: "退出成功",
            //     type: "success",
            //   });
          } else {
            // this.$message({
            //   showClose: true,
            //   message: "退出失败",
            //   type: "error",
            // });
          }
        });
      },
      clickStartRealPlay() {
        console.log("开始预览", this.index);
        // 开始预览
        var that = this;
        that.startPlayLoading = true;
        var szDeviceIdentify = that.hkvInfo.ip + "_" + that.hkvInfo.port;
        debugger
        that.startRealPlay(szDeviceIdentify, this.index, that.hkvInfo.nvrPrechannel);
        that.startPlayLoading = false;
      },
      startRealPlay(szDeviceIdentify, iWndIndex, iChannelID) {
        var that = this;
        WebVideoCtrl.I_StartRealPlay(szDeviceIdentify, {
          iRtspPort: that.iRtspPort,
          iWndIndex: iWndIndex,
          iChannelID: iChannelID,
          bZeroChannel: that.bZeroChannel,
          iStreamType: 2, //码流类型，2为子码流
          success: function() {
            //   that.$notify({
            //     title: "成功",
            //     message: "开始预览通道" + iChannelID + "成功",
            //     type: "success",
            //   });
          },
          error(status, xmlDoc2) {
            console.log(xmlDoc2); //不能删除
            // that.$notify({
            //   title: "失败",
            //   message: "开始预览通道" + iChannelID + "失败",
            //   type: "error",
            // });
            if (status === 403) {
              console.log("szInfo 设备不支持Websocket取流！");
            } else {
              console.log("开始预览失败 ", status, xmlDoc2);
            }
          },
        });
      },
      videoInitPlugin() {
        this.$nextTick(() => {
          var iRet = WebVideoCtrl.I_CheckPluginInstall();
          if (iRet === -1) {
            // alert("您还未安装过插件，双击开发包目录里的WebComponentsKit.exe安装");
            this.myFunction();
            return;
          } else {
            if (this.ua.match(/msie/) != null || this.ua.match(/trident/) != null) {
              this.browserType = "IE";
              this.initPlugin();
            } else {
              this.$notify({
                title: "失败",
                message: "请在ie模式下查看摄像头",
                type: "error",
              });
            }
          }

        });
      },
      myFunction() {
        var r = confirm("您还未安装过插件，请下载后查看摄像!");
        if (r == true) {
          window.location.href = "/WebComponentsKit.exe";
        } else {}
      },
      initPlugin() {
        WebVideoCtrl.I_InitPlugin("100%", "100%", {
          bWndFull: true, //是否支持单窗口双击全屏，默I_CheckPluginInstall
          iWndowType: this.iWndowType, //默认展示几个摄像头1x1 2x2
          cbInitPluginComplete: function() {
            WebVideoCtrl.I_InsertOBJECTPlugin("divPlugin");
            // 检查插件是否最新
            if (WebVideoCtrl.I_CheckPluginVersion() === -1) {
              return;
            }
          },
        });
        for (var i = 0; i < this.videoData.length; i++) {

          this.hkvInfo = this.videoData[i];
          debugger
          this.index = i;
          this.onLogin();
        }
      },
      getDevicePort(szDeviceIdentify) {
        var oPort = WebVideoCtrl.I_GetDevicePort(szDeviceIdentify);
        this.iRtspPort = oPort.iRtspPort;
      },

      clickStopRealPlay: function() {
        for (var i = 0; i <= this.index; i++) {
          setTimeout(this.stopRealPlay(i), 1000);
        }
      },
      stopRealPlay: function(iWndIndex) {
        var that = this;
        WebVideoCtrl.I_Stop({
          iWndIndex: iWndIndex,
          success: function() {
            //   that.$notify({
            //     title: "成功",
            //     message: "停止预览窗口" + iWndIndex + "成功",
            //     type: "success",
            //   });
          },
          error: function() {
            // that.$notify({
            //   title: "失败",
            //   message: "停止预览窗口" + iWndIndex + "失败",
            //   type: "error",
            // });
          },
        });
      },
      // 获取通道，实际上可以根据自己的项目，获取数字通道，模拟通道，零通道中的一个或多个，不用全部获取（提高效率）
      getChannelInfo: function() {
        var that = this;
        var szDeviceIdentify = this.hkvInfo.ip + ":" + this.hkvInfo.port;
        // 数字通道
        that.hkvInfo.channels = [];
        WebVideoCtrl.I_GetDigitalChannelInfo(szDeviceIdentify, {
          async: false,
          mysuccess: function(xmlStr) {
            console.log("mysuccess I_GetDigitalChannelInfo: ", xmlStr);
            var jsonObj = that.$x2js.xml2js(xmlStr);
            var list = jsonObj.InputProxyChannelStatusList.InputProxyChannelStatus;
            for (var x = 0; x < list.length; x++) {
              that.hkvInfo.channels.push(list[x].id);
            }
          },
          success: function(xmlDoc) {},
          error: function(status, xmlDoc) {
            console.log("获取数字通道失败");
          },
        });
        // 模拟通道
        WebVideoCtrl.I_GetAnalogChannelInfo(szDeviceIdentify, {
          async: false,
          mysuccess: function(xmlStr) {
            var jsonObj = that.$x2js.xml2js(xmlStr);
            console.log("模拟通道mysuccess", xmlStr);
            var id = jsonObj.VideoInputChannelList.VideoInputChannel.id;
            that.hkvInfo.channels.push(id);
          },
          success: function(xmlStr) {
            console.log("模拟通道success", xmlStr);
          },
          error: function(status, xmlDoc) {
            console.log("模拟通道error", xmlDoc);
          },
        });
        // TODO 零通道
      },
    },
  };
</script>
<style scoped>
  .video_box {
    width: 100%;
    height: 100%;
  }

  .plugin {
    width: 100%;
    height: 100%;
  }

  .my-tag {
    margin-left: 3px;
  }

  .my-group-btn {
    margin-top: 5px;
  }
</style>
