// src/utils/stompClient.js
import SockJS from 'sockjs-client';
import { Client } from '@stomp/stompjs';
import { wsConfig } from '@/config';

class StompClient {
  constructor(url) {
    this.url = url;
    this.client = null;
    this.subscriptions = new Map(); // pageCode -> subscription
    this.connectedCallbackQueue = [];
    this.connected = false;
  }

  // 初始化连接
  connect() {
    if (this.client) return;

    const socket = new SockJS(this.url);
    this.client = new Client({
      webSocketFactory: () => socket,
      reconnectDelay: 3000, // 断线重连时间
      // debug: (str) => console.log('[STOMP]', str),
      onConnect: () => {
        this.connected = true;
        console.log('STOMP 连接成功');
        this.connectedCallbackQueue.forEach((cb) => cb());
        this.connectedCallbackQueue = [];
      },
      onStompError: (frame) => {
        console.error('STOMP 错误', frame.headers['message'], frame.body);
      },
      onDisconnect: () => {
        this.connected = false;
        console.warn('STOMP 连接断开');
      },
    });

    this.client.activate();
  }

  // 订阅页面数据
  subscribeToPage(pageCode, onMessage) {
    if (!pageCode || typeof onMessage !== 'function') return;

    const doSubscribe = () => {
      const topic = `/topic/page/${pageCode}`;
      if (this.subscriptions.has(pageCode)) {
        console.warn(`已订阅过页面 ${pageCode}`);
        return;
      }

      const subscription = this.client.subscribe(topic, (msg) => {
        const data = JSON.parse(msg.body);
        // console.log(`接收到页面 ${pageCode} 数据：`, data);
        onMessage(data);
      });

      this.subscriptions.set(pageCode, subscription);
      console.log(`订阅页面 ${pageCode} 成功`);
    };

    if (this.connected) {
      doSubscribe();
    } else {
      this.connectedCallbackQueue.push(doSubscribe);
      this.connect();
    }
  }

  // 取消订阅
  unsubscribeFromPage(pageCode) {
    const subscription = this.subscriptions.get(pageCode);
    if (subscription) {
      subscription.unsubscribe();
      this.subscriptions.delete(pageCode);
      console.log(`已取消订阅页面 ${pageCode}`);
    }
  }

  // 主动断开连接
  disconnect() {
    if (this.client) {
      this.client.deactivate();
      this.client = null;
      this.connected = false;
      this.subscriptions.clear();
      console.log('STOMP 客户端已断开');
    }
  }
}

// 实例导出
export const stompClient = new StompClient(wsConfig.stompEndpoint);
