import axios from 'axios'
import qs from 'qs'
import { Notify } from 'vant'
import router from '@/router'
import { logout } from '@/api/account'
const httpRequest = axios.create({
  baseURL: process.env.VUE_APP_BASE_API,
  timeout: 60000,
  withCredentials: true,
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded'
    // tenant: 'sofia'
  }
})

// 请求拦截
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(message)
      } else if (status === 403) {
        logout().then(() => {
          router.replace({
            path: '/login',
            query: { redirect_uri: encodeURIComponent(window.location.href) }
          })
        })
      }
    } else {
      Notify(error)
    }
    return Promise.reject(error)
  }
)

export default httpRequest
