/*
 * @Author: donghao donghao@supervision.ltd
 * @Date: 2025-03-12 15:11:56
 * @LastEditors: donghao donghao@supervision.ltd
 * @LastEditTime: 2025-03-13 10:48:58
 * @FilePath: \5G-Loading-Bay-Web\src\utils\request\index.ts
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import axios, { AxiosInstance, AxiosRequestConfig, AxiosResponse } from "axios";
import { ElMessage, ElMessageBox } from "element-plus";
import type { RequestConfig, RequestInterceptors } from "./type";
import { useUserStore } from "@/stores/user";

class Request {
  instance: AxiosInstance;
  interceptors?: RequestInterceptors;

  constructor(config: RequestConfig) {
    this.instance = axios.create(config);
    this.interceptors = config.interceptors;

    // 全局请求拦截器
    this.instance.interceptors.request.use(
      (config: RequestConfig) => {
        // 处理 token
        const userStore = useUserStore();
        if (userStore.token) {
          config.headers!.Access = `Bearer ${userStore.token}`;
        }
        return config;
      },
      (error: any) => Promise.reject(error)
    );

    // 实例拦截器
    this.instance.interceptors.request.use(
      this.interceptors?.requestInterceptor,
      this.interceptors?.requestInterceptorCatch
    );

    this.instance.interceptors.response.use(
      this.interceptors?.responseInterceptor,
      this.interceptors?.responseInterceptorCatch
    );

    // 全局响应拦截器
    this.instance.interceptors.response.use(
      (res: AxiosResponse) => {
        const { code, message } = res.data;
        if (code !== 200) {
          ElMessage.error(message || "请求失败");
          return Promise.reject(message);
        }
        return res.data;
      },
      (error: any) => {
        // 处理 HTTP 状态码
        if (error.response?.status === 401) {
          ElMessageBox.confirm("登录已过期，请重新登录", "提示", {
            confirmButtonText: "重新登录",
            cancelButtonText: "取消",
            type: "warning",
          }).then(() => {
            const userStore = useUserStore();
            userStore.logout();
          });
        }
        ElMessage.error(error.message || "请求错误");
        return Promise.reject(error);
      }
    );
  }

  request<T = any>(config: RequestConfig<T>): Promise<T> {
    return new Promise((resolve, reject) => {
      // 单个请求的拦截器
      if (config.interceptors?.requestInterceptor) {
        config = config.interceptors.requestInterceptor(config);
      }

      this.instance
        .request<any, T>(config)
        .then((res) => {
          if (config.interceptors?.responseInterceptor) {
            res = config.interceptors.responseInterceptor(res);
          }
          resolve(res);
        })
        .catch((err) => {
          reject(err);
        });
    });
  }

  get<T = any>(
    url: string,
    params?: any,
    config?: RequestConfig<T>
  ): Promise<T> {
    return this.request<T>({ ...config, method: "GET", url, params });
  }

  post<T = any>(
    url: string,
    data?: any,
    config?: RequestConfig<T>
  ): Promise<T> {
    return this.request<T>({ ...config, method: "POST", url, data });
  }
  delete<T = any>(
    url: string,
    data?: any,
    config?: RequestConfig<T>
  ): Promise<T> {
    return this.request<T>({ ...config, method: "DELETE", url, data });
  }

  // 其他方法类似...
}

export default Request;
