<template>
  <div :style="`border: 1px solid #ccc; width: ${width}`">
    <Toolbar
      style="border-bottom: 1px solid #ccc"
      :editor="editorRef"
      :defaultConfig="toolbarConfig"
      :mode="mode"
    />
    <Editor
      :style="`min-height: ${minHeight}; height: ${height} overflow-y: hidden`"
      v-model="valueHtml"
      :defaultConfig="editorConfig"
      :mode="mode"
      @onCreated="handleCreated"
      @onChange="handleChange"
    />
  </div>
</template>

<script>
import "@wangeditor/editor/dist/css/style.css"; // 引入 css
import { onBeforeUnmount, ref, shallowRef, toRefs, watch } from "vue";
import { Editor, Toolbar } from "@wangeditor/editor-for-vue";

export default {
  components: { Editor, Toolbar },
  props: {
    modelValue: {
      type: String,
      default: "",
    },
    minHeight: {
      type: String,
      default: "150px",
    },
    height: {
      type: String,
      default: "320px",
    },
    width: {
      type: String,
      default: "100%",
    },
    focus: {
      type: Boolean,
      default: false,
    },
    mode: {
      type: String,
      default: "default",
    },
  },
  setup(props, context) {
    // 编辑器实例，必须用 shallowRef
    const editorRef = shallowRef();
    // console.log(editorRef.value.getAllMenuKeys());
    // 内容 HTML
    const valueHtml = ref("");
    watch(
      () => props.modelValue,
      (val) => {
        valueHtml.value = val;
      },
      { immediate: true }
    );
    const { height } = toRefs(props);
    const toolbarConfig = {
      toolbarKeys: [
        "bold",
        "underline",
        "italic",
        "through",
        "color",
        "bgColor",
        "fontSize",
        "fontFamily",
        "lineHeight",
        // "emotion",
        // "redo",
        // "undo",
      ],
    };
    const editorConfig = {
      placeholder: "请输入内容...",
      autoFocus: props.focus,
      maxLength: 140,
    };

    // 组件销毁时，也及时销毁编辑器
    onBeforeUnmount(() => {
      const editor = editorRef.value;
      if (editor == null) return;
      editor.destroy();
    });

    const handleCreated = (editor) => {
      editorRef.value = editor; // 记录 editor 实例，重要！
    };

    const handleChange = (editor) => {
      if (editor.getHtml() === "<p><br></p>") {
        context.emit("update:modelValue", "");
      } else {
        context.emit("update:modelValue", editor.getHtml());
      }
    };

    return {
      editorRef,
      valueHtml,
      mode: "default", // 或 'simple'
      toolbarConfig,
      editorConfig,
      height,
      handleCreated,
      handleChange,
    };
  },
};
</script>
