<script setup>
import {AiEditor} from "aieditor";
import "aieditor/dist/style.css"
import {onMounted, onUnmounted, ref} from "vue";

const divRef = ref();
const baseUrl = import.meta.env.VITE_APP_BASE_API;
const minioUrl = import.meta.env.VITE_MINIO_BASE_API;
let aiEditor = null;
onMounted(() => {
  aiEditor = new AiEditor({
    element: divRef.value,
    placeholder: "点击输入内容...",
    content: '',
    toolbarKeys: ["undo", "redo", "brush", "eraser",
      "|", "heading", "font-family", "font-size",
      "|", "bold", "italic", "underline", "strike", "link", "code", "subscript", "superscript", "hr", "todo", "emoji",
      "|", "highlight", "font-color",
      "|", "align", "line-height",
      "|", "bullet-list", "ordered-list", "indent-decrease", "indent-increase", "break",
      "|", "image", "video", "attachment",
      "|", "source-code", "fullscreen"
    ],
    textSelectionBubbleMenu:{
      enable: true,
      items: ["Bold", "Italic", "Underline", "Strike", "code", "comment"],
    },
    image: {
      allowBase64: true,
      defaultSize: 350,
      uploadUrl: baseUrl+"/xcrFile/save",
      uploadFormName: "file",
      uploader: (file, uploadUrl, headers, formName) => {
        const formData = new FormData();
        formData.append(formName, file);
        formData.append('moduleName', '性与暴力');
        return new Promise((resolve, reject) => {
          fetch(uploadUrl, {
            method: "post",
            headers: {'Accept': 'application/json', ...headers},
            body: formData,
          }).then((resp) => resp.json())
              .then(json => {
                resolve(json);
              }).catch((error) => {
            reject(error);
          })
        });
      },
      uploaderEvent:{
        onSuccess(file, res){
          if(res.code !== 200){
            Elmessage({ message: res.msg, type: 'warning' });
            return false;
          }
          return {
            "errorCode": 0,
            "data": {
              "src": minioUrl+res.data.fileUrl,
              "alt": "富文本图片",
              "id": res.data.id
            }
          }
        },
      },
      bubbleMenuItems: ["AlignLeft", "AlignCenter", "AlignRight","delete"]
    },
  })
})

defineExpose({
  getContent() {
    return aiEditor.getHtml()
  },
  setContent(content) {
    aiEditor.setContent(content)
  }
})

onUnmounted(() => {
  aiEditor && aiEditor.destroy();
})
</script>

<template>
  <div ref="divRef" style="height: 600px"></div>
</template>