//https://cn.sli.dev/custom/config-vue

import { defineAppSetup } from "@slidev/types";
import ElementPlus from "element-plus"; // 全局引入 Element Plus
import "element-plus/dist/index.css"; // 引入 Element Plus 全局样式
import axios from "axios";
import { isLoggedIn } from "../scripts/ojauth";

const request = axios.create({
  baseURL: "https://hydro.ac", // 开发环境使用代理
  timeout: 10000,
  headers: {
    "Content-Type": "application/json",
    Accept: "application/json",
  },
});

export default defineAppSetup(({ app, router }) => {
  // 4. 全局注册登录状态和方法（方便所有组件使用）
  app.config.globalProperties.$auth = {
    isLoggedIn,
  };

  if (process.env.NODE_ENV === "production") {
    // 5. 配置路由守卫（实现鉴权核心逻辑）
    router.beforeEach((to, from, next) => {
      // 定义无需鉴权的白名单路由（登录页、404等）
      const whiteList = ["/Login"]; // 对应你的登录页面路由

      // 判断当前路由是否需要鉴权
      const requiresAuth = !whiteList.includes(to.path);

      if (requiresAuth) {
        // 需要鉴权：已登录则放行，未登录则跳转到登录页
        if (isLoggedIn()) {
          next();
        } else {
          next("/Login"); // 重定向到登录页面
        }
      } else {
        // 无需鉴权：登录页如果已登录，自动跳转到首页（避免重复登录）
        if (to.path === "/Login" && isLoggedIn()) {
          next("/"); // 重定向到 Slidev 首页
        } else {
          next();
        }
      }
    });
  }

  // 保留你原有的插件注册（如果需要）
  // app.use(YourPlugin)
  app.use(ElementPlus); // 全局注册 Element Plus

  // 请求拦截器：自动携带token
  // axios.interceptors.request.use(
  //   (config) => {
  //     const token = localStorage.getItem("slidev_token");
  //     if (token) {
  //       config.headers.Authorization = `Bearer ${token}`; // 按后端要求格式携带
  //     }
  //     return config;
  //   },
  //   (error) => Promise.reject(error)
  // );

  // 响应拦截器：统一处理token过期
  // axios.interceptors.response.use(
  //   (response) => response,
  //   (error) => {
  //     // 假设后端返回401表示token过期/无效
  //     if (error.response?.status === 401) {
  //       // 清除本地状态，跳转到登录页
  //       localStorage.removeItem("slidev_is_logged_in");
  //       localStorage.removeItem("slidev_token");
  //       isLoggedIn.value = false;
  //       router.push("/login");
  //     }
  //     return Promise.reject(error);
  //   }
  // );
});
