/**
 * axios全局配置
 * TODO: 拦截器全局配置，根据实际情况修改
 */
import axios from 'axios'
import router from '../router'
import {
  Message
} from 'element-ui'
import {
  Auth
} from '@/util/auth'
// import {Encrypt} from '../util/secret'

// const CancelToken = axios.CancelToken

// 超时设置
const service = axios.create({
  // 请求超时时间
  timeout: 30000,
  baseURL: process.env.NODE_ENV === 'production' && process.env.BASE_API ? process.env.BASE_API : '',
})

// http request 拦截器
// 每次请求都为http头增加token字段，其内容为token
service.interceptors.request.use(
  config => {
    if (Auth.getLoginInfo()) {
      config.headers['token'] = Auth.getLoginInfo()
    }
    return config
  },
  err => {
    return Promise.reject(err)
  }
)

// http response 拦截器
service.interceptors.response.use(
  response => {
    return Promise.resolve(response.data)
  },
  error => {
    if (error.response) {
      switch (error.response.msg) {
        case 401:
          Message({
            message: '认证失败，请重新登录！',
            type: 'error'
          })
          store.dispatch('clearStore')
          router.push('/login')
          break
        case 403:
          router.push('error/403')
          break
        case 404:
          router.push('error/404')
          break
        default:
          Message({
            message: `服务器错误!`,
            type: 'error'
          })
      }
      return Promise.reject(error.response.data)
    }
  }
)

export default service
