import { onMounted, onUnmounted, ref } from 'vue';
import { ElMessageBox } from 'element-plus';
import { useUserStore } from '@/stores';
import { useLockScreenStore } from '@/stores/modules/lockScreen';
import { INACTIVITY_TIMEOUT, INACTIVITY_WARNING } from '@/config';

/**
 * 空闲超时自动锁屏
 * 监听用户活动（鼠标、键盘、滚动、触摸），超过设定时间无操作则弹出警告，
 * 确认后仍无操作则自动锁屏，而非退出登录。
 */
export function useInactivityTimer() {
  const userStore = useUserStore();
  const lockStore = useLockScreenStore();
  const timer = ref<ReturnType<typeof setTimeout>>();
  const warningTimer = ref<ReturnType<typeof setTimeout>>();
  let warningDialog: ReturnType<typeof ElMessageBox.alert> | null = null;

  const events = ['mousemove', 'mousedown', 'keydown', 'scroll', 'touchstart', 'click'];

  function resetTimer() {
    clearTimeout(timer.value);
    clearTimeout(warningTimer.value);

    if (warningDialog) {
      warningDialog.close();
      warningDialog = null;
    }

    timer.value = setTimeout(showWarning, INACTIVITY_TIMEOUT - INACTIVITY_WARNING);
  }

  function showWarning() {
    warningTimer.value = setTimeout(doLock, INACTIVITY_WARNING);

    warningDialog = ElMessageBox.confirm(
      `您已 ${Math.round(INACTIVITY_TIMEOUT / 60000)} 分钟没有操作，系统将在 ${Math.round(INACTIVITY_WARNING / 1000)} 秒后自动锁屏。`,
      '空闲超时提醒',
      {
        confirmButtonText: '继续在线',
        cancelButtonText: '立即锁屏',
        type: 'warning',
        confirmButtonClass: 'el-button--primary',
        cancelButtonClass: 'el-button--info',
        roundButton: true,
        closeOnClickModal: false,
        closeOnPressEscape: false,
        autofocus: false,
      },
    )
      .then(() => {
        warningDialog = null;
        clearTimeout(warningTimer.value);
        resetTimer();
      })
      .catch(() => {
        warningDialog = null;
        doLock();
      });
  }

  function doLock() {
    warningDialog = null;
    clearTimeout(warningTimer.value);
    lockStore.lock();
  }

  function handleActivity() {
    // 锁屏状态下不响应活动重置
    if (userStore.token && !lockStore.isLocked) {
      resetTimer();
    }
  }

  onMounted(() => {
    if (userStore.token && !lockStore.isLocked) {
      resetTimer();
    }
    events.forEach((event) => {
      window.addEventListener(event, handleActivity, { passive: true });
    });
  });

  onUnmounted(() => {
    clearTimeout(timer.value);
    clearTimeout(warningTimer.value);
    if (warningDialog) {
      warningDialog.close();
    }
    events.forEach((event) => {
      window.removeEventListener(event, handleActivity);
    });
  });
}
