let sockets = []

// readyState: 0-正在连接 1-已经连接 2-连接正在关闭 3-已关闭或没连接成功
function onOpen(e, data) {
  console.log('open && send ...', data.name)
  for (let it of sockets) {
    if (it.name === data.name && it.ws.readyState === 1) {
      it.ws.send(data.sendData)
    }
  }

}

function onError(e, data) {
  console.log('ws error...', e, data)
}

function onClose(e, data) {
  console.log('ws close...', e, data)
}

export function initWs(data) {
  console.log('开始连接........', data)
  if (typeof WebSocket === undefined) {
    console.error('您的浏览器不支持socket')
  } else {
    console.log('xinlianjie........', ReconnectingWebSocket, data.url)
    let currentSocket = new ReconnectingWebSocket(data.url)
    console.log('ws实例', currentSocket)
    // 监听socket连接open
    currentSocket.onopen = (e) => onOpen(e, data)
    // 监听socket错误信息
    currentSocket.onerror = (e) => onError(e, data)
    // 断开连接
    currentSocket.onclose = (e) => onClose(e, data)
    sockets.push({
      name: data.name, ws: currentSocket,
    })
    return {
      name: data.name, url: data.url, status: data.status, ws: currentSocket,
    }
  }
}
