import config from "../config/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, fileName, call) {
  let method = (ori.method || 'get').toUpperCase();
  let baseurl = config.base[ori.urlType || "url"];
  let url = baseurl + ori.url;
  let xhttp;
  if(method === 'GET'){
    url +=  getdata(ori.data || {})
  }
  if (window.XMLHttpRequest) xhttp = new XMLHttpRequest();
  else xhttp = new window.ActiveXObject("Microsoft.XMLHTTP");
  xhttp.responseType = "blob";
  xhttp.open(method, url, true);
  if(method === "POST"){
    xhttp.send(JSON.stringify(ori.data));
    xhttp.setRequestHeader(
      "Content-Type",
      "application/json"
    );
  }else{
    xhttp.send();
  }
  xhttp.addEventListener(
    "progress",
    res => {
      console.log(res, (res.loaded / res.total) * 100);
    },
    false
  );
  xhttp.onreadystatechange = function() {
    if (this.readyState != 4 || this.status != 200) return;
    // 组装a标签
    let elink = document.createElement("a");
    // 设置下载文件名
    elink.download = fileName;
    elink.style.display = "none";
    elink.href = URL.createObjectURL(this.response);
    document.body.appendChild(elink);
    elink.click();
    document.body.removeChild(elink);
    call && call()
  };
}
