import useAppStore from '@/store/module/app.js';

// const apiUrl = `ws://${import.meta.env.VITE_WS_URL}/time`;  //线上
const apiUrl = `ws://${import.meta.env.VITE_WS_URL}/time`;  //本地
let Timewss = null;
let timer = null;
const appStore = useAppStore();

function createWebSocket(options = {}) {
  if (Timewss && Timewss.readyState === WebSocket.OPEN) {
    console.log('TimeWebSocket已连接，无需重复创建');
    // 如果有新传入的 onmessage，更新它
    if (options.onmessage) {
      Timewss.onmessage = options.onmessage;
    }
    return Timewss;
  }

  Timewss = new WebSocket(apiUrl);

  Timewss.onopen = () => {
    console.log('TimeWebSocket已连接');
    options.onopen?.();
  };

  Timewss.onmessage = (event) => {
    console.log('Time接收到消息:', event.data);
    options.onmessage?.(event);
  };

  Timewss.onerror = (error) => {
    console.error('WebSocket错误:', error);
    options.onerror?.(error);
  };

  Timewss.onclose = () => {
    console.log('连接关闭，1秒后重连...');
    timer = setTimeout(() => {
      createWebSocket(options); // 重新创建连接，保留回调
      clearTimeout(timer);
      timer = null;
    }, 1000);
  };

  return Timewss;
}

// 获取当前 WebSocket 实例
function getTimewss() {
  return Timewss;
}

export {
  createWebSocket,
  getTimewss
};