import axios from 'axios'
// 创建axios实例
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  withCredentials: true, // send cookies when cross-domain requests
  method: 'post', // request method
  timeout: 5000 // request timeout
})

// 添加请求拦截器
service.interceptors.request.use(config => {
  // 在发送请求之前做些什么
  if (config.url === '/upload') {
    console.log()
  } else {
    console.log()
  }
  return config
}, error => {
  // 对请求错误做些什么
  return Promise.reject(error)
})

// 添加响应拦截器
service.interceptors.response.use(response => {
  // 对响应数据做点什么
  return response
}, error => {
  // 对响应错误做点什么
  const rsp = { errors: [] }
  if (!error.response) {
    rsp.errors.push({ message: error.message })
  } else {
    switch (error.response.status) {
      case 401:
        rsp.errors.push({ message: '未授权，请登录(401)' })
        break
      case 403:
        rsp.errors.push({ message: '拒绝访问(403)' })
        break
      case 404:
        rsp.errors.push({ message: '请求地址错误(404)' })
        break
      case 408:
        rsp.errors.push({ message: '请求超时(408)' })
        break
      case 500:
        rsp.errors.push({ message: '服务器内部错误(500)' })
        break
      case 501:
        rsp.errors.push({ message: '服务未实现(501)' })
        break
      default:
        rsp.errors.push({ message: '请求错误(' + error.response.status + ')' })
        break
    }
  }
  return Promise.reject(rsp)
})
export function jsonRequest(config) {
  return service.request({
    params: {
      method: config.method
    },
    url: '/ajax',
    headers: { 'Content-Type': 'text/plain' },
    data: config.data
  }).then(response => {
    return Promise.resolve(response.data)
  }, response => {
    return Promise.resolve(response)
  })
}
export function fileRequest(config) {
  return service.request({
    url: '/upload',
    data: config.data,
    headers: { 'Content-Type': 'multipart/form-data' },
    onUploadProgress: progressEvent => {
      console.log((progressEvent.loaded / progressEvent.total * 100 | 0) + '%')
    }
  }).then(response => {
    return Promise.resolve(response.data)
  }, response => {
    return Promise.resolve(response)
  })
}

const ajax = {
  example: data => {
    return jsonRequest({
      method: 'ajax.example.example',
      data: data
    })
  },
  fileUpload: file => {
    const fd = new FormData()
    fd.append('file', file)
    return fileRequest({
      data: fd
    })
  },
}

export default ajax