import { useCommonStore } from "@/store/common";
export default class WebSocketService {
  constructor() {
    this.url = import.meta.env.VITE_APP_URL_WEBSOCKET;
    this.socket = null;
    this.isAlive = false; // 用于判断心跳是否正常
    this.reconnectAttempts = 0; // 重连尝试次数
    this.MAX_RECONNECT_ATTEMPTS = 5; // 最大重连次数
    // this.HEARTBEAT_INTERVAL = 5000; // 心跳间隔时间 (30秒)
    this.HEARTBEAT_INTERVAL = 30000; // 心跳间隔时间 (30秒)
    this.heartbeatTimer = null;
    this.reconnectTimer = null;

    // this.connect();
  }

  connect() {
    this.socket = new WebSocket(this.url);
    this.socket.onopen = () => {
      console.log('WebSocket已连接');
      this.webScoketLogin();
      this.reconnectAttempts = 0; // 成功连接后重置重试次数
      this.startHeartbeat(); // 开始心跳检测
    };
    this.onMessage()
    this.socket.onmessage = (event) => {
      // 处理接收到的消息
      console.log('WebSocket收到消息:', event.data);
      this.receivePong()
    };

    this.socket.onclose = () => {
      console.log('WebSocket连接已关闭');
      this.stopHeartbeat();
      this.attemptReconnect();
    };

    this.socket.onerror = (error) => {
      console.log('WebSocket连接错误', error);
    };
  }

  webScoketLogin() {
    const comm = useCommonStore();
    this.sendMessage({
      username: comm.user.username,
      token: comm.user.token,
      type: 'web',
      cmd: "webLogin",
    })
  }
  // 开始发送心跳
  startHeartbeat() {
    console.log('开始发送心跳');
    if (!this.heartbeatTimer) {
      this.heartbeatTimer = setInterval(() => {
        if (this.socket.readyState === WebSocket.OPEN) {
          this.isAlive = false;
          this.sendPing();
        }
      }, this.HEARTBEAT_INTERVAL);
    }
  }
  // 关闭发送心态
  stopHeartbeat() {
    if (this.heartbeatTimer) {
      clearInterval(this.heartbeatTimer);
      this.heartbeatTimer = null;
    }
  }

  sendPing() {
    this.socket.send(JSON.stringify({ cmd: 'heartbeat' }));
    setTimeout(() => {
      if (!this.isAlive) {
        console.warn('WebSocket heartbeat failed, attempting to reconnect...');
        this.socket.close();
      }
    }, this.HEARTBEAT_INTERVAL / 2); // 如果没有pong响应，则关闭并重连
  }

  receivePong() {
    this.isAlive = true;
  }
  // 重新连接
  attemptReconnect() {
    const comm = useCommonStore();
    if (!comm.user.token) return
    if (this.reconnectAttempts < this.MAX_RECONNECT_ATTEMPTS) {
      this.reconnectAttempts++;
      console.log(`正在尝试重新连接 (${this.reconnectAttempts})...`);
      this.reconnectTimer = setTimeout(() => {
        this.connect();
      }, 1000 * this.reconnectAttempts); // 指数退避算法
    } else {
      console.error('达到的最大重连尝试数');
    }
  }
  // 发送消息
  sendMessage(message) {
    console.log('sendMessage');
    if (this.socket && this.socket.readyState === WebSocket.OPEN) {
      this.socket.send(JSON.stringify(message));
    }
  }

  onMessage = (callback) => {
    this.socket.onmessage = (event) => {
      const data = JSON.parse(event.data);
      // console.log(data, 'onMessage');

      if (data.cmd == "webLogin" && !data.code == 200) return this.webScoketLogin()
      callback && callback(data);
      if (event.data.includes('heartbeat')) {
        this.receivePong();
      }
    };
  };
  // 关闭连接
  close() {
    this.stopHeartbeat();
    if (this.reconnectTimer) {
      clearTimeout(this.reconnectTimer);
      this.reconnectTimer = null;
    }
    if (this.socket) {
      this.socket.close();
      this.socket = null;
    }
  }
}

