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

axios.defaults.withCredentials = true

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.defaults.withCredentials = true
// httpRequest.defaults.headers.tenant = 'sofia'
// httpRequest.defaults.headers.token = localStorage.getItem('token') || ''

// 请求拦截
httpRequest.interceptors.request.use(
  function(config) {
    config.headers.token = localStorage.getItem('token') || ''
    config.headers.tenant = 'sofia'

    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) {
        router.replace({
          path: '/login',
          query: { redirect_uri: encodeURIComponent(window.location.href) }
        })
      }
    } else {
      Notify(error)
    }
    return Promise.reject(error)
  }
)

export default httpRequest
