import { createApp } from "vue";
import ElementPlus from "element-plus";
import "element-plus/dist/index.css";
import App from "./App.vue";
import "./registerServiceWorker";
import router from "./router";
import store from "./store";
import { setupRouterGuards, setupTokenRefresh } from "@/utils/permission";
import { setupPermissionDirectives } from "@/directives/permission";

// 引入 Quill 富文本编辑器样式（全局）
import "quill/dist/quill.snow.css";

// 初始化应用
async function initApp() {
  const app = createApp(App);

  // 使用插件
  app.use(ElementPlus);
  app.use(store);
  
  // 在路由初始化前，尝试恢复登录状态并生成动态路由
  const authState = (store.state as any).auth;
  
  if (authState.token && authState.menus && authState.menus.length > 0) {
    try {
      await store.dispatch('auth/generateRoutes');
    } catch (error) {
      console.error('[应用初始化] 动态路由生成失败:', error);
    }
  } else {
    console.log('[应用初始化] 无需生成动态路由（未登录或无菜单）');
  }
  
  app.use(router);

  // 设置权限指令
  setupPermissionDirectives(app, store);

  // 设置路由守卫
  setupRouterGuards(router, store);

  // 设置Token自动刷新
  setupTokenRefresh(store);

  app.mount("#app");
  console.log('[应用初始化] 应用挂载完成');
}

// 启动应用
initApp().catch(error => {
  console.error('[应用初始化] 应用启动失败:', error);
});
