import axios from 'axios'
import router from '@/router'
import store from '@/store'
import { Message } from 'element-ui'

const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API || '',
  timeout: Number(process.env.VUE_APP_TIMEOUT) || 15000
})

// 请求拦截器
service.interceptors.request.use(
  config => {
    const token = localStorage.getItem('token')
    if (token) {
      config.headers['Authorization'] = token
    }
    return config
  },
  error => Promise.reject(error)
)

// 响应拦截器
service.interceptors.response.use(
  response => response.data,
  error => {
    if (error.response && error.response.status === 401) {
      store.dispatch('logout')
      if (router.currentRoute.path !== '/login') {
        router.push('/login')
      }
    } else {
      const msg = error.response && error.response.data && error.response.data.message
        ? error.response.data.message
        : error.message || '请求失败'
      Message.error(msg)
    }
    return Promise.reject(error)
  }
)

export default service
