import { Message } from 'element-ui';
import projectConfig from '@/core/config';
import { getToken } from '@/utils';
class SocketService {
  constructor (url, websocketonmessage = () => {}, successful = () => {}, timeOut) {
    // eslint-disable-next-line no-unused-vars
    this.tokrn = getToken()
    this.timeOut = timeOut || 2000
    this.url = projectConfig.wsUrl + url
    this.ws = null;
    this.timeObj = null;
    this.reconnectNumber = 0
    this.websocketonmessage = websocketonmessage
    this.successful = successful
  }
  // 初始化weosocket
  async initWebSocket () {
    this.ws = await new WebSocket(this.url);
    this.ws.onopen = await this.websocketonopen.bind(this);
    this.ws.onerror = await this.websocketonerror.bind(this);
    this.ws.onmessage = await this.websocketonmessage;
    this.ws.onclose = await this.websocketclose.bind(this);
  }
  // 心跳
  startHeartbeat () {
    clearInterval(this.timeObj)
    this.timeObj = null
    this.timeObj = setInterval(() => {
      this.websocketsend('link')
    }, this.timeOut);
  }
  // 重连
  reconnect () {
    setTimeout(() => {
      Message('尝试重连')
      this.reconnectNumber++
      // 建立新连接
      if (this.reconnectNumber >= 5) return
      this.initWebSocket();
    }, 5000);
  }
  websocketonopen () { // 连接成功
    // this.startHeartbeat()
    Message({
      message: 'WebSocket连接成功',
      type: 'success'
    })
    this.successful()
  }
  websocketonerror (e) { // 错误
    this.reconnect()
    Message({
      message: 'WebSocket连接发生错误',
      type: 'error'
    })
  }
  // websocketonmessage (e) { // 数据接收
  //   this.redata = e;
  // }
  websocketsend (agentData) { // 数据发送
    this.ws.send(agentData);
  }
  websocketclose (e) { // 关闭
    // Message('connection closed (' + e.code + ')')
  }
}

export { SocketService }
