"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports["default"] = _default;

var _index = _interopRequireDefault(require("../config/index"));

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

function getdata(data) {
  var text = "";

  for (var key in data) {
    text += key + "=" + data[key] + "&";
  }

  text ? text = "?" + text : "";
  text = text.replace(/&$/, "");
  return text;
}

function _default(ori) {
  var method = ori.method.toUpperCase();
  var baseurl = _index["default"].base[ori.urlType || "url"];
  var url = baseurl + ori.url;
  if (method === "GET") url += getdata(ori.data || {});
  if (ori.downCsv) return window.open(url);
  var d = {
    lock: true,
    background: "rgba(255, 255, 255, 0.7)"
  };
  ori.target && (d.target = ori.target);
  return new Promise(function (resolve, reject) {
    var xhttp;
    if (window.XMLHttpRequest) xhttp = new XMLHttpRequest();else if (window.ActiveXObject) xhttp = new window.ActiveXObject("Microsoft.XMLHTTP");
    xhttp.open(method, url, true);

    if (method === "POST") {
      xhttp.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
      xhttp.send(JSON.stringify(ori.data));
    } else {
      xhttp.send();
    }

    xhttp.onreadystatechange = function () {
      if (this.readyState != 4 || this.status != 200) return;
      var data = {};

      try {
        data = this.responseText !== "null" ? JSON.parse(this.responseText || "{}") : {};
      } catch (err) {
        console.error(err);
        reject(err);
      }

      data && data.response && (data = data.response);
      if (!ori.urlType && !data.status) return reject(data.message);
      resolve(data.data || data.response || data);
    };
  });
}