'use strict';

var vue = require('vue');
var pinia = require('pinia');
var core = require('@vueuse/core');

const LOGIN_WINDOW_MS = 30 * 1e3;
const LOGIN_MAX_TRIGGERS = 5;
const useLoginStore = pinia.defineStore("gmLoginStore", () => {
  const showLogin = vue.ref(false);
  const userToken = core.useSessionStorage("gmUserToken", void 0);
  const userId = core.useSessionStorage("gmUserId", void 0);
  const loginResult = core.createEventHook();
  const loginTriggerTimestamps = vue.ref([]);
  const isLoginBlocked = vue.computed(() => {
    const now = Date.now();
    const recentCount = loginTriggerTimestamps.value.filter((t) => now - t < LOGIN_WINDOW_MS).length;
    return recentCount >= LOGIN_MAX_TRIGGERS;
  });
  const recordLoginTrigger = () => {
    const now = Date.now();
    loginTriggerTimestamps.value = loginTriggerTimestamps.value.filter((t) => now - t < LOGIN_WINDOW_MS);
    loginTriggerTimestamps.value.push(now);
  };
  const resetLoginBlock = () => {
    loginTriggerTimestamps.value = [];
  };
  const triggerLoginResult = loginResult.trigger;
  const onLoginResultPromise = () => new Promise((resolve) => {
    loginResult.on(resolve);
  });
  const closeLoginResult = core.createEventHook();
  const triggerCloseLoginResult = closeLoginResult.trigger;
  const onCloseLoginResultPromise = () => new Promise((resolve) => {
    closeLoginResult.on(resolve);
  });
  vue.watch(showLogin, (newValue, oldValue) => {
    if (newValue && !oldValue) {
      recordLoginTrigger();
    }
    if (!newValue) {
      triggerCloseLoginResult();
    }
  });
  return {
    /**是否显示登录弹窗 */
    showLogin,
    userToken,
    userId,
    triggerLoginResult,
    /** 监听登录成功*/
    onLoginResult: loginResult.on,
    /** 监听登录成功  promise版 */
    onLoginResultPromise,
    /**监听登录弹窗关闭  promise版 */
    onCloseLoginResultPromise,
    // 401循环保护相关
    /** 是否被阻止登录（30秒内触发超过5次） */
    isLoginBlocked,
    /** 记录登录弹窗触发时间 */
    recordLoginTrigger,
    /** 重置登录阻止状态 */
    resetLoginBlock
  };
});

exports.useLoginStore = useLoginStore;
//# sourceMappingURL=index.js.map
