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

// create an axios instance
const service = axios.create({
  baseURL: '',
  timeout: 10000 // request timeout
})


// request interceptor
service.interceptors.request.use(
  config => {
    // do something before request is sent
    config.headers['Content-Type'] = 'application/x-www-form-urlencoded'
    return config
  },
  error => {
    // do something with request error
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
  */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  response => {
    const res = response.data
    // if the custom code is not 20000, it is judged as an error.
    if (res.code === 1010) {
      Message({
        message: res.message || 'Error',
        type: 'error',
        duration: 5 * 1000,
        showClose: true
      })
      return Promise.reject(new Error(res.message || 'Error'))
    } else if (res.code === 1011) {
      Message({
        message: '登录已经失效,请先登录!',
        type: 'error',
        duration: 2 * 1000,
        showClose: true
      })
      setTimeout((function () {
        window.location.href = res.data
      }), 2000)
    } else if (res.code === 1012) {
      Message({
        message: res.message,
        type: 'error',
        duration: 5 * 1000,
        showClose: true
      })
    } else {
      return res
    }
  },
  error => {
    if (error.response && error.response.status === 401) {
      Message({
        message: '登录已经失效!',
        type: 'error',
        duration: 5 * 1000,
        showClose: true
      })
      // setTimeout(removeToken(), 2000)
      // setTimeout(router.push('/login'), 1000)
    }
    return Promise.reject(error)
  }
)


export default service
