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

<script lang="ts" setup>
import '@wangeditor/editor/dist/css/style.css'; // 引入 css
import { Editor, Toolbar } from '@wangeditor/editor-for-vue';
import type { Ref } from 'vue';
import { ref, toRefs, onBeforeUnmount, shallowRef, computed } from 'vue';
interface EmitEvent {
  (e: 'update:modelValue', params: string): void;
}
// #region 参数传递
const props = defineProps({
  modelValue: { type: String, default: () => '' },
  mode: { type: String, default: () => 'default' },
  url: { type: String, default: () => '' },
});
const { modelValue } = toRefs(props);
const { mode } = toRefs(props);
const { url } = toRefs(props);
// #endregion

const editorRef = shallowRef();
const onCreated = (editor: string) => {
  editorRef.value = Object.seal(editor); // 一定要用 Object.seal() ，否则会报错
};

const emit = defineEmits<EmitEvent>();
const valueHtml = computed({
  get() {
    return modelValue.value;
  },
  set(value: string) {
    emit('update:modelValue', value);
  },
});
const customPicInsert = (result: { errcode: number; uri: string; name: string }, insertFn: any) => {
  const { errcode, uri, name } = result;
  const url = `${import.meta.env.VITE_APP_HOST}${uri}`;
  if (errcode === 0) {
    insertFn(url, name);
  }
};
let editorConfig: Ref<object> = ref({
  placeholder: '请输入内容...',
  MENU_CONF: { uploadImage: { server: url, customInsert: customPicInsert } },
});
let toolbarConfig: Ref<object> = ref({
  // excludeKeys: ['insertImage', 'insertVideo', 'uploadVideo', 'video'],
});
onBeforeUnmount(() => {
  const editor = editorRef.value;
  if (editor == null) return;
  editor.destroy();
});
</script>

<style src="@wangeditor/editor/dist/css/style.css"></style>
<style scoped>
.editor {
  overflow-y: hidden;
}
</style>
