import axios from 'axios'
import { Message } from 'element-ui'
import { serverUrl, devServerUrl } from '@/settings'

const baseURL = process.env.NODE_ENV === 'development' ? devServerUrl : serverUrl

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

// let loadingInstance = null

// request interceptor
service.interceptors.request.use(
  config => {
    // loadingInstance = Loading.service({ fullscreen: true })
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  response => {
    // loadingInstance.close()
    const res = response.data
    return res
    // if (res.code !== 200) {
    //   if (res.code === 401) {
    //     // to re-login
    //     MessageBox.confirm('登录失效，请重新登录！', '温馨提示！', {
    //       confirmButtonText: '确认',
    //       cancelButtonText: '取消',
    //       type: 'warning'
    //     }).then(() => {
    //       store.dispatch('user/resetToken').then(() => {
    //         location.reload()
    //       })
    //     })
    //   } else {
    //     Message({
    //       message: res.msg || 'Error',
    //       type: 'error',
    //       duration: 3 * 1000
    //     })
    //   }
    //   return Promise.reject(new Error(res.message || 'Error'))
    // } else {
    //   return res
    // }
  },
  error => {
    // loadingInstance.close()
    Message({
      message: error.message || 'Error',
      type: 'error',
      duration: 3 * 1000
    })
    return Promise.reject(error)
  }
)

export default service
