<script setup>
import { onBeforeUnmount, onMounted, ref, watch } from 'vue'
import WangEditor from 'wangeditor'

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

const emit = defineEmits(['update:modelValue'])

const editorRef = ref(null)
let editor = null

onMounted(() => {
  editor = new WangEditor(editorRef.value)
  editor.config.placeholder = '请输入内容...'
  editor.config.height = 130
  editor.config.onchange = (newHtml) => {
    emit('update:modelValue', newHtml)
  }
  editor.create()
  editor.txt.html(props.modelValue)
})

watch(
  () => props.modelValue,
  (newValue) => {
    if (editor && newValue !== editor.txt.html()) {
      editor.txt.html(newValue)
    }
  },
)

onBeforeUnmount(() => {
  if (editor) {
    editor.destroy()
    editor = null
  }
})
</script>

<template>
  <div>
    <div ref="editorRef" />
  </div>
</template>
