import axios, { type AxiosRequestConfig, AxiosResponse } from 'axios'
import { AXIOS_DEFAULT_CONFIG } from 'Config/index'

import { requestSuccessFunc, requestFailFunc, responseSuccessFunc, responseFailFunc } from 'Config/interceptors/axios'

// 创建axios实例
const axiosInstance = axios.create(AXIOS_DEFAULT_CONFIG)

// 注入请求拦截
axiosInstance.interceptors.request.use(requestSuccessFunc, requestFailFunc)
// 注入失败拦截
axiosInstance.interceptors.response.use(responseSuccessFunc, responseFailFunc)

const request = {
  async get(url: string, data?: RequestOptions, config?: AxiosRequestConfig): Promise<AxiosResponse> {
    return axiosInstance.request({
      headers: {'X-Access-Token': localStorage.getItem('token')},
      ...config,
      url,
      method: 'GET',
      params: data,
    })
  },
  async post(url: string, data?: RequestOptions, config?: AxiosRequestConfig): Promise<AxiosResponse> {
    return axiosInstance.request({
      headers: {'X-Access-Token': localStorage.getItem('token')},
      ...config,
      url,
      method: 'POST',
      data,
    })
  },
  async delete(url: string, data?: RequestOptions, config?: AxiosRequestConfig): Promise<AxiosResponse> {
    return axiosInstance.request({
      headers: {'X-Access-Token': localStorage.getItem('token')},
      ...config,
      url,
      method: 'DELETE',
      data,
    })
  },
  async put(url: string, data?: RequestOptions, config?: AxiosRequestConfig): Promise<AxiosResponse> {
    return axiosInstance.request({
      headers: {'X-Access-Token': localStorage.getItem('token')},
      ...config,
      url,
      method: 'PUT',
      data,
    })
  },
}

export default request

