// API请求工具 - 基于axios封装
import axios from "axios";
import config from "../utils/config.js";
import { Local } from "./storage.js";
import { showToast, showLoadingToast, closeToast } from "vant";
import { useRouter } from "vue-router";
const router = useRouter();
class ApiService {
  constructor() {
    // 创建axios实例
    this.axios = axios.create({
      baseURL: config.baseURL,
      timeout: config.timeout,
      withCredentials: true, // 包含cookies
      headers: {
        "Content-Type": "application/json",
      },
    });

    this.debug = config.debug;

    // 添加请求拦截器
    this.axios.interceptors.request.use(
      (axiosConfig) => {
        // 获取并添加token到请求头
        const token = Local.get("token");
        if (token) {
          axiosConfig.headers["Authorization"] = token;
        }
        showLoadingToast({
          forbidClick: true,
          loadingType: "spinner",
        });
        // 打印调试信息
        if (this.debug) {
          console.log(
            `[API请求] ${axiosConfig.method.toUpperCase()} ${axiosConfig.url}`
          );
          if (axiosConfig.data) {
            console.log("[API请求数据]", axiosConfig.data);
          }
        }
        return axiosConfig;
      },
      (error) => {
        // 处理请求错误
        console.error("[API错误]", error);
        return Promise.reject(error);
      }
    );

    // 添加响应拦截器
    this.axios.interceptors.response.use(
      (response) => {
        const data = response.data;
        // 打印调试信息
        if (this.debug) {
          console.log("[API响应]", response.data);
        }
        closeToast();
        // 处理响应数据
        if (
          data.code == 400 ||
          data.code == 401 ||
          data.code == 402 ||
          data.code == 403 ||
          data.code == 404
        ) {
          showToast(data.msg || data.message || "请求失败");
          Local.remove("token");
          Local.remove("userInfo");
          router.push("/Login");
        } else if (data.code == 500) {
          showToast(data.msg || data.message || "请求失败");
        }
        return data;
      },
      (error) => {
        // 处理响应错误
        showToast(error.msg || error.message || "请求失败");
        console.error("[API错误]", error);
        throw error;
      }
    );
  }

  // GET请求
  get(url, params = null, headers = {}) {
    return this.axios.get(url, { params, headers });
  }

  // POST请求
  post(url, data = null, headers = {}) {
    return this.axios.post(url, data, { headers });
  }

  // PUT请求
  put(url, data = null, headers = {}) {
    return this.axios.put(url, data, { headers });
  }

  // DELETE请求
  delete(url, params = null, headers = {}) {
    return this.axios.delete(url, { params, headers });
  }

  // PATCH请求
  patch(url, data = null, headers = {}) {
    return this.axios.patch(url, data, { headers });
  }
}

// 导出API服务实例
export default new ApiService();

// 导出API服务类，以便需要时可以创建新的实例
export { ApiService };
