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

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

// 创建axios实例
const service = axios.create({
	//baseURL: 'http://139.129.118.36:3040/',
	//baseURL: 'http://192.168.3.226:3040/',
	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 => {
	//console.log(error.response);

    if (error.response.status) {
      const responseCode = error.response.status

      switch (parseInt(responseCode)) {
        case 400:
          Message({
            message: error.response.data.message,
            type: 'warning'
          });
          break

        //  token 过期
        case 401:
          Notification({
            title: '登录过期，请重新登录',
            duration: 2000,
            type: 'warning'
          })
          setTimeout(() => {
            window.localStorage.removeItem('token')
            window.location = '#/';
			      location.reload()
          }, 3000)
          break

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