import { computed, onUnmounted, unref, watchEffect } from "vue";
import { useThrottleFn } from "@vueuse/core";

// import { useAppStore } from '/@/store/modules/app';
import { useLockStore } from "@/stores/modules/lock";

// import { useUserStore } from '/@/store/modules/user';
// import { useRootSetting } from '../setting/useRootSetting';
import { useUserStore } from "@/stores/modules/user";
import { useGlobalStore } from "@/stores/modules/global";

import type { TimeoutHandle } from "@/typings/global";

export function useLockPage() {
  const { autoLockTime } = useGlobalStore();
  const lockStore = useLockStore();
  const userStore = useUserStore();
  // const appStore = useAppStore();

  let timeId: TimeoutHandle;

  function clear(): void {
    window.clearTimeout(timeId);
  }

  function resetCalcLockTimeout(): void {
    // not login
    if (!userStore.token) {
      clear();
      return;
    }
    // const lockTime = appStore.getProjectConfig.lockTime;
    const lockTime = autoLockTime;
    if (!lockTime || lockTime < 1) {
      clear();
      return;
    }
    clear();

    timeId = setTimeout(() => {
      lockPage();
    }, lockTime * 60 * 1000);
  }

  function lockPage(): void {
    lockStore.setLockInfo({
      isLock: true,
      psw: undefined
    });
  }

  watchEffect(onClean => {
    if (userStore.token) {
      resetCalcLockTimeout();
    } else {
      clear();
    }
    onClean(() => {
      clear();
    });
  });

  onUnmounted(() => {
    clear();
  });

  const keyupFn = useThrottleFn(resetCalcLockTimeout, 2000);

  return computed(() => {
    if (unref(autoLockTime)) {
      return { onKeyup: keyupFn, onMousemove: keyupFn };
    } else {
      clear();
      return {};
    }
  });
}
