import qs from 'querystring';

export const getUA = window.navigator.userAgent.toLowerCase();

export const isIE = !!window.ActiveXObject || 'ActiveXObject' in window;

export const downloadFile = (url, params, t = 'a') => {
  let type = t;
  const baseURL = window.STATIC_ENV_CONFIG.API_PREFIX;
  const paramsUrl = qs.stringify(params);
  if (isIE) {
    type = 'iframe';
  }
  if (type === 'a') {
    const elink = document.createElement('a');
    elink.style.display = 'none';
    let href = baseURL + url;
    if (paramsUrl) href = `${href}?${paramsUrl}`;
    elink.href = href;
    elink.download = '下载';
    document.body.appendChild(elink);
    elink.click();
    document.body.removeChild(elink);
  } else if (type === 'iframe') {
    const iframe = document.createElement('iframe');
    const id = 'saveFileFrame';
    iframe.id = id;
    iframe.style.display = 'none';
    iframe.src = '';
    document.body.appendChild(iframe);
    setTimeout(function loadUrl() {
      let href = baseURL + url;
      if (paramsUrl) href = `${href}?${paramsUrl}`;
      iframe.contentWindow.location.href = href;
      document.body.removeChild(iframe);
    }, 50);
  } else if (type === 'nginx') {
    const elink = document.createElement('a');
    elink.style.display = 'none';
    elink.target = '_block';
    elink.href = `/staticfiles/${url}`;
    document.body.appendChild(elink);
    elink.click();
    document.body.removeChild(elink);
  }
};
