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

// request interceptor
service.interceptors.request.use(
  function(config) {
    var token = getToken()
    if (token === '' || token === null || token === 'undefined') {
      return config
    }else {
      config.headers.token = getToken()
      return config
    }
  },
  function(error) {
    // 对请求错误做些什么
    return Promise.reject(error)
  }
)

// 添加响应拦截器 => 后端给前端的数据【后端返回给前端的东西】
service.interceptors.response.use(
  function(response) {
    // 对响应数据做点什么
    const newToken = response.config.headers.token
    setToken(newToken)
    if (response.data.code === 401) {
      removeToken()
      popmessage({ type: 'error', str: '登陆已过期，请重新登录' })
      this.$router.push('/loginView')
      setTimeout(() => {
        this.$router.go(0)
      }, 1000)
    }
    return response
  },
  function(error) {
    // 对响应错误做点什么

    return Promise.reject(error)
  }
)

export default service
