import axios from 'axios'
import qs from 'qs'
import { Notify } from 'vant'
import router from '@/router'

const httpRequest = axios.create({
  baseURL: process.env.VUE_APP_BASE_API,
  timeout: 60000,
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded',
    tenant: 'sofia',
    token: localStorage.getItem('token')
  }
})

// 请求拦截
httpRequest.interceptors.request.use(
  function(config) {
    if (
      config.headers['Content-Type'] === 'application/x-www-form-urlencoded'
    ) {
      config.data = qs.stringify(config.data)
    }
    return config
  },
  function(error) {
    return Promise.reject(error)
  }
)

// 响应拦截
httpRequest.interceptors.response.use(
  function(response) {
    return response.data
  },
  function(error) {
    if (error.response) {
      const { status, message } = error.response.data
      if (status === 400) {
        Notify({ type: 'error', message: message })
      } else if (status === 403) {
        router.replace({
          path: '/login',
          query: { redirect_uri: encodeURIComponent(window.location.href) }
        })
      }
    } else {
      Notify({ type: 'error', message: error })
    }
    return Promise.reject(error)
  }
)

export default httpRequest
