import axios from 'axios'
import { Notification } from 'element-ui'
import { getToken } from '@/utils/auth'
import Config from '@/settings'

// 使请求头可以携带cookie
axios.defaults.withCredentials = true;

// 创建axios实例
const service = axios.create({
	baseURL: process.env.VUE_APP_LOCAL_API + '/',
	timeout: Config.timeout // 请求超时时间
})

// request拦截器
service.interceptors.request.use(
  config => {
    if (getToken()) {
      config.headers['Authorization'] = getToken() // 让每个请求携带自定义token 请根据实际情况自行修改
    }
    config.headers['Content-Type'] = 'application/json'
    return config
  },
  error => {
    Promise.reject(error)
  }
)

// response 拦截器
service.interceptors.response.use(
  response => {
    return response.data
  },
  error => {
    if (error.response.status) {
      const responseCode = error.response.status

      switch (responseCode) {
        case 400:
          // Message.error('操作失败');

          break

          //  token 过期
        case 401:
			Notification({
				title: '登录过期，请重新登录',
				duration: 2000,
				type: 'warning'
			})

			setTimeout(() => {
				window.localStorage.removeItem('token')
				window.location = '#/';
				location.reload()
			}, 1000)

			break

        default:
          break
      }
      return error.response.data
    }
  }
)
export default service
