
import axios from 'axios'
import store from '@/store'
import qs from 'qs'

// create an axios instance 创建实例
const service = axios.create({
  // baseURL: '', // url = base url + request url
  baseURL: '', // url = base url + request url
  timeout: 600000 // request timeout
})

// request interceptor 拦截
service.interceptors.request.use(
  config => {
    // do something before request is sent

    // if (store.getters.token) {
      // let each request carry token
      // ['X-Token'] is a custom headers key
      // please modify it according to the actual situation
      // config.headers['X-Token'] = getToken()
    // }
    if(config.method=='post'){
      config.data = qs.stringify(config.data)
    }
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    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
  */
  response => {
    const res = response.data

    // // if the custom errno is not 200, it is judged as an error.
    // if (res.errno !== 200) {
    //   // alert(res.msg)
    //   return Promise.reject(new Error(res.msg || 'Error'))
    // } else {
    //   // success
    //   return res
    // }
    return res
  },
  error => {
    // console.log('err' + error) // for debug
    // console.log(error.response.status)
    if(error.response.status == 400 || error.response.status == 409){
      alert(error.response.data.msg)
    }else{
      alert(error.message)
    }
    return Promise.reject(error)
  }
)

export default service