/**
 * 获取文件的base64字符串
 * @param {File} file 
 */

 const toBlob = canvas => new Promise(r => canvas.toBlob(r))

export const getDataURL = file => new Promise((resolve) => {
  const reader = new FileReader()
  reader.onload = (e) => {
    resolve(e.target.result)
  }
  reader.readAsDataURL(file)
})
/**
 * 压缩图片
 * @param {String} url 链接、base64
 * @param {Number} quality 质量
 */
export const compress = ({
  file,
  url,
  size
}) => new Promise((resolve) => {
  //   window.app.$toast.loading({
  //     mask: true,
  //     duration: 10000,
  //     className: 'longToast',
  //     message: '图片压缩中...'
  //   })
  let img = new Image()
  if (file) {
    getDataURL(file).then(res => {
      img.src = res;
    })
  } else {
    img.src = url
  }
  img.crossOrigin = 'Annoymous'
  const maxSize = size * 1024 * 1024;
  img.onload = async function () {
    let that = this;
    // 默认按比例压缩
    let w = that.width,h = that.height;
    //生成canvas
    let canvas = document.createElement('canvas');
    let ctx = canvas.getContext('2d');
    // 创建属性节点
    let anw = document.createAttribute("width");
    anw.nodeValue = w;
    let anh = document.createAttribute("height");
    anh.nodeValue = h;
    canvas.setAttributeNode(anw);
    canvas.setAttributeNode(anh);
    ctx.drawImage(that, 0, 0, w, h);
    let blob = await toBlob(canvas)
    while (blob.size > maxSize) {
      ctx.clearRect(0, 0, w, h);
      let rate = Math.sqrt(maxSize / blob.size * 0.95)
      w = w * rate
      h = h * rate
      anw.nodeValue = w
      anh.nodeValue = h
      ctx.drawImage(that, 0, 0, w, h);
      blob = await toBlob(canvas)
    }
    blob.name = 'image.png'
    let dataUrl = await getDataURL(blob)
    resolve({
      file: blob,
      url: dataUrl
    })
  }
})

/**
 * 将以base64的图片url数据转换为Blob
 * @param urlData
 *            用url方式表示的base64图片数据
 */
export const base64ToBlob = urlData => {
  var arr = urlData.split(','),
    mime = arr[0].match(/:(.*?);/)[1],
    bstr = atob(arr[1]),
    n = bstr.length,
    u8arr = new Uint8Array(n);
  while (n--) {
    u8arr[n] = bstr.charCodeAt(n);
  }
  return new Blob([u8arr], {
    type: mime
  });
}

/**
 * 将以base64的图片url数据转换为File
 * @param urlData
 *            用url方式表示的base64图片数据
 */
export const base64ToFile = urlData => {
  let bstr = atob(urlData),
    n = bstr.length,
    u8arr = new Uint8Array(n);
  while (n--) {
    u8arr[n] = bstr.charCodeAt(n);
  }
  return new File([u8arr], {
    type: 'image/png'
  });
}

/**
 * 链接转图片
 * @param {String} url 
 */
export const dataURLtoImage = url => new Promise(r => {
  let img = new Image()
  img.onload = () => {
    r(img)
  }
  img.src = url
})

/**
 * 图片转
 * @param {Image} image 
 */
export const imagetoFile = image => new Promise(r => {
  let cvs = document.createElement("canvas")
  let ctx = cvs.getContext('2d')
  cvs.width = image.width
  cvs.height = image.height
  ctx.drawImage(image, 0, 0, cvs.width, cvs.height)
  cvs.toBlob(r, 'image/jpeg', 1)
})
