<template>
  <div class="dds"></div>
</template>

<script>
const prefix = process.env.VUE_APP_WS_URL;
export default {
  name: 'SocketMessage',
  props: {
    onMessage: {
      type: Function,
      required: true,
    },
    ws: {
      type: String,
      required: true,
    },
  },
  data() {
    return {
      socket: null,
      url: prefix,
      reconnectInterval: 5000, // 重连间隔时间（毫秒）
      maxReconnectAttempts: 10, // 最大重连次数
      reconnectAttempts: 0, // 当前重连次数
    };
  },
  mounted() {
    this.connect();
  },
  beforeDestroy() {
    this.disconnect();
  },
  methods: {
    connect() {
      this.socket = new WebSocket(`${prefix}${this.ws}`);
      this.socket.onopen = this.onOpen;
      this.socket.onmessage = this.onMessageReceived;
      this.socket.onerror = this.onError;
      this.socket.onclose = this.onClose;
    },
    disconnect() {
      if (this.socket) {
        this.socket.close();
        this.socket = null;
      }
    },
    onOpen() {
      console.log('WebSocket connection established');
      this.reconnectAttempts = 0; // 重置重连次数
    },
    onMessageReceived(event) {
      const data = JSON.parse(event.data);
      this.onMessage(data);
    },
    onError(error) {
      console.error('WebSocket error:', error);
    },
    onClose(event) {
      console.log('WebSocket closed:', event);
      this.reconnect();
    },
    reconnect() {
      if (this.socket && this.socket.readyState === WebSocket.CLOSED) {
        if (this.reconnectAttempts < this.maxReconnectAttempts) {
          console.log(`Reconnecting in ${this.reconnectInterval}ms...`);
          setTimeout(() => {
            this.reconnectAttempts++;
            this.connect();
          }, this.reconnectInterval);
        } else {
          console.error('Max reconnect attempts reached');
        }
      } else {
        console.log('WebSocket is not closed, no need to reconnect');
      }
    }
  },
};
</script>
