import { getConfig as m } from "@das-fed/utils/config";
import { getToken as f } from "@das-fed/utils/common-info";
import { objectToUrlparams as d } from "@das-fed/utils/common-tools";
const c = m(), h = () => {
  let s = "";
  return c.baseURL ? s = c.baseURL : s = location.origin, s.replace("https://", "wss://").replace("http://", "ws://") || "";
}, w = (s, t = {}) => {
  const e = d(t);
  return e ? h() + s + `?${e}` : h() + s;
}, p = (s, t) => Math.floor(Math.random() * (t - s + 1)) + s;
class R {
  constructor({
    url: t,
    params: e = {},
    opened: r,
    close: n,
    error: i,
    message: o,
    ifReconnect: a,
    reconnectNum: l,
    reconnectWhenClose: u
  }) {
    if (this.$ws = null, this.url = "", this.params = {}, this.lockReturn = !1, this.startTime = 0, this.heartbeatInterval = null, this.ifReconnect = !0, this.reconnectId = null, this.reconnectNum = 3, this.reconnectWhenClose = !1, this.currentReconnectNum = 0, this.$ws = null, this.startTime = 0, this.heartbeatInterval = null, this.ifReconnect = a ?? !0, this.reconnectNum = l ?? 3, this.reconnectWhenClose = u ?? !1, this.lockReturn = !1, this.currentReconnectNum = 0, this.reconnectId = null, this.params = { ...e, access_token: f() }, t)
      this.url = t;
    else
      throw new Error("url is required");
    r && (this.opened = r), n && (this.close = n), i && (this.error = i), o && (this.afterMsg = o), this.initWebSocket();
  }
  initWebSocket() {
    if (typeof WebSocket > "u") throw new Error("您的浏览器不支持websocket");
    const t = w(this.url, this.params);
    this.$ws = new WebSocket(t), this.$ws.onopen = () => {
      this.open();
    }, this.$ws.onclose = (e) => {
      this.close(e);
    }, this.$ws.onmessage = (e) => {
      this.message(e);
    }, this.$ws.onerror = (e) => {
      this.error(e);
    };
  }
  open() {
    this.currentReconnectNum = 0, this.startTime = (/* @__PURE__ */ new Date()).getTime(), this.opened(this.$ws), this.startHeartbeat();
  }
  opened(t) {
  }
  close(t) {
    this.$ws.readyState === WebSocket.CLOSED && ((/* @__PURE__ */ new Date()).getTime(), this.reconnectWhenClose && this.reconnect(), clearInterval(this.heartbeatInterval));
  }
  message(t) {
    const e = typeof t.data == "object" ? t.data : JSON.parse(t.data);
    this.afterMsg(e);
  }
  afterMsg(t) {
  }
  error(t) {
    return this.ifReconnect && this.reconnect(), t;
  }
  /** websocket重连 */
  reconnect() {
    this.lockReturn || (this.lockReturn = !0, this.currentReconnectNum++, !(this.currentReconnectNum > this.reconnectNum) && (this.reconnectId && clearTimeout(this.reconnectId), this.reconnectId = setTimeout(() => {
      this.initWebSocket(), this.lockReturn = !1;
    }, 3e3)));
  }
  /** 发送消息给服务器 */
  send(t) {
    var e;
    ((e = this.$ws) == null ? void 0 : e.readyState) === WebSocket.OPEN && this.$ws.send(t);
  }
  // 启动心跳检测==>30s-5分钟内随机发一次心跳保持会话（时间区间内随机是为了降低突增流量的概率）
  startHeartbeat() {
    this.heartbeatInterval = setInterval(() => {
      this.send("");
    }, p(3e4, 3e5));
  }
  /** 断开连接 */
  disconnect() {
    this.$ws.close();
  }
}
export {
  R as socketService
};
