/**
 * @file Axios的Vue插件（添加全局请求/响应拦截器）
 */
import {DEVICE_TYPE, REQUEST_URL} from './config'
import axios from 'axios'
import UAParser from 'ua-parser-js'

// 获得操作系统版本
let parser = new UAParser()

const axiosObj = axios.create({
  baseURL: REQUEST_URL,
  headers: {
    'Content-Type': 'application/json;charset=UTF-8',
    'Device-Type': DEVICE_TYPE,
    'Suppress-Response-Code': '1',
    'Device-Info': 'System:'+parser.getOS().name+'; Version:'+parser.getOS().version+'; NetworkType:; UUID:;',
  },
})

// 拦截request,设置全局请求为ajax请求
axiosObj.interceptors.request.use((config) => {
  //config.headers['X-Requested-With'] = 'XMLHttpRequest';

  return config

})

// 拦截响应response，并做一些错误处理
axiosObj.interceptors.response.use((response) => {
  const responseData = response.data
  const data = responseData.data

  if (responseData.success === false) {
    const err = new Error(data.message)
    err.data = data
    err.message = data.message
    err.response = response
    throw err
  } else {
    return data
  }
}, (err) => { // 这里是返回状态码不为200时候的错误处理
  if (err && err.response) {
    switch (err.response.status) {
      case 400:
        err.message = '请求错误'
        break
      case 401:
        err.message = '未授权，请登录'
        break
      case 403:
        err.message = '拒绝访问'
        break
      case 404:
        err.message = `请求地址出错: ${err.response.config.url}`
        break
      case 408:
        err.message = '请求超时'
        break
      case 500:
        err.message = '服务器内部错误'
        break
      case 501:
        err.message = '服务未实现'
        break
      case 502:
        err.message = '网关错误'
        break
      case 503:
        err.message = '服务不可用'
        break
      case 504:
        err.message = '网关超时'
        break
      case 505:
        err.message = 'HTTP版本不受支持'
        break
      default:
    }
  }

  return Promise.reject(err)
})

export default axiosObj
