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

// 创建axios基础设置
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: false, // 跨域发送cookie
  timeout: 300000 // 超时
})

// 请求拦截
service.interceptors.request.use(
  config => {
    // 不携带token白名单
    const whiteUrl = ['/api/admin/login']
    // 请求地址
    const url = config.url
    if (store.getters.token) {
      // 发送请求携带token
      if (whiteUrl.indexOf(url) === -1) {
        config.headers['authorization'] = 'Bearer ' + getToken()
      }
    }
    return config
  },
  error => {
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

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

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

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

    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: msg,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

export default service
