import axios from 'axios'
import { Message } from 'element-ui'
import store from '@/store'
import { getSsoToken, getToken } from '@/utils/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
  // timeout: 5000 // request timeout
})
// request interceptor
service.interceptors.request.use(
  config => {
    if (getToken()) {
      // 携带token
      config.headers[process.env.VUE_APP_TOKEN_KEY] = getToken()
    }
    if (getSsoToken()) {
      // 携带token
      config.headers.ssoToken = getSsoToken()
    }
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
  */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   * 开发环境使用mock.js并不能模拟http状态码，下面暂时使用业务的状态码
   */
  response => {
    const { status, data } = response
    if (status === 401 || status === 403) {
      // 没有登录或者没有权限
      store.dispatch('user/logout').then(() => {
        location.reload()
      })
    }

    return data
  },
  error => {
    console.error(error) // for debug
    if (error.response.status === 401 || error.response.status === 403) {
      Message({
        message: error.response.data.msg || '没有权限访问',
        type: 'error',
        duration: 5 * 1000
      })
      // 没有登录或者没有权限
      store.dispatch('user/logout').then(() => {
        location.reload()
      })
    } else {
      Message({
        message: error.response.data.msg || '请求失败,服务器开小差了',
        type: 'error'
      })
      return error.response.data
    }
  }
)

export default service
