<script setup lang="ts">
import { computed, onBeforeUnmount, onMounted } from 'vue';
import { NConfigProvider, NMessageProvider, createDiscreteApi, darkTheme } from 'naive-ui';
import type { WatermarkProps } from 'naive-ui';
import { useAppStore } from './store/modules/app';
import { useThemeStore } from './store/modules/theme';
import { naiveDateLocales, naiveLocales } from './locales/naive';
import { clearAuthStorage } from './store/modules/auth/shared';

const { message } = createDiscreteApi(['message']);

defineOptions({
  name: 'App'
});

const appStore = useAppStore();
const themeStore = useThemeStore();

const naiveDarkTheme = computed(() => (themeStore.darkMode ? darkTheme : undefined));

const naiveLocale = computed(() => {
  return naiveLocales[appStore.locale];
});

const naiveDateLocale = computed(() => {
  return naiveDateLocales[appStore.locale];
});

const watermarkProps = computed<WatermarkProps>(() => {
  return {
    content: themeStore.watermark?.text || 'SoybeanAdmin',
    cross: true,
    fullscreen: true,
    fontSize: 16,
    lineHeight: 16,
    width: 384,
    height: 384,
    xOffset: 12,
    yOffset: 60,
    rotate: -15,
    zIndex: 9999
  };
});

let isMinimized = false;
let minimizedTime = 0;
let shouldRedirect = false;
const maxMinimizedDuration = 60 * 60 * 1000; // 10分钟不在当前页面操作就登出

const checkMinimized = () => {
  if (isMinimized && Date.now() - minimizedTime > maxMinimizedDuration) {
    shouldRedirect = true; // 设置为需要跳转
  }
};

const handleVisibilityChange = () => {
  if (document.hidden) {
    isMinimized = true;
    minimizedTime = Date.now();
  } else {
    isMinimized = false;
    if (shouldRedirect) {
      message.create('您已离开页面太久，请重新登录。', {
        type: 'info', // 信息类型
        duration: 2000, // 信息展示的时长
        onAfterLeave() {
          clearAuthStorage();
          window.location.href = '/login';
        }
      });
    }
  }
};
onMounted(() => {
  document.addEventListener('visibilitychange', handleVisibilityChange);
  setInterval(checkMinimized, 1000); // 每秒检查一次
});
onBeforeUnmount(() => {
  document.removeEventListener('visibilitychange', handleVisibilityChange);
});
</script>

<template>
  <NMessageProvider></NMessageProvider>
  <NConfigProvider
    :theme="naiveDarkTheme"
    :theme-overrides="themeStore.naiveTheme"
    :locale="naiveLocale"
    :date-locale="naiveDateLocale"
    class="h-full"
  >
    <AppProvider>
      <RouterView class="bg-layout" />
      <NWatermark v-if="themeStore.watermark?.visible" v-bind="watermarkProps" />
    </AppProvider>
  </NConfigProvider>
</template>

<style scoped></style>
