import axios from 'axios'
import { getToken,removeToken } from './auth'
// create an axios instance
const serverConditionRequest  = axios.create({
  baseURL: 'http://jzmanagerweb.aiyangniu.net', // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 5000 // request timeout
})

// request interceptor
serverConditionRequest .interceptors.request.use(
  (config) => {
    // do something before request is sent
    var token = getToken()
    if (token === '' || token === null || token === 'undefined') {
      return config
    } else {
      config.headers.token = getToken()
      return config
    }
  },
  (error) => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

serverConditionRequest .interceptors.response.use(
  function(response) {
    // 对响应数据做点什么
    if (response.data.code === 401) {
      removeToken()
      popmessage({ type: 'error', str: '登陆已过期，请重新登录' })
      router.push('/login')
      setTimeout(() => {
        this.$router.go(0)
      }, 1000)
    }
    return response
  },
  function(error) {
    // 对响应错误做点什么

    return Promise.reject(error)
  }
)

export default serverConditionRequest
