let lockReconnect = false
let timer = false
/**
 * 人员socket连接成功+
 */
function onOpen(data) {
  console.log('socket--连接成功!')
  // data.callBack(1111);
}

// 接收回调信息
function onMessage(msg, data) {
  if (msg.data) {
    // console.log(msg.data)
    try {
      const result = JSON.parse(msg.data)
      data.callBack(result)
    } catch (e) {}
  }
}

/**
 * 连接错误
 */
function onError(e, data) {
  console.log('连接错误')
  reconnect(data)
}

function onClose(e, data) {
  console.log('websocket 断开: ' + e.code + ' ' + e.reason + ' ' + e.wasClean)
  console.log('websocket 断开: ' + e)
  if (timer) {
    clearTimeout(timer)
  }
}

function reconnect(data) {
  if (lockReconnect) {
    return
  }
  lockReconnect = true
  timer = setTimeout(() => {
    init(data)
    lockReconnect = false
  }, 10000)
}

export function init(data) {
  if (typeof WebSocket === undefined) {
    console.error('您的浏览器不支持socket')
  } else {
    let socket = new WebSocket(data.url)
    // 监听socket连接
    socket.onopen = onOpen
    // 监听socket错误信息
    socket.onerror = (e) => onError(e, data)
    // 监听socket消息
    socket.onmessage = (msg) => onMessage(msg, data)
    // 断开连接
    socket.onclose = (e) => onClose(e, data)
    // return socket;
    return socket
  }
  return null
}

// export {
//     socket
// }
