import axios, { AxiosRequestConfig } from "axios"
import { message } from "antd"
import { getAuth, getApiUrl } from "./tools"

const customAxios = axios.create({
  baseURL: getApiUrl(),
  timeout: 8000,
})
interface AxiosErrorInterface {
  message: string
  config: any
  response: any
}

customAxios.interceptors.request.use(
  (config: any) => {
    return config
  },
  (error: AxiosErrorInterface) => {
    return error
  }
)

customAxios.interceptors.response.use(
  (response: any) => {
    if (response.status !== 200) {
      response.data.message && message.error(response.data.message)
      return Promise.reject(response)
    }
    return Promise.resolve(response.data)
  },
  (error: AxiosErrorInterface) => {
    if (~`${error.message}`.indexOf("timeout")) {
      message.error("网络超时")
    }
    error.response &&
      error.response.data.message &&
      message.error(error.response.data.message)
    if (error.response && error.response.status === 401) {
      message.error("登录信息已过期，请重新登录")
    } else {
      error.response &&
        error.response.statusText &&
        message.error(error.response.data.message)
    }

    return Promise.reject(error)
  }
)

const baseRequest = (config: any): Promise<any> => {
  config = {
    ...config,
    headers: {
      Authorization: `${getAuth()}`,
    },
  }
  return customAxios.request(config)
}

export const get = (
  url: string,
  params?: object,
  config?: AxiosRequestConfig
) =>
  baseRequest({
    method: "get",
    params,
    url,
    ...config,
  })
export const post = (
  url: string,
  data?: object,
  config?: AxiosRequestConfig
) => {
  return baseRequest({
    data,
    method: "post",
    url,
    ...config,
  })
}
export const patch = (
  url: string,
  data: object,
  config?: AxiosRequestConfig
) => {
  return baseRequest({
    data,
    method: "patch",
    url,
    ...config,
  })
}
export const put = (
  url: string,
  data?: object,
  config?: AxiosRequestConfig
) => {
  return baseRequest({
    data,
    method: "put",
    url,
    ...config,
  })
}
export const remove = (
  url: string,
  data?: object,
  config?: AxiosRequestConfig
) => {
  return baseRequest({
    data,
    method: "delete",
    url,
    ...config,
  })
}
