<template>
  <div>
    <div style="border: 1px solid #ccc; margin-top: 10px">
      <!-- 工具栏 -->
      <Toolbar
        style="border-bottom: 1px solid #ccc"
        :editor="editor"
        :default-config="toolbarConfig"
      />
      <!-- 编辑器 -->
      <Editor
        v-model="html"
        style="height: 400px; overflow-y: hidden"
        :default-config="editorConfig"
        @onChange="onChange"
        @onCreated="onCreated"
      />
    </div>
  </div>
</template>

<script>
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import { upload } from '@/utils/upload'
import { mapGetters } from 'vuex'

export default {
  name: 'MyEditor',
  components: { Editor, Toolbar },
  props: {
    html: {
      type: String,
      defaultValue: ''
    }
  },
  computed: {
    ...mapGetters([
      'imagesUploadApi',
      'baseApi'
    ])
  },
  data() {
    return {
      editor: null,
      toolbarConfig: {
        // toolbarKeys: [ /* 显示哪些菜单，如何排序、分组 */ ],
        // excludeKeys: [ /* 隐藏哪些菜单 */ ],
      },
      editorConfig: {
        placeholder: '请输入内容...',
        // autoFocus: false,

        // 所有的菜单配置，都要在 MENU_CONF 属性下
        MENU_CONF: {
          'uploadImage': {
            customUpload: this.update
          }
        }
      }
    }
  },

  mounted() {
    // 模拟 ajax 请求，异步渲染编辑器
  },
  beforeDestroy() {
    const editor = this.editor
    if (editor == null) return
    editor.destroy() // 组件销毁时，及时销毁 editor ，重要！！！
  },
  methods: {
    update(file, insertFn) {
      // 文件上传
      // files 是 input 中选中的文件列表
      // insert 是获取图片 url 后，插入到编辑器的方法
      upload(this.imagesUploadApi, file).then(res => {
        const data = res.data
        const url = data.url
        insertFn(url)
      })
    },
    onCreated(editor) {
      this.editor = Object.seal(editor) // 【注意】一定要用 Object.seal() 否则会报错
    },
    onChange(editor) {
      console.log('onChange', editor.getHtml()) // onChange 时获取编辑器最新内容
    },
    getEditorText() {
      const editor = this.editor
      if (editor == null) return

      console.log(editor.getText()) // 执行 editor API
    },
    printEditorHtml() {
      const editor = this.editor
      if (editor == null) return

      console.log(editor.getHtml()) // 执行 editor API
    }
  }
}
</script>

<style src="@wangeditor/editor/dist/css/style.css"></style>
