import axios from 'axios'
import { MessageBox, Message } from 'element-ui'

// create an axios instance
const service = axios.create({
  baseURL: '/', // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  // timeout: 5000 // request timeout
})

// request interceptor
service.interceptors.request.use(
  config => {
    return config
  },
  error => {
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  response => {
    const res = response.data||{}
    // if the custom code is not 200, it is judged as an error.
    if (res.code == 200 || res.code == 0) {
      return Promise.resolve(res  )
    } else if( res.code == 401){
      localStorage.removeItem('token')
      localStorage.removeItem('uid')
      return Promise.resolve( res )
    }else {
      Message({
        message: res.msg || 'Error',
        type: 'error',
        duration:  1000
      })
      return Promise.resolve( res )
    }
  },
  error => {
    return Promise.reject(error)
  }
)

export default service
