<template>
  <div style="border: 1px solid #cccccc">
    <Toolbar style="border-bottom: 1px solid #cccccc" :editor="editorRef" :default-config="toolbarConfig" :mode="mode" />
    <Editor
      style="height: 500px; overflow-y: hidden"
      :style="{ pointerEvents: disabled ? 'none' : 'auto' }"
      v-model="valueHtml"
      :default-config="editorConfig"
      :mode="mode"
      :read-only="true"
      @on-created="handleCreated"
    />
  </div>
</template>

<script lang="ts" setup>
import "@wangeditor/editor/dist/css/style.css"; // 引入 css
import { onBeforeUnmount, ref, shallowRef, watch, defineEmits, defineProps } from "vue";
import { Editor, Toolbar } from "@wangeditor/editor-for-vue";
import { IDomEditor } from "@wangeditor/editor";

const props = defineProps({
  value: {
    type: String,
    default: ""
  },
  maxLength: { type: Number || String, default: 2000 },
  disabled: { type: Boolean, default: false }
});

const emit = defineEmits(["update:value"]);

// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef();

const valueHtml = ref(props.value || "");
const mode = ref("default");

const toolbarConfig = {};
const editorConfig: any = { placeholder: "请输入内容..." };

editorConfig.maxLength = 1000;
editorConfig.onMaxLength = function (editor: IDomEditor) {
  console.log("已达到最大长度");
};

watch(valueHtml, newValue => {
  console.log(typeof newValue);
  emit("update:value", newValue);
});

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

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

<style scoped>
h1 {
  color: #42b983;
}
</style>
