import { UUID } from 'amos-tool';
/*
* 图片的绝对路径地址 转换成base64编码 如下代码：
*/
const getBase64Image = img => {
  let canvas = document.createElement('canvas');
  canvas.width = img.width;
  canvas.height = img.height;
  let ctx = canvas.getContext('2d');
  ctx.drawImage(img, 0, 0, img.width, img.height);
  let ext = img.src.substring(img.src.lastIndexOf('.') + 1).toLowerCase();
  let dataURL = canvas.toDataURL('image/' + ext);
  return {
    dataURL,
    type: 'image/' + ext
  };
};

const convertBase64UrlToFile = (base64, filename) => {
  let urlData = base64.dataURL;
  let type = base64.type;
  let mime = type.split('/')[1];
  let bytes = window.atob(urlData.split(',')[1]); //去掉url的头，并转换为byte
  //处理异常,将ascii码小于0的转换为大于0
  let ab = new ArrayBuffer(bytes.length);
  let ia = new Uint8Array(ab);
  for (var i = 0; i < bytes.length; i++) {
    ia[i] = bytes.charCodeAt(i);
  }
  return new File([ia], filename, { type: mime });
};

export const getBase64 = file => {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => resolve(reader.result);
    reader.onerror = error => reject(error);
  });
};

export const convertImgUrlToFile = (imgUrl, filename, callBack) => {
  let image = new Image();
  image.crossOrigin = '';
  image.src = imgUrl;
  image.onload = function() {
    let base64 = getBase64Image(image);
    let file = convertBase64UrlToFile(base64, filename);
    file.uid = UUID.uuidFast();
    file.url = imgUrl;
    callBack(file);
  };
};
