<template>
  <div class="ckeditor">
    <ckeditor
      :editor="editor"
      :value="value"
      :disabled="disabled"
      :config="editorConfig"
      @ready="onEditorReady"
      @input="onEditorInput"
    ></ckeditor>
  </div>
</template>

<script>
import CKEditor from '@ckeditor/ckeditor5-vue2'

import DecoupledEditor from '@ckeditor/ckeditor5-build-decoupled-document'
import '@ckeditor/ckeditor5-build-decoupled-document/build/translations/zh-cn'

// import ClassicEditor from '@ckeditor/ckeditor5-build-classic'
// import '@ckeditor/ckeditor5-build-classic/build/translations/zh-cn'

import MyUploadAdapter from './MyUploadAdapter'

export default {
  components: {
    ckeditor: CKEditor.component
  },
  props: {
    value: { type: String },
    disabled: { type: Boolean, default: false }
  },
  data() {
    return {
      editor: DecoupledEditor,
      editorConfig: {
        language: this.$i18n.locale.toLocaleLowerCase(),
        fontFamily: { options: ['default', '宋体', 'Times New Roman'] },
        fontSize: { options: ['12px', '14px', '16px', '18px', '20px', '24px', '36px'] }
      }
    }
  },
  methods: {
    onEditorReady(editor) {
      editor.ui
        .getEditableElement()
        .parentElement.insertBefore(editor.ui.view.toolbar.element, editor.ui.getEditableElement())

      const FileRepository = editor.plugins.get('FileRepository')
      // 自定义上传图片插件
      FileRepository.createUploadAdapter = loader => {
        return new MyUploadAdapter(loader)
      }
    },
    onEditorInput(value) {
      this.$emit('input', value)
      this.dispatch('ElFormItem', 'el.form.change', value)
    },
    dispatch(componentName, eventName, params) {
      var parent = this.$parent || this.$root
      var name = parent.$options.componentName

      while (parent && (!name || name !== componentName)) {
        parent = parent.$parent

        if (parent) {
          name = parent.$options.componentName
        }
      }
      if (parent) {
        parent.$emit.apply(parent, [eventName].concat(params))
      }
    }
  }
}
</script>

<style>
.ck-content {
  min-height: 300px;
  max-height: 500px;
  word-break: break-word;
  background: var(--ck-color-base-background);
  border: 1px solid var(--ck-color-toolbar-border) !important;
}
.ck-sticky-panel__content {
  position: unset !important;
}
</style>
