<template>
  <div style="border: 1px solid #ccc">
    <!-- 工具栏 -->
    <Toolbar style="border-bottom: 1px solid #ccc" :editor="editorRef" :defaultConfig="toolbarConfig" mode="default" />
    <!-- 编辑区 -->
    <Editor style="height: 500px; overflow-y: hidden;" v-model="valueHtml" :defaultConfig="editorConfig" mode="default"
      @onCreated="handleCreated" @onChange="handleChange" />
  </div>
</template>

<script>
import '@wangeditor/editor/dist/css/style.css'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'

export default {
  name: 'WangEditorV5',
  components: { Editor, Toolbar },
  props: {
    modelValue: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      editorConfig: {
        MENU_CONF: {
          uploadImage: {
            server: '/cloud/api.php',
            fieldName: 'file',
            maxFileSize: 10 * 1024 * 1024,
            customInsert(res, insertFn) {
              insertFn(res.viewurl || res.downurl, res.name, res.viewurl || res.downurl)
            }
          },
          uploadVideo: {
            server: '/cloud/api.php',
            fieldName: 'file',
            maxFileSize: 1024 * 1024 * 1024,
            customInsert(res, insertFn) {
              insertFn(res.viewurl || res.downurl, res.viewurl || res.downurl)
            }
          }
        }
      }
    }
  },
  watch: {
    modelValue(val) {
      if (val !== this.valueHtml) {
        this.valueHtml = val
      }
    }
  },
  methods: {
    handleCreated(editor) {
      this.editorRef = editor
    },
    handleChange(editor) {
      this.$emit('update:modelValue', this.valueHtml)
      this.$emit('change', this.valueHtml)
    }
  },
  beforeUnmount() {
    const editor = this.editorRef
    if (editor) {
      editor.destroy()
    }
  }
}
</script>
