import axios from 'axios'
import { Notification } from 'element-ui'
import { getToken } from '@/utils/auth'
import router from '../router'
import store from '../store'

const service = axios.create({
  baseURL: window.global.baseURL,
  timeout: 30000 // request timeout
})

// 添加请求拦截器
service.interceptors.request.use(
  config => {
    if (getToken()) {
      config.headers['Authorization'] = getToken() // 添加token
    }
    return config
  }
)

// 添加响应拦截器
service.interceptors.response.use(
  function(response) {
    // console.log(response, '========================》response')
    // dataAxios 是 axios 返回数据中的 data
    const dataAxios = response.data
    if (dataAxios.code === 0 || dataAxios.code === 99) {
      return dataAxios
    }
    if (dataAxios.code === 101011) {
      Notification({
        title: '失败',
        message: '登录失效,请重新登录',
        type: 'error'
      })
      setTimeout(() => {
        store.dispatch('user/logout')
          .then(() => {
            router.push(`/login`)
          })
      }, 500)
      // dataAxios.code === 101014 ||
    } else if (dataAxios.code === -1 || dataAxios.code === '-1') {
      Notification({
        title: '警告',
        message: dataAxios.msg,
        type: 'warning'
      })
      return Promise.reject(dataAxios)
    } else {
      Notification({
        title: '失败',
        message: dataAxios.msg,
        type: 'error'
      })
      return Promise.reject(dataAxios)
    }
  },
  function(error) {
    // 超出 2xx 范围的状态码都会触发该函数。
    // 对响应错误做点什么
    // console.log(error)
    return Promise.reject(error)
  }
)

export default service
