import { onBeforeUnmount } from 'vue';

function useMultipleWebSockets(urls: any) {
  const sockets: { [key: string]: WebSocket } = {};
  const status: { [key: string]: string } = {};
  const sendData: { [key: string]: string } = {};

  // 初始化所有连接
  urls.forEach((url: string) => {
    sockets[url] = new WebSocket(url);

    sockets[url].onopen = () => {
      console.log(`WebSocket connected to ${url}`);
      status[url] = "connected";
    };

    sockets[url].onmessage = (event) => {
      // console.log(`Message from ${url}:`, event.data);
      sendData[url] = event.data;
      // 处理不同来源的消息
    };

    sockets[url].onerror = (error) => {
      console.error(`WebSocket error on ${url}:`, error);
    };

    sockets[url].onclose = () => {
      console.log(`WebSocket disconnected from ${url}`);
      status[url] = "disconnected";
    };
  });

  // 组件卸载时关闭所有连接
  onBeforeUnmount(() => {
    Object.values(sockets).forEach(socket => {
      if (socket.readyState === WebSocket.OPEN) {
        socket.close();
      }
    });
  });

  // 发送消息到指定连接
  const send = (url: any, message: any) => {
    if (sockets[url] && sockets[url].readyState === WebSocket.OPEN) {
      sockets[url].send(JSON.stringify(message));
    }
  };

  return { sockets, send,sendData,status };
}


export default useMultipleWebSockets;