"use strict";

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

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

var _vant = require("vant");

require("vant/lib/toast/style/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 baseurl = _index["default"].base[ori.urlType || "defaultURl"];
  var url = baseurl + ori.url;

  _vant.Toast.loading({
    message: '加载中...',
    forbidClick: true,
    duration: 0
  });

  return new Promise(function (resolve, reject) {
    var xhttp;
    if (window.XMLHttpRequest) xhttp = new XMLHttpRequest();else if (window.ActiveXObject) xhttp = new window.ActiveXObject("Microsoft.XMLHTTP");
    var method = ori.method.toUpperCase();
    if (method === "GET") url += getdata(ori.data || {});
    xhttp.open(method, url, true);
    xhttp.setRequestHeader("Content-type", ori.header ? ori.header.contentType || "application/json" : "application/json");
    method === "GET" ? xhttp.send() : xhttp.send(JSON.stringify(ori.data));

    xhttp.onreadystatechange = function () {
      if (this.readyState != 4) return;

      _vant.Toast.clear();

      if (this.status === 404) {
        (0, _vant.Toast)("请求失败 " + this.status);
        reject(this.status);
        return;
      }

      if (this.status != 200) {
        var t = JSON.parse(this.responseText || "{}");
        (0, _vant.Toast)(t.message || "请求失败 " + this.status);
        reject(t.message);
        return;
      }

      var data = {};

      try {
        data = this.responseText !== "null" ? JSON.parse(this.responseText || "{}") : {};
      } catch (err) {
        (0, _vant.Toast)("请求失败");
        console.error(err);
        reject(err);
      }

      if (data.code === 0) resolve(data.data);else {
        (0, _vant.Toast)(data.message || "请求失败");
        reject(data);
      }
    };
  });
}