import axios from 'axios'
import { Loading, Message } from 'element-ui'
import storage from '@/utils/storage'

const instance = axios.create({
  baseURL: process.env.VUE_APP_BASE_API,
  timeout: 5000
})

let loadingInstance

instance.interceptors.request.use(
  config => {
    const hasToken = storage.ss.get('vue_template_token')
    if (hasToken) {
      config.headers['Authorization'] = 'Bearer ' + hasToken
    }
    loadingInstance = Loading.service({
      lock: true,
      text: '数据加载中，请稍后...',
      spinner: 'el-icon-loading',
      background: 'rgba(0, 0, 0, 0.7)'
    })
    return config
  },
  error => {
    loadingInstance.close()
    Message.error('请求错误')
    return Promise.reject(error)
  }
)

instance.interceptors.response.use(
  response => {
    loadingInstance.close()
    const code = response.data.code || 200
    if (code === 401) {
      // 重新登陆
      console.log('重新登陆')
      Message.warning('重新登陆')
    } else if (code === 403) {
      // 无权限
      console.log('无权限')
      Message.warning('无权限')
    } else if (code === 500) {
      // 系统错误
      Message.error(response.data.msg || '系统错误')
      return Promise.reject(new Error(response.data.msg))
    } else {
      return response.data
    }
  },
  error => {
    loadingInstance.close()
    Message.error(error.message)
    return Promise.reject(error)
  }
)

export default instance
