import axios from 'axios'
import Qs from 'qs'
import store from '@/store'
import { showError } from '@/util'

let host = ''
if (window.location.port === '3000') {
  host = '//localhost:1024/'
}else if (window.location.host.match('test')) {
  host = '//test-api-hr.duowan.com'
} else{
  host = '//api-hr.duowan.com'
}

let ax = axios.create({
  baseURL: host,
  headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
  transformRequest: [
    function (data, headers) {
      data = Qs.stringify(data)
      return data
    }
  ],
  transformResponse: [],
  withCredentials: true
})

ax.host = host

ax.interceptors.request.use(
  config => {
    let param = config.method === 'post' ? config.data : config.params
    if (param && param.needAuth) {
      if (!(store.userId && store.token)) {
        showError('登录态失效，请重新登录')
        store.logout()
        return Promise.reject('请先登录')
      } else {
        store.userId && (param.userId = store.userId)
        param.token = store.token
        delete param.needAuth
      }
    }
    // 在发送请求之前做些什么
    return config
  },
  error => {
    // 对请求错误做些什么
    return Promise.reject(error)
  }
)

// 拦截器处理错误
ax.interceptors.response.use(
  response => {
    if (response.data.code === 0) {
      return Promise.resolve(response.data)
    } else if (response.data.code === -5) {
      showError(response.data.msg)
      store.logout()
    } else {
      return Promise.reject(new Error(response.data.msg))
    }
  },
  error => {
    return Promise.reject(error)
  }
)

export default ax
