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

<script setup>
import '@wangeditor/editor/dist/css/style.css' // 引入 css

import { onBeforeUnmount, ref, shallowRef, onMounted, watch } from 'vue'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'

import {
  useFormItem,
} from 'element-plus'

const props = defineProps({
  modelValue: {
    type: String,
    default: '',
  },
  disabled:{
    type:Boolean,
    default:false
  },
  mode: {
    type: String,
    default: 'default'
  }
})

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

const valueHtml = ref('')

const { formItem } = useFormItem()

const editorRef = shallowRef()

onMounted(() => {
  setTimeout(()=>{
    valueHtml.value = props.modelValue
  })
})

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

onBeforeUnmount(() => {
  const editor = editorRef.value
  if (editor == null) return
  editor.destroy()
})
const handleCreated = (editor) => {
  editorRef.value = editor // 记录 editor 实例，重要！
  if(props.disabled){
    editor.disable()
  }
}
const handleChange = ()=>{
  emit("update:modelValue", valueHtml.value);
}
const handleBlur = ()=>{
  formItem?.validate?.('blur').catch((err) => console.warn(err))
}

watch(
  () => props.modelValue,
  (n,o) => {
    valueHtml.value = n
  }
)
</script>   