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

const host = window.location.host
const domain = host.substring(0, host.indexOf('.')) || host.substring(0, host.indexOf(':'))
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)
  // 因为微信开发者工具重复授权，本地开发时写死
  if (/^(0|192|10|localhost)|(test$)/.test(domain)) {
    request.url += '&owner_open_id=o0wUBtDVDAvu3z1GRu58kv4_9DnI'
  }
  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
