<template>
  <section class="hikversionMonitor">
    <div id="monitorIns">
      <el-link v-if="needSetupPlugin" href="https://cdn.cunwuyun.cn/wsr/lib/VideoWebPlugin.exe" type="primary">
        请检查是否安装视频插件,如果没有请点击下载视频插件并安装
      </el-link>
      <div v-else>视频插件未启动，正在尝试启动，请稍候...</div>
    </div>
  </section>
</template>

<script>
export default {
  name: "hikversionMonitor",
  props: {
    src: {default: ""},
    list: {default: () => []}
  },
  data() {
    return {
      monitorIns: null,
      initCount: 0
    }
  },
  computed: {
    needSetupPlugin() {
      return this.initCount >= 3
    }
  },
  methods: {
    getMonitorWidth() {
      let {width} = document.querySelector("#monitorIns")?.getBoundingClientRect()
      return width
    },
    getMonitorHeight() {
      let {height} = document.querySelector("#monitorIns")?.getBoundingClientRect()
      return height
    },
    initSDK() {
      this.$nextTick(() => {
        let width = this.getMonitorWidth(), height = this.getMonitorHeight()
        if (width) {
          this.monitorIns = new WebControl({
            szPluginContainer: "monitorIns",                       // 指定容器id
            iServicePortStart: 15900,                           // 指定起止端口号，建议使用该值
            iServicePortEnd: 15909,
            szClassId: "23BF3B0A-2C56-4D97-9C03-0CB103AA8F11",   // 用于IE10使用ActiveX的clsid
            cbConnectSuccess: () => {                     // 创建WebControl实例成功
              this.monitorIns.JS_StartService("window", {         // WebControl实例创建成功后需要启动服务
                dllPath: "./VideoPluginConnect.dll"         // 值"./VideoPluginConnect.dll"写死
              }).then(() => {                           // 启动插件服务成功
                this.monitorIns.JS_CreateWnd("monitorIns", width, height).then(() => { //JS_CreateWnd创建视频播放窗口，宽高可设定
                  this.monitorIns.JS_RequestInterface({
                    funcName: "getRSAPubKey",
                    argument: JSON.stringify({
                      keyLength: 1024
                    })
                  }).then((oData) => {
                    if (oData.responseMsg.data) {
                      let encrypt = new JSEncrypt();
                      encrypt.setPublicKey(oData.responseMsg.data);
                      let secret = encrypt.encrypt("JSqHo9JUgPLQxfCIjsmQ");
                      this.monitorIns.JS_RequestInterface({
                        funcName: "init",
                        argument: JSON.stringify({
                          appkey: "23335895",                                                    //API网关提供的appkey
                          secret,                                                                //API网关提供的secret
                          ip: "124.128.246.74",                                                  //API网关IP地址
                          playMode: 0,                                                           //初始播放模式：0-预览，1-回放
                          port: 1443,                                                            //端口
                          snapDir: ".",                                                          //抓图存储路径
                          videoDir: ".",                                                         //紧急录像或录像剪辑存储路径
                          layout: "1x1",                                                         //布局
                          enableHTTPS: 1,                                                        //是否启用HTTPS协议
                          encryptedFields: "secret",                                             //加密字段
                          showToolbar: 1,                                                        //是否显示工具栏
                          showSmart: 1,                                                          //是否显示智能信息
                          buttonIDs: "0,16,256,257,258,259,260,512,513,514,515,516,517,768,769"  //自定义工具条按钮
                        })
                      }).then(() => {
                        this.monitorIns.JS_Resize(width, height);  // 初始化后resize一次，规避firefox下首次显示窗口后插件窗口未与DIV窗口重合问题
                        this.startPreview()
                      })
                    }
                  })
                });
              }, (...args) => {
                // 启动插件服务失败
                console.log(args)
              })
            },
            cbConnectError: () => {
              this.monitorIns = null
              WebControl.JS_WakeUp("VideoWebPlugin://");
              this.initCount++
              if (!this.needSetupPlugin) {
                setTimeout(() => {
                  this.initSDK()
                }, 3000)
              }
            }
          })
        }
      })
    },
    startPreview() {
      const layout = len =>
          len <= 1 ? '1x1' :
              len == 2 ? '1x2' :
                  len == 3 ? '1+2' :
                      len == 4 ? '2x2' :
                          len < 6 ? '1+5' :
                              len == 7 ? '3+4' :
                                  len == 8 ? '1+7' :
                                      len == 9 ? '3x3' :
                                          len == 10 ? '1+9' :
                                              len <= 16 ? '4x4' : '4x6'
      let list = this.src?.split(",")
      this.monitorIns?.JS_RequestInterface({
        funcName: "setLayout",
        argument: JSON.stringify({layout: layout(list.length)})
      }).then(() => {
        this.monitorIns?.JS_RequestInterface({
          funcName: "startMultiPreviewByCameraIndexCode",
          argument: JSON.stringify({
            list: list.map((cameraIndexCode, i) => ({
              cameraIndexCode,       //监控点编号
              streamMode: 0,                          //主子码流标识
              transMode: 1,                           //传输协议
              gpuMode: 0,                             //是否开启GPU硬解
              wndId: i + 1                              //可指定播放窗口
            }))
          })
        })
      })

    },
  },
  watch: {
    src(v) {
      v && this.monitorIns?.JS_RequestInterface({funcName: "stopAllPreview"}).then(() => this.startPreview())
    }
  },
  mounted() {
    this.$injectLib("https://cdn.cunwuyun.cn/wsr/lib/jsencrypt.min.js")
    this.$injectLib("https://cdn.cunwuyun.cn/wsr/lib/jsWebControl-1.0.0.min.js", () => {
      this.initSDK()
    })
  },
  beforeDestroy() {
    this.monitorIns?.JS_DestroyWnd()
  }
}
</script>

<style lang="scss" scoped>
.hikversionMonitor {
  color: #fff;
  height: 100%;

  #monitorIns {
    height: 100%;
    background: #000;
    display: flex;
    justify-content: center;
    align-items: center;
  }
}
</style>
