<template lang="html">
  <div class="editor">
    <div ref="toolbar" class="toolbar" id="toolbar-container"></div>
    <div ref="editor" class="text" id="editor-container"></div>
  </div>
</template>

<script>
import '@wangeditor/editor/dist/css/style.css';
import { createEditor, createToolbar } from '@wangeditor/editor';
import { upload } from "../../api/files/upload";
// toolbar
let editor;
export default {
  name: 'editoritem',
  data () {
    return {
      info_: null,
      editorConfig: {
        MENU_CONF: {}
      }
    };
  },
  props: {
    value: {
      type: String,
      default: ''
    },
    disabled: {
      type: Boolean,
      default: false
    },
  },
  mounted () {
    this.seteditor();
  },
  methods: {
    seteditor () {
      // 创建编辑器
      editor = createEditor({
        selector: '#editor-container',
        config: {
          onChange: (editor) => {
            this.info_ = editor.getHtml(); // 绑定当前改变地值
            this.$emit('change', this.info_); // 将内容同步到父组件中
          },
          customPaste: (editor, event) => {
            const text = event.clipboardData.getData('text/plain');
          },
          MENU_CONF: {
            uploadImage: {
              async customUpload(file, insertFn) {
                var data = new FormData();
                data.append('file', file);
                const res = await upload(data);
                const url = res.url;
                const alt = res.newFileName;
                const href = res.url;
                // 上传图片，返回结果，将图片插入到编辑器中
                insertFn(url, alt, href);
              }
            },
            uploadVideo: {
              async customUpload(file, insertFn) {
                var data = new FormData();
                data.append('file', file);
                const res = await upload(data);
                const url = res.url;
                // 上传图片，返回结果，将图片插入到编辑器中 poster
                insertFn(url, null);
              }
            }
          }
        }
      });
      // 创建工具栏
      createToolbar({
        editor,
        selector: '#toolbar-container'
      });
      editor.setHtml((this.value));
      if (this.disabled) editor.disable();
      // 启用
      // editor.enable();
      
    }
  },
  beforeDestroy() {
    if (editor == null) return;
    editor.destroy(); // 组件销毁时，及时销毁编辑器
  }
};
</script>

<style lang="scss">
.title {
  margin-top: 0px;
}
.text {
  height: 350px;
}
</style>
