import axios from 'axios'
import { Message } from 'element-ui'
// create an axios instance
const GraphApiService = axios.create({
  baseURL: 'https://pvapi.purplevineip.com/graphAPI/api/v1.0',
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 300000, // request timeout
  headers: {
    'Content-Type': 'application/json'
  }
})

// 請求攔截
GraphApiService.interceptors.request.use(
  confing => {
    return confing
  },
  error => {
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// 響應攔截
GraphApiService.interceptors.response.use(
  response => {
    const res = response.data
    if (
      res.type &&
      (res.type ===
        'application/vnd.openxmlformats-officedocument.wordprocessingml.document' ||
        res.type === 'application/zip')
    ) {
      return res
    }
    if (res.status !== 200) {
      // if the custom code is not 200, it is judged as an error.
      Message({
        message: res.message || 'Error',
        type: 'error',
        duration: 5 * 1000
      })

      return Promise.reject(new Error(res.message || 'Error'))
    } else {
      return res
    }
  },
  error => {
    console.log('err' + error) // for debug
    Message({
      message: error.message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)
export default GraphApiService
