/**
 * @websocket
 * @param url
 * @param onOpen
 * @param onMessage
 * @param onClose
 * @param onError
 * @param heart
 * @param isReconnect
 * @returns {WebSocket}
 * @private
 */
const _webSocket = ({ url, onOpen, onMessage, onClose, onError, heart, isReconnect }) => {
  if (!window.WebSocket) {
    throw new Error("您的浏览器不支持WebSocket");
  }
  let isConnected = false; // 设定已链接webSocket标记
  let ws = null; // websocket对象
  let heartTimer = null;
  let _heart = {
    timer: 3000,
    message: "",
  };
  if (heart) {
    if (typeof heart === "object" && Object.keys(heart).length > 0) {
      _heart = { ..._heart, ...heart };
    }
  } else {
    _heart = null;
  }
  // 创建并链接webSocket
  const connect = () => {
    // 如果未链接webSocket，则创建一个新的webSocket
    if (!isConnected) {
      const wsUrl = `${process.env.VUE_APP_API_WS}${url}`;
      ws = new WebSocket(wsUrl);
      isConnected = true;
    }
  };
  // 向后台发送心跳消息
  const heartCheck = () => {
    ws.send(JSON.stringify(_heart.message));
  };
  // 初始化事件回调函数
  const initEventHandle = () => {
    ws.addEventListener("open", (e) => {
      if (_heart) {
        heartCheck();
      }
      // 如果传入了函数，执行onOpen
      if (!onOpen) {
        return false;
      } else {
        onOpen(e, ws);
      }
    });
    ws.addEventListener("message", (e) => {
      if (!e) {
        console.log("get nothing from service");
        return false;
      } else {
        // 如果获取到后台消息，则timer毫秒后再次发起心跳请求给后台，检测是否断连
        if (_heart) {
          heartTimer = setTimeout(() => {
            if (isConnected) {
              heartCheck();
            }
          }, _heart.timer);
        }
      }
      // 如果传入了函数，执行onMessage
      if (!onMessage) {
        return false;
      } else {
        onMessage(e);
      }
    });
    ws.addEventListener("close", (e) => {
      if (heartTimer) {
        clearTimeout(heartTimer);
        heartTimer = null;
      }
      // 如果传入了函数，执行onClose
      if (!onClose) {
        return false;
      } else {
        onClose(e);
      }
    });
    ws.addEventListener("error", (e) => {
      if (!onError) {
        return false;
      } else {
        onError(e);
      }
      if (isReconnect) {
        // 如果断开立即重连标志为true
        // 重新链接webSocket
        connect();
      } else {
        if (heartTimer) {
          clearTimeout(heartTimer);
          heartTimer = null;
        }
      }
    });
  };
  // 1.创建并链接webSocket
  connect();
  // 2.初始化事件回调函数
  initEventHandle();
  // 3.返回
  return ws;
};

export default _webSocket;

export { _webSocket };
