
import { onBeforeUnmount, ref } from 'vue';


// function useMultipleWebSockets(urls: any) {

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

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

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

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

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

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

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

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

const useSockets = () => {
  const sockets = ref<{ [key: string]: WebSocket }>({});
  const connectedStatus = ref<{ [key: string]: string }>({});

  const connected = (url: any) => {
    return new Promise((resolve, reject) => {
      connectedStatus.value[url] = "connecting";
      if (sockets.value[url]) {
        resolve(sockets.value[url]);
        return;
      }
      try {
        const ws = new WebSocket(url) || "";
        ws.onopen = () => {
          sockets.value[url] = ws;
          connectedStatus.value[url] = "connected";
          resolve(ws);
        };
        ws.onclose = (error: any) => {
          connectedStatus.value[url] = "disconnected";
          reject(error);
        };
        ws.onerror = (error: any) => {
          connectedStatus.value[url] = "error";
          reject(error);
        }
      }catch (error) {
        console.log(error)
        reject(error);
      }
    });
  };
  onBeforeUnmount(() => {
    Object.values(sockets.value).forEach(socket => {
      socket.close();
    });
  });

  return { sockets, connectedStatus, connected };
};

export default useSockets;
