'use strict';

var lodashEs = require('lodash-es');
var storage = require('../utils/storage.js');
var elementPlus = require('element-plus');
var request = require('../utils/request.js');
var useLocale = require('./useLocale.js');

var __defProp = Object.defineProperty;
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
async function loadSignalR() {
  while (!window.__SIGNALR_INSTANCE__) {
    await new Promise((resolve) => setTimeout(resolve, 100));
  }
  return window.__SIGNALR_INSTANCE__;
}
class IdleTimeoutManager {
  constructor(config = {}) {
    __publicField(this, "timerId", null);
    __publicField(this, "config");
    __publicField(this, "debouncedReset");
    /** 检查闲置超时时间间隔 */
    __publicField(this, "checkTimeoutInterval", 2 * 1e3);
    __publicField(this, "handleVisibilityChange", () => {
      if (document.visibilityState === "visible") {
        this.setLastActivityTime();
      }
    });
    this.config = {
      timeout: 30 * 60,
      events: ["mousewheel", "keydown", "click"],
      onTimeout: this.timeOutExec.bind(this),
      debounceInterval: 200,
      ...config
    };
    this.debouncedReset = this.config.debounceInterval > 0 ? lodashEs.debounce(this.setLastActivityTime.bind(this), this.config.debounceInterval) : this.setLastActivityTime.bind(this);
    this.init();
  }
  init() {
    this.config.events.forEach((event) => {
      window.addEventListener(event, this.debouncedReset);
    });
    document.addEventListener("visibilitychange", this.handleVisibilityChange);
    this.setLastActivityTime();
    this.updateIdleTimeout(this.config.timeout);
  }
  /** 设置最后活动时间 */
  setLastActivityTime() {
    storage.Local.set("lastActivityTime", (/* @__PURE__ */ new Date()).getTime());
  }
  /**
   * 更新空闲超时时间
   * @param timeout - 新的超时时间（毫秒）
   */
  updateIdleTimeout(timeout) {
    this.config.timeout = timeout;
    if (this.config.timeout > 0 && this.timerId == null) {
      this.timerId = window.setInterval(this.checkTimeout.bind(this), this.checkTimeoutInterval);
    } else if (this.config.timeout == 0 && this.timerId != null) {
      window.clearInterval(this.timerId);
      this.timerId = null;
    }
  }
  /** 检查是否超时 */
  checkTimeout() {
    const currentTime = (/* @__PURE__ */ new Date()).getTime();
    const lastActivityTime = Number(storage.Local.get("lastActivityTime"));
    if (lastActivityTime == 0) return;
    const accessToken = storage.Local.get(request.accessTokenKey);
    if (!accessToken || accessToken == "invalid_token") return;
    const timeout = this.config.timeout * 1e3;
    if (currentTime - lastActivityTime > timeout) {
      this.destroy();
      this.config.onTimeout();
    }
  }
  /** 销毁实例 */
  destroy() {
    this.config.events.forEach((event) => {
      window.removeEventListener(event, this.debouncedReset);
    });
    document.removeEventListener("visibilitychange", this.handleVisibilityChange);
    if (this.timerId !== null) {
      window.clearInterval(this.timerId);
      this.timerId = null;
    }
  }
  /** 超时时执行 */
  timeOutExec() {
    const appEl = document.getElementById("app");
    appEl == null ? void 0 : appEl.remove();
    loadSignalR().then((signalR) => {
      signalR.stop();
    });
    storage.Local.remove(request.accessTokenKey);
    storage.Local.remove(request.refreshAccessTokenKey);
    storage.Session.clear();
    const { t } = useLocale.useLocale();
    elementPlus.ElMessageBox.alert(t("plus.list.idleTimeoutMessage"), t("plus.list.sysMessage"), {
      type: "warning",
      draggable: true,
      callback: () => {
        window.location.reload();
      }
    });
  }
}
function initIdleTimeout(config) {
  if (!window.__IDLE_TIMEOUT__) {
    window.__IDLE_TIMEOUT__ = new IdleTimeoutManager(config);
  }
  return window.__IDLE_TIMEOUT__;
}
function destroyIdleTimeout() {
  if (window.__IDLE_TIMEOUT__) {
    window.__IDLE_TIMEOUT__.destroy();
    window.__IDLE_TIMEOUT__ = void 0;
  }
}
function updateIdleTimeout(timeout) {
  if (window.__IDLE_TIMEOUT__) {
    window.__IDLE_TIMEOUT__.updateIdleTimeout(timeout);
  }
}

exports.destroyIdleTimeout = destroyIdleTimeout;
exports.initIdleTimeout = initIdleTimeout;
exports.updateIdleTimeout = updateIdleTimeout;
