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) {
  let method = ori.method.toUpperCase();
  let baseurl = config.base[ori.urlType || 'url'];
  let url = baseurl + ori.url;
  if (method === 'GET') url += getdata(ori.data || {});
  if (ori.downCsv) return window.open(url);
  let d = {
    lock: true,
    background: 'rgba(255, 255, 255, 0.7)',
  };
  ori.target && (d.target = ori.target);
  return new Promise((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 (
      ori.headers &&
      xhttp.setRequestHeader &&
      typeof ori.headers === 'object'
    ) {
      // 存在header
      const keys = Object.keys(ori.headers);
      for (let i = 0; i < keys.length; i++) {
        const v = keys[i];
        xhttp.setRequestHeader(v, encodeURIComponent(ori.headers[v]));
      }
    }
    if (method === 'POST') {
      const isFrom = Object.prototype.toString
        .call(ori.data)
        .slice(8, -1)
        .toLowerCase();
      if (isFrom !== 'formdata') {
        xhttp.setRequestHeader(
          'Content-Type',
          'application/json;charset=UTF-8'
        );
        xhttp.send(JSON.stringify(ori.data));
      } else {
        xhttp.send(ori.data);
      }
    } else xhttp.send();
    xhttp.onreadystatechange = function () {
      if (this.readyState != 4) return;
      if (this.status != 200) return reject(this.status);
      let 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);
      if (ori.resType != 't200' && data.code) return reject(data);
      resolve(data.data || data.response || data);
    };
  });
}
