import axios from 'axios'
import { Message } from 'element-ui'
import store from '@/store'
import { getToken } from '@/utils/auth'
import router from '@/router'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style

NProgress.configure({ showSpinner: false }) // NProgress Configuration

// 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: 60000 // request timeout
})

// 请求拦截
service.interceptors.request.use(
  config => {
    NProgress.start()
    // 默认以application/json 格式传递参数
    config.headers['Content-Type'] = config.headers['Content-Type'] || 'application/json'
    // 只有以当 Content-Type === application/json 是对参数序列化
    if (config.headers['Content-Type'] === 'application/json') {
      config.data = JSON.stringify(config.data)
    }

    const token = getToken()
    if (token) {
      config.headers['X-Token'] = token
    }
    return config
  },
  error => {
    NProgress.done()
    return Promise.reject(error)
  }
)

// 响应拦截
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
   */
  response => {
    const res = response.data
    // token失效时
    if (res.code === -99) {
      Message({ message: '登录失效，请重新登录！', duration: 1500 })
      setTimeout(() => {
        store.dispatch('user/logout')
        store.dispatch('resetState')
        router.replace('/login')
      }, 500)
      NProgress.done()
      return Promise.reject(res)
      // 返回不成功
    } else if (res.code !== 0) {
      Message({
        message: res.msg || '操作失败了，请重试！',
        type: 'error',
        duration: 1500
      })
      NProgress.done()
      return Promise.reject(res)
    } else {
      NProgress.done()
      return res
    }
  },
  error => {
    console.log('错误：' + error) // for debug
    Message({
      message: error.message,
      type: 'error',
      duration: 500
    })
    NProgress.done()
    return Promise.reject(error)
  }
)

export default service
