import methods from "@/common/methodTool";
let num = 1;
let _resolve;
let _reject;

function getBase64Size(base64) {
  if (base64) {
    base64 = base64.split(",")[1].split("=")[0];
    var strLength = base64.length;
    var fileLength = strLength - (strLength / 8) * 2;
    return Math.floor(fileLength); // 向下取整
  } else {
    return null;
  }
}
//获得图片大小
function imageSizeIsLessLimitSize(imagePath, limitSize) {
  return new Promise((resolve, reject) => {
    wx.getFileSystemManager().getFileInfo({
      filePath: imagePath,
      success: (res) => {
        resolve(res.size);
      },
    });
  });
}

//主函数，默认限制大小2048kb即2mb,drawWidth是绘画区域的大小
//初始值传入为画布自身的边长（我们这是一个正方形的画布）
function getLessLimitSizeImage(imagePath, quality) {
  uni.compressImage({
    src: imagePath,
    quality: quality * 100,
    success: (res) => {
      console.log(res.tempFilePath, res, "压缩后");
      _resolve(res.tempFilePath);
    },
  });
}
function compressH5(url, quality) {
  let image = new Image();
  image.onload = function () {
    var canvas = document.createElement("canvas");
    canvas.width = image.width;
    canvas.height = image.height;
    var ctx = canvas.getContext("2d");
    ctx.drawImage(image, 0, 0, this.height, this.width); //压缩比例
    var base64 = canvas.toDataURL("image/jpeg", quality);
    _resolve(base64);
  };
  image.src = url;
  image.setAttribute("crossOrigin", "Anonymous");
  image.onerror = () => {
    _reject(new Error("zip error"));
  };
}
function myCompressImage(url, limitSize = 2048) {
  return new Promise(async (resolve, reject) => {
    _resolve = resolve;
    _reject = resolve;
    limitSize = limitSize * 1024;
    // 获得size
    if (typeof url == "string") {
      // base64
      if (methods.isBase64(url)) {
        url = {
          path: url,
          size: getBase64Size(url),
        };
      }
      // #ifdef MP-WEIXIN
      url = {
        path: url,
        size: await imageSizeIsLessLimitSize(url),
      };
      // #endif
    }
    const size = url.size;
    if (size < limitSize) {
      return _resolve(url.path);
    }
    num++;
    const quality = limitSize / size;
    console.log(size, quality, "压缩前");
    // #ifdef MP-WEIXIN
    getLessLimitSizeImage(url.path, quality);
    // #endif
    // #ifdef H5
    compressH5(url.path, quality);
    // #endif
  });
}

export default myCompressImage;
