import { getConfig as m } from "@das-fed/utils/config";
import { getToken as f } from "@das-fed/utils/common-info";
import { objectToUrlparams as w } 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://") || "";
}, b = (s, e = {}) => {
  const t = w(e);
  return t ? h() + s + `?${t}` : h() + s;
}, g = (s, e) => Math.floor(Math.random() * (e - s + 1)) + s;
class R {
  constructor({
    url: e,
    params: t = {},
    opened: n,
    close: r,
    error: o,
    message: i,
    ifReconnect: l,
    reconnectNum: a,
    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 = l ?? !0, this.reconnectNum = a ?? 3, this.reconnectWhenClose = u ?? !1, this.lockReturn = !1, this.currentReconnectNum = 0, this.reconnectId = null, this.params = { ...t, access_token: f() }, e)
      this.url = e;
    else
      throw new Error("url is required");
    n && (this.opened = n), r && (this.close = r), o && (this.error = o), i && (this.afterMsg = i), this.initWebSocket();
  }
  initWebSocket() {
    if (typeof WebSocket > "u") throw new Error("您的浏览器不支持websocket");
    const e = b(this.url, this.params);
    this.$ws = new WebSocket(e), this.$ws.onopen = () => {
      this.open();
    }, this.$ws.onclose = (t) => {
      this.close(t);
    }, this.$ws.onmessage = (t) => {
      this.message(t);
    }, this.$ws.onerror = (t) => {
      this.error(t);
    };
  }
  open() {
    this.currentReconnectNum = 0, this.startTime = (/* @__PURE__ */ new Date()).getTime(), this.opened(this.$ws), this.startHeartbeat(), console.log(this.url + " =>websocket连接成功,可以开始通讯");
  }
  opened(e) {
    console.log(this.url + " =>websocket连接已打开:", e);
  }
  close(e) {
    if (this.$ws.readyState === WebSocket.CLOSED) {
      const t = (/* @__PURE__ */ new Date()).getTime();
      this.reconnectWhenClose && this.reconnect(), clearInterval(this.heartbeatInterval), console.log(`${this.url}=>WebSocket连接已经关闭,连接总时长: ${t - this.startTime}ms`);
    }
  }
  message(e) {
    const t = typeof e.data == "object" ? e.data : JSON.parse(e.data);
    this.afterMsg(t);
  }
  afterMsg(e) {
    console.log(this.url + " =>接收到websocket的消息:", e);
  }
  error(e) {
    return this.ifReconnect && this.reconnect(), e;
  }
  /** 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(e) {
    var t;
    if (((t = this.$ws) == null ? void 0 : t.readyState) !== WebSocket.OPEN) {
      console.log(this.url + "=>websocket连接未建立，还不能发送消息");
      return;
    }
    this.$ws.send(e);
  }
  // 启动心跳检测==>30s-5分钟内随机发一次心跳保持会话（时间区间内随机是为了降低突增流量的概率）
  startHeartbeat() {
    this.heartbeatInterval = setInterval(() => {
      const e = "";
      this.send(e), console.log(this.url + "=>心跳检测发送消息:", e);
    }, g(3e4, 3e5));
  }
  /** 断开连接 */
  disconnect() {
    this.$ws.close(), console.log(this.url + " =>主动断开websocket连接");
  }
}
export {
  R as socketService
};
