import axios from 'axios'
import router from '@/router'
import { Message } from 'element-ui'

import BASE_URL from '../config/env'
import store from '@/store/index.js'

// 创建axios实例
const service = axios.create({
  baseURL: BASE_URL().baseUrl // api的base_url
  // timeout: 5000 // 请求超时时间
})

// request拦截器
service.interceptors.request.use(config => {
  if (localStorage.mgt_token && config.url.indexOf('upload') < 0) { // 判断是否存在token，如果存在的话，则每个http header都加上token
    config.headers.ClearAuthToken = localStorage.mgt_token
  }
  return config
}, error => {
  // Do something with request error
  console.log(error) // for debug
  Promise.reject(error)
})

// respone拦截器
service.interceptors.response.use(response => {
  /**
  * code为非20000是抛错 可结合自己业务进行修改
  */
  // console.log(response)
  const code = response.data.resCode
  if (code) {
    if (code !== 200) {
      Message({
        message: response.data.errInfo,
        type: 'error'
      })
      switch (code) {
        case 403:
        case 401:
          store.dispatch('FedLogOut').then(() => {
            router.push('/login')
            location.reload()// In order to re-instantiate the vue-router object to avoid bugs
          })
          break
        default:
          return Promise.reject(new Error(response.data))
      }
    } else {
      return response.data
    }
  } else {
    if (typeof response.data === 'object') {
      return response.data
    } else {
      let errInfo
      if (response.data.trim() === 'access denied') {
        errInfo = '您无权访问，请登录'
        store.dispatch('FedLogOut').then(() => {
          router.push('/login')
        })
      } else {
        errInfo = response.data
      }
      Message({
        message: errInfo,
        type: 'error'
      })
      return Promise.reject(new Error(response.data))
    }
  }
}, error => {
  console.log(error)// for debug
  Message({
    message: '服务器出错了T_T',
    type: 'error'
  })
  return Promise.reject(error)
})

export default service
