import * as SignalR from '@microsoft/signalr';
import { ElNotification } from 'element-plus';
import { getToken } from './request.mjs';

const initSignalR = () => {
  const token = getToken();
  if (!token) return null;
  const connection = new SignalR.HubConnectionBuilder().configureLogging(SignalR.LogLevel.Warning).withUrl(`${window.__env__.VITE_API_URL}/hubs/onlineUser?token=${token}`, {
    transport: SignalR.HttpTransportType.WebSockets,
    skipNegotiation: true
  }).withAutomaticReconnect({
    nextRetryDelayInMilliseconds: () => {
      return 5e3;
    }
  }).build();
  connection.keepAliveIntervalInMilliseconds = 15 * 1e3;
  connection.serverTimeoutInMilliseconds = 30 * 1e3;
  connection.start().then(() => {
  }).catch((err) => {
    console.error("SignalR \u8FDE\u63A5\u5931\u8D25:", err);
  });
  connection.onclose(async () => {
  });
  connection.onreconnecting(() => {
    ElNotification({
      title: "\u63D0\u793A",
      message: "\u8FDE\u63A5\u5DF2\u65AD\u5F00  >>>>>",
      type: "error",
      position: "bottom-right"
    });
  });
  connection.onreconnected(() => {
    ElNotification({
      title: "\u63D0\u793A",
      message: "\u8FDE\u63A5\u5DF2\u6062\u590D  >>>>>",
      type: "success",
      position: "bottom-right"
    });
  });
  connection.on("OnlineUserList", () => {
  });
  connection.on("ReceiveMessage", (message) => {
    var tmpMsg = `<div style="white-space: pre-wrap;">${message.message}<div><br/>`;
    tmpMsg += `<p style="color:#808080; font-size:10px;float:right"> ${message.sendUserName}  ${message.sendTime}<p>`;
    ElNotification({
      title: `${message.title}`,
      message: tmpMsg,
      type: message.messageType.toString().toLowerCase(),
      position: "top-right",
      dangerouslyUseHTMLString: true,
      duration: 5e3
    });
  });
  return connection;
};
const getSignalR = () => {
  return window.__SIGNALR_INSTANCE__;
};
if (!window.__SIGNALR_INSTANCE__) {
  const instance = initSignalR();
  if (instance) {
    window.__SIGNALR_INSTANCE__ = instance;
  }
}
if (!window.__SIGNALR_INSTANCE__) {
  const instance = initSignalR();
  if (instance) {
    window.__SIGNALR_INSTANCE__ = instance;
  } else {
  }
}
const signalR = {
  on: (event, callback) => {
    const instance = getSignalR();
    if (instance) {
      instance.on(event, callback);
    } else {
      console.warn(`SignalR \u672A\u8FDE\u63A5\uFF0C\u65E0\u6CD5\u76D1\u542C\u4E8B\u4EF6: ${event}`);
    }
  },
  off: (event, callback) => {
    const instance = getSignalR();
    if (instance) {
      instance.off(event, callback);
    }
  },
  send: (method, ...args) => {
    const instance = getSignalR();
    if (instance) {
      return instance.invoke(method, ...args);
    } else {
      console.warn("SignalR \u672A\u8FDE\u63A5\uFF0C\u65E0\u6CD5\u53D1\u9001\u6D88\u606F");
      return Promise.reject("SignalR \u672A\u8FDE\u63A5");
    }
  },
  stop: () => {
    const instance = getSignalR();
    if (instance) {
      return instance.stop();
    }
    return Promise.resolve();
  }
};
const restartSignalR = async () => {
  const instance = getSignalR();
  if (instance) {
    await instance.stop();
  }
  const newInstance = initSignalR();
  if (newInstance) {
    window.__SIGNALR_INSTANCE__ = newInstance;
  }
};

export { restartSignalR, signalR };
