import { SocketEnum } from '@/enums/socketEnum';
import { notificationStoreWidthOut } from '@/store/modules/notification';
const notificationStore = notificationStoreWidthOut();
import { useUserStoreWidthOut } from '@/store/modules/user';

let socket: WebSocket;

export function getSocket(): WebSocket {
  console.log('socket:', socket);
  if (socket === undefined) {
    location.reload();
  }
  return socket;
}

export function addOnMessage(onMessageList: any, func: Function) {
  let exist = false;
  for (let i = 0; i < onMessageList.length; i++) {
    if (onMessageList[i].name == func.name) {
      onMessageList[i] = func;
      exist = true;
    }
  }
  if (!exist) {
    onMessageList.push(func);
  }
}

export default (onMessage: Function) => {
  const heartCheck = {
    timeout: 5000,
    timeoutObj: setTimeout(() => {}),
    serverTimeoutObj: setInterval(() => {}),
    reset: function () {
      clearTimeout(this.timeoutObj);
      clearTimeout(this.serverTimeoutObj);
      return this;
    },
    start: function () {
      // eslint-disable-next-line @typescript-eslint/no-this-alias
      const self = this;
      clearTimeout(this.timeoutObj);
      clearTimeout(this.serverTimeoutObj);
      this.timeoutObj = setTimeout(function () {
        socket.send(
          JSON.stringify({
            type: SocketEnum.TypeHeartBeat,
          })
        );
        console.log('ping');
        self.serverTimeoutObj = setTimeout(function () {
          console.log('关闭服务');
          socket.close();
        }, self.timeout);
      }, this.timeout);
    },
  };
  const useUserStore = useUserStoreWidthOut();
  let lockReconnect = false;
  let timer: ReturnType<typeof setTimeout>;
  const createSocket = () => {
    console.log('createSocket...11111');
    console.log('useUserStore.config:', useUserStore);
    try {
      socket = new WebSocket(
        useUserStore.config.socket_url + '?authorization=' + useUserStore.token
      );
      init();
    } catch (e) {
      console.log('createSocket err:' + e);
      reconnect();
    }
    if (lockReconnect) {
      lockReconnect = false;
    }
  };
  const reconnect = () => {
    if (lockReconnect) return;
    lockReconnect = true;
    clearTimeout(timer);
    timer = setTimeout(() => {
      createSocket();
    }, SocketEnum.HeartBeatInterval);
  };

  const init = () => {
    socket.onopen = function (_) {
      console.log('WebSocket:已连接');
      heartCheck.reset().start();
    };

    socket.onmessage = function (event) {
      console.log('WebSocket:收到一条消息', event.data);
      const isHeart = /pong/.test(event.data);
      console.log('isHeart:' + isHeart);
      notificationStore.addMessages(event.data);

      if (onMessage && !isHeart) {
        onMessage.call(null, event);
      }
      heartCheck.reset().start();
    };

    socket.onerror = function (_) {
      console.log('WebSocket:发生错误');
      reconnect();
    };

    socket.onclose = function (_) {
      console.log('WebSocket:已关闭');
      heartCheck.reset();
      reconnect();
    };

    window.onbeforeunload = function () {
      socket.close();
    };
  };

  createSocket();
};
