/*
ajax请求函数模块
返回值: promise对象(异步返回的数据是: response.data)
 */
import axios from 'axios'
import storageUtils from "../../utils/storageUtils"

/*axios请求拦截器，给请求头添加授权*/
axios.interceptors.request.use(config => {
  config.headers.Authorization = storageUtils.getToken()
  return config
})

export default function ajax (url, data={}, type='GET',reqName) {

  return new Promise(function (resolve, reject) {
    // 执行异步ajax请求
    let promise
    if (type === 'GET') {
      // 准备url query参数数据
      let dataStr = '' //数据拼接字符串
      Object.keys(data).forEach(key => {
        dataStr += key + '=' + data[key] + '&'
      })
      if (dataStr !== '') {
        dataStr = dataStr.substring(0, dataStr.lastIndexOf('&'))
        url = url + '?' + dataStr
      }
      // 发送get请求
      promise = axios.get(url)
    } else if(type === 'POST'){
      // 发送post请求
      promise = axios.post(url, data)
    } else if(type === 'DELETE'){
      // 发送delete请求
      promise = axios.delete(url,{
        params:data
      })
    }

    promise.then(function (response) {
      // 成功了调用resolve()
      resolve(response.data)
    }).catch(function (error) {
      // 如果是登录请求失败
      if(reqName === 'login'){
        alert(`用户名或密码错误！`)
        return
      }
      alert(`请求出错了 ${error}`)
    })
  })
}
