import modal from "./modal";

// WebSocketService.js
class WebSocketService {
  constructor() {
    this.ws = null;
    // // 记录重连次数
    // this.reconnectCount = 0;
    // // 最大重连次数
    // this.maxReconnectAttempts = 2;
    this.reconnectInterval = 3000;
    this.eventListeners = {};
    this.listeners = {};
  }

  connect(url) {
    this.ws = new WebSocket(url);

    this.ws.onopen = () => {
      console.log("WebSocket connected");
      this.emit("open");
    };

    this.ws.onmessage = (event) => {
      const message = JSON.parse(event.data);
      if (message.type === "info") {
        modal.msgSuccess(message.data);
        return;
      }
      this.emit("message", message);
    };

    this.ws.onerror = (error) => {
      // console.error("WebSocket error:", error);
      this.emit("error", error);
    };

    // this.ws.onclose = () => {
    //   console.log("WebSocket closed");
    //   this.emit("close");

    //   if (this.reconnectCount < this.maxReconnectAttempts) {
    //     this.reconnectCount++;
    //     console.log(`尝试第 ${this.reconnectCount} 次重连`);
    //     setTimeout(() => this.connect(url), this.reconnectInterval);
    //   } else {
    //     console.log("达到最大重连次数,停止重连");
    //     modal.msgError("WebSocket连接失败,请检查网络后刷新页面重试");
    //   }
    // };
    this.ws.onclose = () => {
      console.log("WebSocket closed");
      this.emit("close");
      setTimeout(() => this.connect(url), this.reconnectInterval);
    };
  }

  send(data) {
    if (this.ws && this.ws.readyState === WebSocket.OPEN) {
      this.ws.send(JSON.stringify(data));
    } else {
      console.error("WebSocket is not connected");
    }
  }

  on(event, callback,id) {
    this.eventListeners[event] = [];
    this.eventListeners[event].push(callback);
    if (!this.listeners[event]) {
      this.listeners[event] = {};
    }
    this.listeners[event][id] = callback;
  }

  removeEventListener(event, id) {
    if (this.listeners[event] && this.listeners[event][id]) {
      delete this.listeners[event][id];
    }
  }

  closeMessageListener() {
    if (this.ws) {
      this.ws.onmessage = null;
    }
  }

  emit(event, data) {
    if (this.eventListeners[event]) {
      this.eventListeners[event].forEach((callback) => callback(data));
    }
  }

  close() {
    if (this.ws) {
      this.ws.close();
      this.ws = null;
    }
  }
}

export default WebSocketService;
