import Request, { HttpRequestConfig, HttpResponse, HttpError } from '@/lib/luch-request/index'
import tool from '@/common/utils/tool'

// @ts-ignore
const baseUrl = import.meta.env.VITE_BASE_URL
const http = new Request()

/* 设置全局配置 */
http.setConfig((config: HttpRequestConfig): HttpRequestConfig => {
  config.header = { ...config.header }
  config.sslVerify = false
  config.baseURL = baseUrl
  return config
})

http.interceptors.request.use(
  async (config: HttpRequestConfig): Promise<HttpRequestConfig> => {
    config.header = { ...config.header }
    return config
  },
  (config: HttpRequestConfig): Promise<HttpRequestConfig> => {
    return Promise.reject(config)
  }
)

http.interceptors.response.use((response: HttpResponse): Promise<HttpResponse> => {
  if (response.statusCode == 500 || response.statusCode == 404 || response.statusCode == 403) {
    console.error(response)
    // @ts-ignore
    return tool.alert('网络错误，请稍后重试')
  }

  if (response.statusCode == 401 || response.data.code == 401) {
  }

  if (response.statusCode == 200) {
    return Promise.resolve(response)
  } else {
    return Promise.reject(response)
  }
}, (error: HttpError): Promise<HttpError> => {
  return Promise.reject(error)
})

export default http