import config from "../config/index.js";
import { Toast } from "vant";
import "vant/lib/toast/style/index";

function getdata(data) {
  let text = "";
  for (const key in data) {
    text += key + "=" + data[key] + "&";
  }
  text ? (text = "?" + text) : "";
  text = text.replace(/&$/, "");
  return text;
}

export default function (ori) {
  let baseurl = config.base[ori.urlType || "defaultURl"];
  let url = baseurl + ori.url;
  return new Promise((resolve, reject) => {
    var xhttp;
    Toast.loading({
      message: '加载中...',
      forbidClick: true,
      duration: 0
    });
    if (window.XMLHttpRequest) xhttp = new XMLHttpRequest();
    else if (window.ActiveXObject)
      xhttp = new window.ActiveXObject("Microsoft.XMLHTTP");
    let 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"
    );
    localStorage.token && xhttp.setRequestHeader("token", localStorage.token) 
    method === "GET" ? xhttp.send() : xhttp.send(JSON.stringify(ori.data));
    xhttp.onreadystatechange = function () {
      if (this.readyState != 4) return;
      Toast.clear()
      if (this.status != 200) return Toast("请求失败 " + this.status);
      let data = {};
      try {
        data = this.responseText || "";
        resolve(data);
      } catch (err) {
        Toast("请求失败");
        console.error(err);
        reject(err);
      }
    };
  });
}
