import axios, {
  AxiosInstance,
  AxiosRequestConfig,
  InternalAxiosRequestConfig,
  AxiosResponse,
} from 'axios';
import { message } from 'ant-design-vue';

interface ResponseData {
  code: number;
  data: any;
  message: string;
}

class HttpRequest {
  private baseUrl: string;
  private timeout: number;
  private headers: any;
  private axiosInstance: AxiosInstance;

  constructor() {
    this.baseUrl = process.env.VUE_APP_BASE_URL || "";
    this.timeout = 5000;
    this.headers = {
      "Content-Type": "application/json;charset=UTF-8",
    };
    this.axiosInstance = axios.create({
      baseURL: this.baseUrl,
      timeout: this.timeout,
      headers: this.headers,
    });

    // 请求拦截器
    this.axiosInstance.interceptors.request.use(
      (config: InternalAxiosRequestConfig) => {
        const token = JSON.parse(localStorage.getItem("token") || '{}')
        if (token) {
          config.headers.Authorization = token;
        }
        return config;
      },
      (error) => {
        return Promise.reject(error);
      }
    );

    // 响应拦截器
    this.axiosInstance.interceptors.response.use(
      (response: AxiosResponse<ResponseData>) => {
        if (response.data.code === 0) {
          return response.data.data;
        } else {
          message.error(response.data.message);
          return Promise.reject(response.data.message);
        }
      },
      (error) => {
        message.error(error.message);
        return Promise.reject(error);
      }
    );
  }

  public request(config: AxiosRequestConfig): Promise<any> {
    return new Promise((resolve, reject) => {
      this.axiosInstance
        .request(config)
        .then((res) => {
          resolve(res);
        })
        .catch((err) => {
          reject(err);
        });
    });
  }

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

  public post(url: string, data?: any): Promise<any> {
    return this.request({
      method: "POST",
      url,
      data,
    });
  }

  public patch(url: string, data?: any): Promise<any> {
    return this.request({
      method: "PATCH",
      url,
      data,
    });
  }

  public put(url: string, data?: any): Promise<any> {
    return this.request({
      method: "PUT",
      url,
      data,
    });
  }

  public delete(url: string, params?: any): Promise<any> {
    return this.request({
      method: "DELETE",
      url,
      params,
    });
  }
}

const httpRequest = new HttpRequest();

export default httpRequest;
