import { insertTagToEditor } from "../utils";

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

/**
 * 和clipboard.js部分内容相同，注意同步修改
 *
 * @this {Object} VEditor 因为VEditor会带很多选项，所以绑定this传过来
 * @param {Event} event
 */
export async function imageHandle(event) {
  this.$refs.editor.focus();
  /** @type {File} */
  const file = event.target.files[0];
  event.target.value = "";
  if (file.size > this.maxImageSize) {
    this.$message(`单张图片超过限制，最大为 ${this.maxImageSize / 1024} KB.`);
    return;
  }

  // 图片大于 10KB 或者 富文本总计超过 200KB的话，就以附件保存图片
  // if (
  //   file.size > this.imageExceedSizeAsAttachment ||
  //   this.value.length > this.jsonExceedSizeAsAttachment
  // ) {
  //   // event.preventDefault();
  //   const filePath = await saveBlobToServer(this.folder, file, "png");
  //   insertTagToEditor(
  //     this.$refs.editor,
  //     "IMG",
  //     filePath
  //   );
  // } else {
  const srcBase64 = await toBase64(file);
  insertTagToEditor(this.$refs.editor, "IMG", srcBase64);
  // }
}

export async function saveFormulaImageToEditorHandle(imgDataUrl, attributes) {
  // if (
  //   file.size > this.imageExceedSizeAsAttachment ||
  //   this.value.length > this.jsonExceedSizeAsAttachment
  // ) {
  //   // event.preventDefault();
  // } else {
  insertTagToEditor(this.$refs.editor, "IMG", imgDataUrl, attributes);
  // }
}
