import axios from 'axios'
import router from '../router'

const request = axios.create({
  withCredentials: true,
  baseURL: process.env.API_DOMAIN,
  timeout: 50000,
  headers: {
    'Content-Type': 'application/json;charset=UTF-8'
  }
})

// Add a request interceptor
request.interceptors.request.use(request => {
  const requestUrl = request.url
  // Do something before request is sent
  request.url = requestUrl + (requestUrl.indexOf('?') > -1 ? '&' : '?') + 'next=' + encodeURIComponent(location.href)
  return request
}, error => {
  // Do something with request error
  return Promise.reject(error)
})

// Add a response interceptor
request.interceptors.response.use(response => {
  // Do something with response data
  const { code, authorizeUrl } = response.data
  if (code === 301 && authorizeUrl) {
    location.replace(authorizeUrl)
  } else if (code === 403) {
    router.push('/partner/login')
  }
  return response.data
}, (error) => {
  // Do something with response error
  return Promise.reject(error)
})

export default request
