<template>
  <div style="border: 1px solid #ccc; z-index: 100">
    <Toolbar style="border-bottom: 1px solid #ccc" :editor="editorRef" :defaultConfig="toolbarConfig" :mode="mode" />
    <Editor
      style="height: 500px; overflow-y: hidden"
      v-model="valueHtml"
      @onChange="handleChange"
      @onBlur="handleBlur"
      :defaultConfig="editorConfig"
      :mode="mode"
      @onCreated="handleCreated" />
  </div>
</template>

<script setup>
import "@wangeditor/editor/dist/css/style.css"; // 引入 css

import { onBeforeUnmount, ref, shallowRef, onMounted } from "vue";
import { Editor, Toolbar } from "@wangeditor/editor-for-vue";

import { useFormItem } from "element-plus";

const props = defineProps({
  modelValue: {
    type: String,
    default: "",
  },
  disabled: {
    type: Boolean,
    default: false,
  },
  mode: {
    type: String,
    default: "default",
  },
});

const emit = defineEmits(["update:modelValue", "change", "blur"]);

const valueHtml = ref("");
// change次数
let changeNum = ref(0);

const { formItem } = useFormItem();

const editorRef = shallowRef();

onMounted(() => {
  setTimeout(() => {
    valueHtml.value = props.modelValue;
  });
});

const toolbarConfig = {};
const editorConfig = {
  placeholder: "请输入内容...",
  MENU_CONF: {
    uploadImage: {
      server: "/apaas/common/image/upload", // 服务器地址
      fieldName: "file", // 上传的文件的字段名称
      meta: {
        directory: "image",
      }, // 上传图片必须携带的参数
      maxFileSize: 2 * 1024 * 1024, // 图片最大2M
      timeout: 3 * 60 * 1000, // 超时时间3分钟
      allowedFileTypes: ["image/jpg", "image/png", "image/gif", "image/jpeg"],
      customInsert(res, insertFn) {
        // res 即服务端的返回结果
        // 从 res 中找到 url alt href ，然后插图图片 url是必须，href和alt可以为""
        let url = res.data;
        let alt = "";
        let href = res.data;
        insertFn(url, alt, href);
      },
      onBeforeUpload(file) {
        // 可以 return
        // 1. return file 或者 new 一个 file ，接下来将上传
        // 2. return false ，不上传这个 file
        let allowedType = ["jpg", "png", "jpeg", "gif", "bmp", "tiff"]; // 常见的图片格式
        let data = Object.values(file)[0];
        if (allowedType.indexOf(data.extension) == -1) {
          alert(`图片验证未通过，【${data.name}】不是图片`);
          return false;
        } else {
          return file;
        }
      },
      onError(file, err, res) {
        console.log(`${file.name} 上传出错`, err, res);
      },
    },
  },
};

onBeforeUnmount(() => {
  const editor = editorRef.value;
  if (editor == null) return;
  editor.destroy();
});
const handleCreated = (editor) => {
  editorRef.value = editor; // 记录 editor 实例，重要！
  if (props.disabled) {
    editor.disable();
  }
};
const handleChange = () => {
  //初始化会默认赋值<p><br></p>
  //会对原有数据造成影响，return掉
  changeNum.value++;
  if (changeNum.value == 1) {
    return;
  }
  emit("update:modelValue", valueHtml.value);
};
const handleBlur = () => {
  formItem?.validate?.("blur").catch((err) => console.warn(err));
};
</script>
