import _regeneratorRuntime from '@babel/runtime/regenerator';
import { _ as __awaiter } from '../tslib.es6-848120af.js';
import { getCanvas } from './get-canvas.mjs';
import '../third-party/canvas.mjs';

/**
 * 压缩 base64 图片
 * - 通过 canvas 缩放图片到指定最大宽度，并转为 JPEG 格式降低体积
 * @param {string} base64Img base64 图片字符串（可带或不带 data:image 前缀）
 * @param {object} options 压缩选项
 * @param {number} options.maxWidth 最大宽度，默认 280
 * @param {number} options.quality JPEG 质量 0-1，默认 0.8
 * @returns {Promise<string>} 压缩后的 base64 图片字符串
 *
 * @example
 *
 * const compressed = await compressBase64Img(base64Str, { maxWidth: 280, quality: 0.8 });
 */
function compressBase64Img(base64Img) {
  var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  return __awaiter(this, void 0, void 0, /*#__PURE__*/_regeneratorRuntime.mark(function _callee() {
    var _options$maxWidth, maxWidth, _options$quality, quality, canvasLibrary, createCanvas, loadImage, imgSrc, image, oWidth, oHeight, targetWidth, targetHeight, ratio, canvas, ctx, compressedBase64;
    return _regeneratorRuntime.wrap(function (_context) {
      while (1) switch (_context.prev = _context.next) {
        case 0:
          _options$maxWidth = options.maxWidth, maxWidth = _options$maxWidth === void 0 ? 280 : _options$maxWidth, _options$quality = options.quality, quality = _options$quality === void 0 ? 0.8 : _options$quality;
          canvasLibrary = getCanvas();
          if (canvasLibrary) {
            _context.next = 1;
            break;
          }
          console.warn('[compressBase64Img] canvas 库不可用，返回原图');
          return _context.abrupt("return", base64Img);
        case 1:
          createCanvas = canvasLibrary.createCanvas, loadImage = canvasLibrary.loadImage; // 确保 base64 字符串带有 data URI 前缀
          imgSrc = base64Img;
          if (!imgSrc.startsWith('data:')) {
            imgSrc = "data:image/png;base64,".concat(imgSrc);
          }
          _context.next = 2;
          return loadImage(imgSrc);
        case 2:
          image = _context.sent;
          oWidth = image.width, oHeight = image.height; // 如果原图宽度已经小于等于 maxWidth，不需要缩放，仅做质量压缩
          targetWidth = oWidth;
          targetHeight = oHeight;
          if (oWidth > maxWidth) {
            ratio = maxWidth / oWidth;
            targetWidth = maxWidth;
            targetHeight = Math.round(oHeight * ratio);
          }
          canvas = createCanvas(targetWidth, targetHeight);
          ctx = canvas.getContext('2d');
          ctx.drawImage(image, 0, 0, targetWidth, targetHeight);
          // 转为 JPEG 格式以获得更好的压缩率
          compressedBase64 = canvas.toDataURL('image/jpeg', quality);
          return _context.abrupt("return", compressedBase64);
        case 3:
        case "end":
          return _context.stop();
      }
    }, _callee);
  }));
}

export { compressBase64Img };
