import { createApp } from 'vue';
import { Editor, Toolbar } from '@wangeditor/editor-for-vue';
import '@wangeditor/editor/dist/css/style.css';
import VueGridLayout from 'vue-grid-layout';
import './plugins/assets';
import { localStg } from '@/utils/storage';
// main.js or main.ts
import 'font-awesome/css/font-awesome.css';
import { setupDayjs, setupIconifyOffline, setupLoading, setupNProgress } from './plugins';
import { setupStore } from './store';
import { setupRouter } from './router';
import { setupI18n } from './locales';
import App from './App.vue';

let timeoutHandle: string | number | NodeJS.Timeout | undefined;
const INACTIVITY_TIMEOUT = 20 * 60 * 1000;

function handleLogout(app: any) {
  localStg.remove('token');
  localStg.remove('refreshToken');
  localStg.remove('userInfo');
  app.config.globalProperties.$router.push('/login/pwd-login');
}

function checkLastActivity(app: any) {
  const lastActivity = localStorage.getItem('lastActivityTime');
  if (lastActivity) {
    const timeDiff = Date.now() - Number.parseInt(lastActivity, 10);
    if (timeDiff > INACTIVITY_TIMEOUT) {
      handleLogout(app);
    }
  }
}

function startInactivityTimer(app: any) {
  clearTimeout(timeoutHandle);
  localStorage.setItem('lastActivityTime', Date.now().toString());
  timeoutHandle = setTimeout(() => handleLogout(app), INACTIVITY_TIMEOUT);
}

function resetInactivityTimer(app: any) {
  startInactivityTimer(app);
}

async function setupApp() {
  setupLoading();
  setupNProgress();
  setupIconifyOffline();
  setupDayjs();

  const app = createApp(App);
  setupStore(app);
  await setupRouter(app);
  setupI18n(app);

  // 检查上次活动时间
  checkLastActivity(app);

  // 监听用户的操作
  window.addEventListener('mousemove', () => resetInactivityTimer(app));
  window.addEventListener('keydown', () => resetInactivityTimer(app));
  window.addEventListener('click', () => resetInactivityTimer(app));
  window.addEventListener('scroll', () => resetInactivityTimer(app));

  // 启动计时器
  startInactivityTimer(app);

  app.use(VueGridLayout);

  // 全局注册 wangeditor 组件
  app.component('WangEditor', Editor);
  app.component('WangToolbar', Toolbar);

  app.mount('#app');
}

// 页面卸载时保存最后活动时间
window.addEventListener('beforeunload', () => {
  localStorage.setItem('lastActivityTime', Date.now().toString());
});

setTimeout(() => {
  setupApp();
}, 200);
