export const base64ToFile = (dataUrl: string, name?: string) => {
  const arr: string[] = dataUrl.split(',');
  // const mime = arr[0].match(/:(.*?);/)[1];
  const bstr: string = atob(arr[1]);
  let n = bstr.length;
  const u8arr = new Uint8Array(n);
  while (n--) {
    u8arr[n] = bstr.charCodeAt(n);
  }
  return new File([u8arr], `${name}.png`, { type: 'image/png' });
};
export const urlToBase64 = (url: string) => {
  return new Promise((resolve) => {
    const timeStamp = new Date().getTime();
    // 通过构造函数来创建的 img 实例，在赋予 src 值后就会立刻下载图片，相比 createElement() 创建 				<img> 省去了 append()，也就避免了文档冗余和污染
    const Img = new Image();
    // 处理缓存,fix缓存bug,有缓存，浏览器会报错;
    Img.src = `${url}?${timeStamp}`;
    // 解决控制台跨域报错的问题
    Img.crossOrigin = 'Anonymous';
    // 获取后缀
    const ext = Img.src.substring(Img.src.lastIndexOf('.') + 1).toLowerCase();
    Img.onload = () => {
      // 要先确保图片完整获取到，这是个异步事件
      const canvas: any = document.createElement('canvas'); // 创建canvas元素
      // 确保canvas的尺寸和图片一样
      canvas.width = Img.width;
      canvas.height = Img.height;
      // 将图片绘制到canvas中
      canvas.getContext('2d').drawImage(Img, 0, 0, Img.width, Img.height);
      // 转换图片为dataURL
      resolve(canvas.toDataURL(`image/${ext}`));
    };
  });
};
// 过滤对象属性
export const filterObjAttr = (obj: any, key: string[]) => {
  return Object.keys(JSON.parse(JSON.stringify(obj))).reduce((pre: any, cur: string) => {
    if (!key.includes(cur)) {
      pre[cur] = obj[cur];
    }
    return pre;
  }, {});
};
