<template>
  <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="handleCreated"
    />
  </div>
</template>

<script setup>
import '@wangeditor/editor/dist/css/style.css'
import { onBeforeUnmount, ref, shallowRef, onMounted, watch } from 'vue'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'

const props = defineProps({
  modelValue: {
    type: String,
    default: '',
  },
});

const emit = defineEmits(['update:modelValue', 'image-upload']);

const editorRef = shallowRef();
const valueHtml = ref(props.modelValue);

watch(() => props.modelValue, (newValue) => {
  if (newValue !== valueHtml.value) {
    valueHtml.value = newValue;
  }
});

watch(valueHtml, (newValue) => {
  emit('update:modelValue', newValue);
});

const toolbarConfig = {};
const editorConfig = { 
  placeholder: '请输入内容...',
  MENU_CONF: {}
};

editorConfig.MENU_CONF['uploadImage'] = {
  async customUpload(file, insertFn) {
    const url = await emit('image-upload', file);
    if (url) {
      insertFn(url);
    }
  }
};

onBeforeUnmount(() => {
  const editor = editorRef.value;
  if (editor == null) return;
  editor.destroy();
});

const handleCreated = (editor) => {
  editorRef.value = editor;
};

onMounted(() => {
  setTimeout(() => {
    valueHtml.value = props.modelValue;
  }, 100);
});
</script>

<style scoped>
.wysiwyg-editor {
  border: 1px solid #ccc;
  z-index: 100;
}
</style>

