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

// const apiUrl = `ws://121.229.107.155:19021/time`;  //线上
const apiUrl = `ws://127.0.0.1:19021/time`;  //线上
let Timewss = null;
let timer = null;
const appStore = useAppStore();

function createWebSocket() {
  Timewss = new WebSocket(apiUrl);

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

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

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

  Timewss.onclose = () => {
    console.log('连接关闭，1秒后重连...');
    timer = setTimeout(() => {
      Timewss = createWebSocket(); // 重新创建连接
      clearTimeout(timer);
      timer = null; //释放内存
    }, 1000);
  };
}

// 初始化连接
if (!Timewss || Timewss.readyState === WebSocket.CLOSED) {
  createWebSocket();
}

export default Timewss;