import axios from 'axios'
// import { getToken } from '@/utils/auth'
// import { blobToJson } from '@/utils'
import qs from 'qs'
// import Vue from 'vue'
// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API,
  // baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 10000 // request timeout
})

// request interceptor
// 发送请求拦截器
service.interceptors.request.use(
  config => {
    // do something before request is sent
    // if (getToken()) {
    //   config.headers.token = getToken()
    // }
    // config.headers.token = getToken()
    return config
  },
  error => {
    // do something with request error
    // console.error(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
// 请求返回之后的拦截器
service.interceptors.response.use(
  response => {
    const res = response.data
    console.log(res)
    return res
  },
  error => {
    console.log('error', error)
    if (error?.response?.status === 400) {
      return Promise.reject(error.response.data.message)
    }
    return Promise.reject(error.message)
  }
)

// 请求方法
const http = {
  post (url, params) {
    return service.post(url, params, {
      transformRequest: [(params) => {
        return JSON.stringify(params)
      }],
      headers: {
        'Content-Type': 'application/json'
      }
    })
  },
  get (url, params) {
    return service.get(url, {
      params: params,
      paramsSerializer: (params) => {
        return qs.stringify(params)
      }
    })
  },
  formData (url, params) {
    return service.post(url, params, {
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
      }
    })
  },
  upload (url, params) {
    return service.post(url, params, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })
  },
  download (url, params) {
    return service.post(url, params, {
      // timeout: 10000,
      headers: {
        'Content-Type': 'application/json'
      },
      responseType: 'blob'
    })
  }
}
export default http
