import ElementUI from 'element-ui';
let lockReconnect = false;
let socket;
let timer;
let count = 10;
let wsUrl;
function initWebSocket(wsUri) {
  wsUrl = wsUri;
  //这里面的this都指向vue
  socket = new WebSocket(wsUri);
  socket.onerror = webSocketOnError;
  socket.onclose = closeWebsocket;
  socket.onopen = openWebsocket;
}

//错误事件监听
function webSocketOnError(e) {
  ElementUI.Notification({
    title: '',
    message: "WebSocket连接发生错误" + e,
    type: 'error',
    duration: 0,
  });
}

// websocket关闭监听事件
function closeWebsocket() {
  reconnect();
}

//开始事件
function openWebsocket() {
  if(timer){
    clearInterval(timer);
  }
}

// 关闭 websocket
function close() {
  lockReconnect = true;
  socket.close();
}

//消息发送
function webSocketSend(agentData) {
  socket.send(agentData);
}

//重连机制
function reconnect(){
  if(lockReconnect){
    return
  }
  lockReconnect = true;
  //没连接上会一直重连，设置延迟避免请求过多
  timer = setTimeout(function(){
    count --;
    initWebSocket(wsUrl);
    this.lockReconnect = false
    if(count == 0){
      clearInterval(timer);
    }
  },2000)
}

//监听事件添加
function addEvent(type,event){
  if(type == "onopen"){
    socket.onopen = event;
  }else if(type == "onmessage"){
    socket.onmessage = event;
  }else if(type == "onclose"){
    socket.onclose = event;
  }else if(type == "onerror"){
    socket.onerror = event;
  }else{
    socket.addEventListener(type,event);
  }
}

export default {
  initWebSocket, close, addEvent
}
