// 业务联查功能使用时socket切换到该文件
import { useHttp } from '@crami/http';
import { getInfo, ICP_CONFIG } from '@/utils/commMethods';
// import handleMessage from './messageHandle';

let socket = null;
const getUrl = async () => {
  const data = await useHttp({
    url: '/api/msg/serverUrl/getWebsocketServerUrl',
    method: 'get',
  });
  if (data.code === 200) {
    return data.data;
  } else {
    return false;
  }
};

const setSocket = async (opts = {}) => {
  if (socket && [socket.CONNECTING, socket.OPEN].includes(socket.readyState)) return;
  const router = opts.router;
  const userInfo = getInfo(ICP_CONFIG);
  const socketUrl = await getUrl();
  if (!userInfo || !socketUrl) return;
  const URL = `${socketUrl}${userInfo.user_id}`;
  socket = new WebSocket(URL);
  socket.addEventListener('message', event => {
    const { data } = event;
    let result: Record<string, any> = {};
    try {
      result = JSON.parse(data);
    } catch (e) {
      // TODO
    }

    // handleMessage(result);
  });
};
const closeSocket = async () => {
  socket.close();
};
export { setSocket, closeSocket };
