import axios from 'axios'
// import { MessageBox,Message } from 'element-ui'
import { Message } from 'element-ui'
import store from '@/store'
import { getToken } from '@/utils/auth'

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

// request interceptor
service.interceptors.request.use(
  config => {
    // do something before request is sent
    if (store.getters.token) {
      config.headers['Authorization'] = 'Bearer ' + getToken()
    }
    config.headers['Req-Version'] = 'v2'
    config.headers['Req-Client'] = 'Ops'
    return config
  },
  error => {
    // do something with request error
    console.error(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
   */

  /**
   * 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 (response.status !== 200) {
      if (res.errorCode !== 0) {
        Message({
          message: `[${response.status}]` + (res.errorMsg || 'Error'),
          type: 'error',
          duration: 5 * 1000
        })
      }
      return Promise.reject(new Error(res.message || 'Error'))
    }

    if (res.errorCode !== 0 && !(res instanceof Blob)) {
      Message({
        message: res.errorMsg || 'Error',
        type: 'error',
        duration: 5 * 1000
      })
      return Promise.reject(new Error(res.message || 'Error'))
    }

    return res
  },
  error => {
    console.error('err:', error) // for debug

    if (error.config.messageAlert === false) {
      return Promise.reject(error)
    }

    if (error.code === 'ECONNABORTED') {
      console.error('请求超时，请刷新后重试')
      return Promise.reject(error)
    }

    const resData = error.response.data || {}
    if (resData.errorCode === 401) {
      store.dispatch('user/resetToken').then(() => {
        location.reload()
      })
      return Promise.reject(error)
    }

    // if (error.response.status === 504) {
    //   return Promise.reject(error)
    // }

    let message = resData.errorMsg || error.message
    if (resData.errorCode < 600) {
      message = `[${resData.errorCode}] ${message}`
    }
    Message({
      message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

export default service
