import Axios from 'axios'
// @ts-ignore
import qs from 'qs'
import { isUndefined } from 'lodash'
import axiosResponse from './axios-response'
import { getStore } from './storage'

const baseURL = '/webapi'

const axios = Axios.create({
  timeout: 20000, // 请求超时 20s
  paramsSerializer(params) {
    return qs.stringify(params, { arrayFormat: 'repeat' })
  }
})

// 前置拦截器（发起请求之前的拦截）
axios.interceptors.request.use(
  (request) => {
    if (request.url && !request.url.startsWith(baseURL) && !request.url.startsWith('http')) {
      request.url = baseURL + (request.url.startsWith('/') ? request.url : `/${request.url}`)
    }
    // request.headers.secret = encrypt(new Date().getTime().toString())
    const token = getStore('token')
    if (token) {
      request.headers.Authorization = `Bearer ${token}`
    }
    return request
  },
  (error) => Promise.reject(error)
)

// 后置拦截器（获取到响应时的拦截）
axios.interceptors.response.use((response) => {
  if (response.status === 200) {
    if (response.config.responseType === 'blob') {
      return Promise.resolve(response)
    }
    if (isUndefined(response.data.code)) {
      return Promise.resolve(response.data)
    }
    if (response.data.code !== 0) {
      return axiosResponse(response)
    }
    if (response.data.code === 0) {
      return Promise.resolve(response.data.data)
    }
    return Promise.resolve(response.data)
  }
  return axiosResponse(response)
}, axiosResponse)

export default axios
