import axios from "axios";
import { authStore } from "@/store/auth";
import { ElNotification } from "element-plus";
import router from "@/router";

let notifyInstance = null;

// 创建 axios 实例
const api = axios.create({
  baseURL: import.meta.env.VITE_API_URL,
  timeout: 60000, // 请求超时设置，单位是毫秒
  headers: {
    "Content-Type": "application/json",
  },
});

// 是否正在刷新 token 的标志
let isRefreshing = false;
// 重试队列，用于存放因 token 过期而失败的请求
let retryQueue = [];

/**
 * 处理重试队列
 * @param {string} token - 新的 token
 */
function processQueue(token) {
  retryQueue.forEach(({ resolve, reject, config }) => {
    if (token) {
      config.headers.Authorization = `Bearer ${token}`;
      resolve(api.request(config));
    } else {
      reject(new Error("Token 刷新失败"));
    }
  });
  retryQueue = [];
}

// 请求拦截器，在请求头中添加 token
api.interceptors.request.use(
  (config) => {
    // 如果请求配置中标记了不需要认证，则跳过添加 token
    if (config.skipAuth) {
      return config;
    }
    const token = sessionStorage.getItem("accessToken");
    if (token) {
      config.headers.Authorization = `Bearer ${token}`;
    }

    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// 响应拦截器，处理 token 过期和自动刷新
api.interceptors.response.use(
  (response) => {
    // 这里可以处理返回的数据
    return response.data;
  },
  async (error) => {
    if (error.response && error.response.status === 401) {
      const auth = authStore();
      auth.logout();
      const currentPath = router.currentRoute.value.path;
      if (currentPath !== '/login') {
        router.push('/login');
      }
      if (!notifyInstance) {
        notifyInstance = ElNotification({
          title: '登录失效',
          message: '当前登录已经失效, 请重新登录',
          type: 'info',
          onClose: () => {
            notifyInstance = null;
          }
        })
      }
      return Promise.reject(error)
    }

    // 其他错误直接返回
    console.error("请求失败", error);
    return Promise.reject(error);
  }
);

// 发送请求的具体方法
export const post = async (url, query = {}) => {
  try {
    // 创建新对象避免修改原对象
    const params = { ...query };
    if (!params.corpId) {
      params.corpId = sessionStorage.getItem("corpId");
    }

    // 检查是否为登录接口，登录接口不需要token
    const isLoginRequest = params.type === "login";
    const config = isLoginRequest ? { skipAuth: true } : {};

    const result = await api.post(`/getYoucanData/${url}`, params, config);
    const { success = false, message, ...data } = result;
    console.log(`api name: ${params.type || "unknown"}`);
    console.log(data);
    return { success, data, message: message || (success ? "" : "服务器开小差了, 请稍后再试~") };
  } catch (e) {
    console.error(`API 请求失败 [${url}]:`, e);
    return { success: false, message: e.message || "服务器开小差了, 请稍后再试~~" };
  }
};

export const postFile = async (formData) => {
  try {
    const result = await api.post("/upload", formData, {
      headers: {
        "Content-Type": "multipart/form-data",
      },
    });
    return result;
  } catch {
    return { success: false, message: "服务器开小差了, 请稍后再试~" };
  }
};

export const postParseFile = async (formData, path) => {
  try {
    const result = await api.post(path, formData, {
      headers: {
        "Content-Type": "multipart/form-data",
      },
    });
    return result;
  } catch {
    return { success: false, message: "服务器开小差了, 请稍后再试~" };
  }
};
