import axios from 'axios'
import { message } from '@/utils/resetMessage';
import store from '@/store'
import { getToken, getRequestId } from '@/utils/auth'

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

// request interceptor
service.interceptors.request.use(
  config => {
    if (store.getters.token) {
      config.headers['Authorization'] = getToken()
    }
    config.headers['x-request-id'] = getRequestId()
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  response => {
    if (response.data) {
      const { success } = response.data
      // 判断当前请求是否成功
      if (success === true) {
        // 返回成功后解析数据
        return response.data
      } else if (success === false) {
        message({
          message: response.data.message || '操作失败',
          type: 'error',
          duration: 5 * 1000
        })
        return Promise.reject(new Error(message))
      }
       else {
        return response
      }
    } else {
      return response
    }

  },
  error => {
    console.log('失败', error.response)
    if (
      error.response &&
      (error.response.status == 401 ||
        error.response.status == 502)
    ) {
      store.dispatch('user/logout').then(() => {
        location.reload()
      })
      message({
        message: '请重新登录!',  //error.message
        type: 'error',
        duration: 5 * 1000
      })
    }
    return Promise.reject(new Error(error))
  }
)

export default service
