import config from '@/config/index';

let websocket = null; //全局WebSocket对象
let lockReconnect = false; // 网络断开重连
let wsCreateHandler = null; // 创建连接

export function createSocket(fn) {
    try {
      if ('WebSocket' in window)
        websocket = new window.WebSocket(config.base.ws);
      else if ('MozWebSocket' in window)
        websocket = new window.MozWebSocket(config.base.ws);
      else reconnect();
    } catch {
      reconnect();
      return;
    }

    websocket.onmessage = function (data) {
      fn && fn({
        ws: websocket,
        data: JSON.parse(data.data)
      })
    };

    websocket.onopen = function (event) {
      // websocket.send("连接成功");
      console.log('服务已连接', event);
    };
    websocket.onclose = function (event) {
      console.log('服务连接关闭', event);
    };
    websocket.onerror = function (event) {
      console.log(event, '连接出错');
    };
}

/**
 *  异常处理
 * 处理可以检测到的异常，并尝试重新连接
 */
function reconnect() {
  if (lockReconnect) {
    return;
  }
  console.log('reconnect');
  lockReconnect = true;
  // 没链接上会一直连接，设置延迟，避免过多请求
  wsCreateHandler && clearTimeout(wsCreateHandler);
  wsCreateHandler = setTimeout(function () {
    console.log('-----websoket异常-------');
    createSocket();
    lockReconnect = false;
  }, 1000);
}
