<template>

  <!-- 绑定父组件class：videoWindow -->
  <div
    :id="playWndId"
    ref="video-preview">
  </div>

</template>

<script>
/* eslint-disable */

export default {
  name: 'video-preview',
  data() {
    return {
      width: 0,
      height: 0,
      secret: '',
      oWebControl: null,
      initCount: 0,
      appkey: import.meta.env.VITE_APP_HAIKANG_APPKEY,
      ip: import.meta.env.VITE_APP_HAIKANG_IP,
      port: parseInt(import.meta.env.VITE_APP_HAIKANG_PORT),
      playMode: 1,
      pubKey: '',
      isInit: false
    }
  },
  props: {
    layout: {
      type: String,
      default: () => '1x1'
    },
    cameraIndexCode: {},
    timeOut: {
      type: Number,
      default: () => 500
    },
    videoWindowClassName: {
      type: String,
      default: "videoWindow",
      required: false
    },
    playWndId: {
      type: String,
      default: "playWnd",
      required: false
    }
  },
  mounted() {
    var that = this
    this.$nextTick(function() {
      that.windowChange()
      setTimeout(() => {
        that.initPlugin()
      }, that.timeOut)
      window.addEventListener('resize', function() {
        that.onResize()
      })
    })
  },
  destroyed() {
    this.uninit()
  },
  methods: {
    onResize(change=true){
      let that = this
      if (that.oWebControl) {
        if(change){
          that.windowChange()
        }
        that.oWebControl.JS_Resize(that.width, that.height)
      }
    },
    wait (fn, timeout, tick) {
      timeout = timeout || 5000;
      tick = tick || 250;
      var timeoutTimer = null;
      var execTimer = null;

      return new Promise(function(resolve, reject) {

        timeoutTimer = setTimeout(function() {
          clearTimeout(execTimer);
          reject(new Error('polling fail because timeout'));
        }, timeout);

        tickHandler(fn);

        function tickHandler(fn) {
          var ret = fn();
          if (!ret) {
            execTimer = setTimeout(function() {
              tickHandler(fn);
            }, tick)
          } else {
            clearTimeout(timeoutTimer);
            resolve();
          }
        }
      });
    },
    // 初始化plugin
    initPlugin() {
      let that = this
      this.oWebControl = new WebControl({
        szPluginContainer: this.playWndId,
        iServicePortStart: 15900,
        iServicePortEnd: 15909,
        szClassId: '23BF3B0A-2C56-4D97-9C03-0CB103AA8F11', // 用于IE10使用ActiveX的clsid
        cbConnectSuccess: function() {
          that.setCallbacks();
          //实例创建成功后需要启动服务
          that.oWebControl
            .JS_StartService("window", {
              dllPath: "./VideoPluginConnect.dll"
            })
            .then(
              function() {
                that.oWebControl
                  .JS_CreateWnd(that.playWndId, that.width, that.height)
                  .then(function() {
                    //JS_CreateWnd创建视频播放窗口，宽高可设定
                    that.init(); //创建播放实例成功后初始化
                  });
              },
              function() {}
            );
        },
        cbConnectError: function() {
          that.oWebControl = null;
          $("#" + that.playWndId).html("插件未启动，正在尝试启动，请稍候...");
          WebControl.JS_WakeUp("VideoWebPlugin://"); //程序未启动时执行error函数，采用wakeup来启动程序
          initCount++;
          if (initCount < 3) {
            setTimeout(function() {
              that.initPlugin();
            }, 2000);
          } else {
            $("#" + that.playWndId).html("插件启动失败，请检查插件是否安装！");
          }
        },
        cbConnectClose: function(bNormalClose) {
          that.oWebControl = null
        }
      })
    },
    init() {
      
      let that = this;
      that.getPubKey(function() {
        ////////////////////////////////// 请自行修改以下变量值	////////////////////////////////////
        var snapDir = "d:\\SnapDir"; //抓图存储路径
        var videoDir = "d:\\VideoDir"; //紧急录像或录像剪辑存储路径
        var layout = "1x1"; //playMode指定模式的布局
        var enableHTTPS = 1; //是否启用HTTPS协议与综合安防管理平台交互，是为1，否为0
        var encryptedFields = "secret"; //加密字段，默认加密领域为secret
        var showToolbar = 1; //是否显示工具栏，0-不显示，非0-显示
        var showSmart = 1; //是否显示智能信息（如配置移动侦测后画面上的线框），0-不显示，非0-显示
        var buttonIDs = "0,16,256,257,258,259,260,512,515,516,517,768,769"; //自定义工具条按钮
        ////////////////////////////////// 请自行修改以上变量值	////////////////////////////////////
        that.secret = that.setEncrypt(import.meta.env.VITE_APP_HAIKANG_SECRET);
        that.oWebControl
          .JS_RequestInterface({
            funcName: "init",
            argument: JSON.stringify({
              appkey: that.appkey, //API网关提供的appkey
              secret: that.secret, //API网关提供的secret
              ip: that.ip, //API网关IP地址
              playMode: that.playMode, //播放模式（决定显示预览还是回放界面）
              port: that.port, //端口
              snapDir: snapDir, //抓图存储路径
              videoDir: videoDir, //紧急录像或录像剪辑存储路径
              layout: layout, //布局
              enableHTTPS: enableHTTPS, //是否启用HTTPS协议
              encryptedFields: encryptedFields, //加密字段
              showToolbar: showToolbar, //是否显示工具栏
              showSmart: showSmart, //是否显示智能信息
              buttonIDs: buttonIDs //自定义工具条按钮
            })
          })
          .then(function(oData) {
            that.oWebControl.JS_Resize(that.width, that.height); // 初始化后resize一次，规避firefox下首次显示窗口后插件窗口未与DIV窗口重合问题
          });
      });
    },
    // 获取公钥
    getPubKey(callback) {
      var that = this
      this.oWebControl.JS_RequestInterface({
        funcName: 'getRSAPubKey',
        argument: JSON.stringify({
          keyLength: 1024
        })
      }).then(function(oData) {
        if (oData.responseMsg.data) {
          that.pubKey = oData.responseMsg.data
          that.isInit = true
          callback()
        }
      })
    },
    // 设置窗口控制回调
    setCallbacks() {
      let that = this;
      that.oWebControl.JS_SetWindowControlCallback({
        cbIntegrationCallBack: function (oData) {
                if(oData.responseMsg.msg.result === 816){
                  that.$emit('close')
                }
        }
      });
    },
    // RSA加密
    setEncrypt(value) {
      let that = this;
      var encrypt = new JSEncrypt();
      encrypt.setPublicKey(that.pubKey);
      return encrypt.encrypt(value);
    },
    ready() {
      let that = this;
      return new Promise((resolve, reject) => {
        this.wait(
          function() {
            return that.isInit;
          },
          6000 + that.timeOut || 500,
          100
        )
          .then(function() {
            resolve();
          })
          .catch(function(err) {
            // that.$Message.info({
            //   content: "视频控件加载超时，请检查:" + err,
            //   duration: 3
            // });
            // reject("视频控件加载超时，请检查:" + err);
          });
      });
    },

    playBack(codes, startTime, endTime) {
      let that = this;
      const startTimeStamp = this.timrStr2Stamp(startTime) + "";
      const endTimeStamp = this.timrStr2Stamp(endTime) + "";
      var recordLocation = 0; //录像存储位置：0-中心存储，1-设备存储
      var transMode = 1; //传输协议：0-UDP，1-TCP
      var gpuMode = 0; //是否启用GPU硬解，0-不启用，1-启用
      var wndId = -1; //播放窗口序号（在2x2以上布局下可指定播放窗口）
      that.oWebControl
        .JS_RequestInterface({
          funcName: "startPlayback",
          argument: JSON.stringify({
            cameraIndexCode: codes, //监控点编号
            startTimeStamp: startTimeStamp, //录像查询开始时间戳，单位：秒
            endTimeStamp: endTimeStamp, //录像结束开始时间戳，单位：秒
            recordLocation: recordLocation, //录像存储类型：0-中心存储，1-设备存储
            transMode: transMode, //传输协议：0-UDP，1-TCP
            gpuMode: gpuMode, //是否启用GPU硬解，0-不启用，1-启用
            wndId: wndId //可指定播放窗口
          })
        })
        .then(res => {
          console.log("回放的参数", res);
        });
    },
    timrStr2Stamp(str) {
      let date = new Date(str);
      let time = date.getTime();
      return time / 1000;
    },
    stopPlayBack() {
      this.oWebControl.JS_RequestInterface({
        funcName: "stopAllPlayback"
      });
    },
    uninit() {
      console.log(999);
      
      let that = this;
      if (that.oWebControl != null) {
        that.oWebControl.JS_RequestInterface({
          funcName: "stopAllPreview"
        });
        that.oWebControl.JS_HideWnd(); // 先让窗口隐藏，规避可能的插件窗口滞后于浏览器消失问题
        that.oWebControl.JS_Disconnect().then(
          function() {
            // 断开与插件服务连接成功
          },
          function() {
            // 断开与插件服务连接失败
            console.log("oWebControl close error");
          }
        );
        that.oWebControl = null;
      }
    },
    windowChange() {
      
      //列表选项在下方
      this.width = document.getElementsByClassName(
        this.videoWindowClassName
      )[0].scrollWidth;
      var btnHeight = 0;
      if (document.getElementsByClassName("playBtn").length > 0) {
        btnHeight = document.getElementsByClassName("playBtn")[0].clientHeight;
        this.height =
          document.getElementsByClassName(this.videoWindowClassName)[0]
            .scrollHeight -
          btnHeight -
          10;
      } else {
        this.height = document.getElementsByClassName(
          this.videoWindowClassName
        )[0].scrollHeight;
      }
      if (document.getElementById(this.playWndId)) {
        document.getElementById(this.playWndId).style.height = this.height + "px";
        document.getElementById(this.playWndId).style.width = this.width + "px";
      }
    }
  }
}
</script>

<style scoped>

</style>
