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


var instance = axios.create({
  baseURL: process.env.NODE_ENV === 'production' ? 'http://temu.jjcp52.com' : 'http://temu.jjcp52.com',
  timeout: 50000,
  validateStatus: function (status) {
    return status < 500
  }
})

instance.interceptors.request.use(request => {
  if (!request.withoutToken && !request.headers.Authorization) {
    request.headers.Authorization = store.state.token || ''
  }

  return request
})

instance.interceptors.response.use(
  (response) => {
    if (response.data.code === 401 || response.data.code === 403) {
      Message.error('登录失效，请重新登录')
      store.dispatch('SignOut', true)

      return response.data
    } else if (response.data.code === 1 && response.data.msg) {
      Message.error(response.data.msg)
    } else {
      return response.data
    }
  },
  (err) => {
    console.log(err)
    Message.error('后台报错啦！请联系管理员')
    return err
  }
)

export default instance
