import { BLOB_TYPE, ENMU_BLOB_TYPE } from '@/utils/constants';

export function getBlob(url) {
  return new Promise((resolve) => {
    const xhr = new XMLHttpRequest();
    xhr.open('GET', url, true);
    xhr.responseType = 'blob';
    xhr.onload = () => {
      if (xhr.status === 200) {
        resolve(xhr.response);
      }
    };
    xhr.send();
  });
}

export const downFile = ({ data, type = ENMU_BLOB_TYPE.XLS, fileName }) => {
  //
  const blob = new Blob([data], {
    type: BLOB_TYPE[type]
  });

  const a = document.createElement('a');
  a.href = URL.createObjectURL(blob);
  a.download = `${fileName}`;
  a.click();
  URL.revokeObjectURL(a.href);
  a.remove();
};

const developBaseUrl = '';

export const downFileWithDownloadUrl = ({ url, fileName }) => {
  //
  const a = document.createElement('a');
  a.href =
    window.location.host.indexOf('192.168.1') > -1 ||
    window.location.host.indexOf('localhost') > -1
      ? developBaseUrl + url
      : url;
  a.download = fileName;
  a.click();
  a.remove();
};

export const downloadImageWithUrl = ({ url, fileName }) => {
  if (!url) return;

  getBlob(url).then((res) => {
    if (res) {
      const link = document.createElement('a');
      link.style.display = 'none';
      link.download = fileName || 'file';
      link.href = URL.createObjectURL(res);
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
    }
  });
};

// base64转image
export function base64src(base64data, cb) {
  return new Promise((resolve, reject) => {
    const [, format, bodyData] =
      /data:image\/(\w+);base64,(.*)/.exec(base64data) || [];
    if (!format) {
      reject(new Error('ERROR_BASE64SRC_PARSE'));
    }
  });
}
