import axios from 'axios'
import { Message } from 'element-ui'
import store from '@/store'
import { getToken } from '@/utils/auth'

const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // baseURL
  timeout: 56789 // 超时时间
})

service.interceptors.request.use(config => { // 请求拦截器
  if (store.getters.token) {
    config.headers.Authorization = 'Bearer ' + getToken()
  }
  return config
}, error => {
  console.log(error) // 打印错信息
  return Promise.reject(error)
})

// 响应拦截
service.interceptors.response.use(
  response => {
    const res = response.data

    // code不为200,请求错误
    if (res.code !== 200) {
      Message({
        message: res.msg || 'Error',
        type: 'error',
        duration: 5 * 1000
      })

      // 400112登录过期
      if (res.code === 50000) {
        // 重新登录
        Message.error('token过期,请重新登陆')
        store.dispatch('user/resetToken').then(() => {
          location.reload()
        })
      }
      return Promise.reject(new Error(res.message || 'Error'))
    } else {
      return res
    }
  },
  error => {
    let message = ''
    let code = null
    try {
      const { msg, status_code } = error.response.data
      message = msg
      code = status_code
    } catch (e) {
      message = error.msg
    }

    if (code) {
      switch (code) {
        case 405:
          console.log(405)
          break
        // case 422:
        //   // 重新登录
        //   Message.error('token过期,请重新登陆')
        //   store.dispatch('user/resetToken').then(() => {
        //     location.reload()
        //   })
        //   break
        default:
          console.log('other' + code)
      }
    }

    console.log('err' + error) // for debug
    Message({
      message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

export default service

