'use strict';

exports.__esModule = true;

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _axios = require('axios');

var _axios2 = _interopRequireDefault(_axios);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; } // require (PrototypeObject.js), 使用了isEmptyObject、params


// axios 默认配置
// axios.defaults.timeout = 5000
_axios2.default.defaults.headers.post['Content-Type'] = 'application/json;charset=UTF-8';

// response中提取result
function getResult(response) {
  var result = response.data || response;
  if (typeof result === 'string') {
    try {
      return JSON.parse(result);
    } catch (error) {
      console.log('result转换JSON失败' + error);
      return result;
    }
  }
  return result;
}

// 构建get请求参数, get请求需要把url和data拼接起来
function buildGetUrl(url, params) {
  if (!params || Object.isEmptyObject(params)) {
    return url;
  }
  if (typeof params === 'string') {
    return url + '?' + params;
  }
  if (Object.type(params) === 'json') {
    return url + '?' + Object.params(params);
  }
  return url;
}

// jsonp上传
function jsonp(url) {
  return new Promise(function (resolve, reject) {
    window.jsonCallBack = function (result) {
      resolve(result);
    };
    var JSONP = document.createElement('script');
    JSONP.type = 'text/javascript';
    JSONP.src = url + '&callback=jsonCallBack';
    document.getElementsByTagName('head')[0].appendChild(JSONP);
    setTimeout(function () {
      document.getElementsByTagName('head')[0].removeChild(JSONP);
    }, 500);
  });
}

// 表单上传
function formUpload(url, options) {
  return new Promise(function (resolve) {
    if (!options.file) {
      // file文件框
      console.warn('没有找到options.file, 无法上传');
      resolve({
        code: '0',
        message: '没有找到options.file, 无法上传'
      });
      return;
    }
    // 上传数据
    var formData = new FormData();
    formData.append('file', options.file.files[0]);
    // 发送请求
    var instance = _axios2.default.create({
      withCredentials: true
    });
    instance.post(url, formData).then(function (response) {
      resolve(getResult(response));
    }).catch(function (error) {
      if (Api.fail) Api.fail(error);
      return Promise.reject(error);
    });
  });
}

// 封装成Api类
var Api = {
  fail: function fail(error) {
    console.warn({ error: error });
  },
  setBaseURL: function setBaseURL(baseURL) {
    _axios2.default.defaults.baseURL = baseURL;
  },
  request: function request(url) {
    var params = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};

    var method = params.method,
        head = params.head,
        data = params.data,
        options = _objectWithoutProperties(params, ['method', 'head', 'data']);
    // 设置method


    if (method !== 'get' && method !== 'post' && method !== 'jsonp' && method !== 'upload' && method !== 'form-upload') method = 'get';
    // 如果是jsonp, 则其它参数都没有意义了
    if (method === 'jsonp') {
      return jsonp(url);
    }
    // 如果是上传文件
    if (method === 'upload') {
      return formUpload(buildGetUrl(url, data), options);
    }
    return (0, _axios2.default)(_extends({
      url: method === 'get' ? buildGetUrl(url, data) : url,
      method: method,
      headers: _extends({}, head),
      data: method === 'get' ? null : data
    }, options));
  },
  post: function post(url) {
    var params = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};

    return this.request(url, Object.assign({}, params, { method: 'post' }));
  },
  get: function get(url) {
    var params = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};

    return this.request(url, Object.assign({}, params, { method: 'get' }));
  },
  all: function all(requests) {
    var _this = this;

    // requests: [{url: '', params: {}}]
    var methods = requests.map(function (request) {
      return _this.request(request.url, request.params);
    });
    return _axios2.default.all(methods);
  },
  jsonp: function jsonp(url) {
    var params = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};

    return this.request(url, Object.assign({}, params, { method: 'jsonp' }));
  }

  // 响应拦截器
};_axios2.default.interceptors.response.use(function (response) {
  return getResult(response);
}, function (error) {
  if (Api.fail) Api.fail(error);
  return Promise.reject(error);
});

exports.default = Api;
module.exports = exports['default'];