<template>
  <div ref="document-editor" :class="[{'document-editor': true, 'not-show-toolbar': disabled}, customClass]">
    <div ref="document-editor__toolbar" class="document-editor__toolbar"></div>
    <div class="document-editor__editable-container">
      <div ref="document-editor__editable" class="document-editor__editable"></div>
    </div>
  </div>
</template>

<script>
import CKEditor from './ckeditor5/build/ckeditor'
const defaultOptions = {
  placeholder: '请输入内容',
  fontSize: {
    options: [12, 'default', 14, 16, 18, 20, 22, 24, 26, 28, 36, 44, 48],
  },
  fontFamily: {
    options: [
      '宋体', '黑体', '楷体', '微软雅黑'
    ]
  },
  image: {
    // Configure the available styles.
    styles: ['alignLeft', 'alignCenter', 'alignRight', 'side', 'inline','full'],
    toolbar: [
      'imageStyle:alignLeft',
      'imageStyle:alignCenter',
      'imageStyle:alignRight',
      'imageTextAlternative',
      'imageStyle:full',
      'imageStyle:side',
      'imageStyle:inline',
      // 'linkImage',
      'toggleImageCaption',
      'linkImage'
    ]
  },
  table: {
    contentToolbar: [
      'tableColumn',
      'tableRow',
      'mergeTableCells'
    ]
  },
  toolbar: [
    'heading',
    '|',
    'bold', 'italic', 'underline', 'strikethrough', 'fontFamily', 'fontSize', 'fontColor', 'fontBackgroundColor',
    // 'highlight', 
    '|',
    'alignment', 'indent', 'outdent',
    '|',
    'numberedList',
    'bulletedList',
    '|',
    // 'todoList',
    'blockQuote', 'link', 'insertTable', 'imageUpload',
    '|',
    'undo', 'redo'
  ],
  extraPlugins: [],
  // extraPlugins: ['Image', 'ImageInline']
  heading: {
    options: [
      { model: 'paragraph', title: 'Paragraph', class: 'ck-heading_paragraph' },
      { model: 'heading1', view: 'h1', title: 'Heading 1', class: 'ck-heading_heading1' },
      { model: 'heading2', view: 'h2', title: 'Heading 2', class: 'ck-heading_heading2' },
      { model: 'heading3', view: 'h3', title: 'Heading 3', class: 'ck-heading_heading3' },
      { model: 'heading4', view: 'h4', title: 'Heading 4', class: 'ck-heading_heading4' },
      { model: 'heading5', view: 'h5', title: 'Heading 5', class: 'ck-heading_heading5' },
      { model: 'heading6', view: 'h6', title: 'Heading 6', class: 'ck-heading_heading6' },
    ]
  },
  list: {
    properties: {
      styles: true,
      startIndex: true,
      reversed: true
    }
  }
}
export default {
  name: 'CbimCkEditor',
  props: {
    config: {
      type: Object,
      default: () => {}
    },
    value: {
      type: String,
      default: () => ''
    },
    disabled: {
      type: Boolean,
      default: () => false
    },
    imageUploadAdapter: null,
    fileUploadAdapter: null,
    customClass: {
      type: String,
      default: ''
    },
  },
  data() {
    return {}
  },
  watch: {
    value: {
      handler(val, oldVal) {
        if (!this.once && this.editor) {
          this.once = true
          if (val !== this.editor.getData()) {
            this.editor.setData(val)
          }
        } else if (this.editor && val !== oldVal) {
          if (val !== this.editor.getData()) {
            this.editor.setData(val)
          }
          // this.editor.setData(this.value)
          // this.$emit('input', this.editor.getData())
        }
      },
      immediate: true
    },
    disabled: {
      handler() {
        if (!this.editor) {
          return
        }
        this.editor.isReadOnly = this.disabled
      },
      immediate: true
    },
  },
  mounted() {
    this.$nextTick(() => {
      this.initEditor()
    })
  },
  methods: {
    initEditor() {
      const self = this
      /** merge editorconfig */
      const $refs = self.$refs
      const options = Object.assign({}, defaultOptions, this.config)
      /** 图片上传拦截器 */
      if (Object.prototype.toString.apply(self.imageUploadAdapter) === '[object Function]') {
        const ImageUploadAdapter = self.imageUploadAdapter
        options.extraPlugins.push((editor) => {
          editor.plugins.get('FileRepository').createUploadAdapter = (loader) => new ImageUploadAdapter(loader)
        })
      }
      const $editorToolbar = $refs['document-editor__toolbar']
      const $editor = $refs['document-editor__editable']
      CKEditor.create($editor, options).then(editor => {
        /** 插入工具栏 */
        $editorToolbar.appendChild(editor.ui.view.toolbar.element)
        editor.__vueConf = this
        this.editor = editor
        editor.isReadOnly = this.disabled
        /** v-model */
        if (this.value) {
          editor.setData(this.value)
          this.editor.data.model.document.on('change:data', () => {
            if (self.value !== self.editor.getData()) {
              self.$emit('input', self.editor.getData())
            }
          })
        } else {
          // 解决上传图片报错的问题
          editor.setData('请输入内容')
          setTimeout(() => {
            if (!self.once) {
              self.once = true
              editor.setData('')
              self.$emit('input', self.editor.getData())
              self.once = false
              this.editor.data.model.document.on('change:data', () => {
                if (self.value !== self.editor.getData()) {
                  self.$emit('input', self.editor.getData())
                }
              })
            }
          }, 0)
        }
      }).catch(error => {
        console.log(error)
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.document-editor {
  display: flex;
  border: 1px solid var(--ck-color-base-border);
  border-radius: var(--ck-border-radius);

  /* Set vertical boundaries for the document editor. */
  max-height: 700px;

  /* This element is a flex container for easier rendering. */
  display: flex;
  flex-flow: column nowrap;

  .document-editor__toolbar {
    /* Make sure the toolbar container is always above the editable. */
    z-index: 1;
    /* Create the illusion of the toolbar floating over the editable. */
    box-shadow: 0 0 5px hsla( 0,0%,0%,.2 );

    /* Use the CKEditor CSS variables to keep the UI consistent. */
    border-bottom: 1px solid var(--ck-color-toolbar-border);

    /deep/ .ck-toolbar {
      border: 0;
      border-radius: 0;
    }
  }

  /* Make the editable container look like the inside of a native word processor application. */
  .document-editor__editable-container {
    // background: var(--ck-color-base-foreground);
    // padding: calc( 2 * var(--ck-spacing-large) );
    height: 100%;
    padding: 0;

    /* Make it possible to scroll the "page" of the edited content. */
    overflow-y: auto;

    .ck-editor__editable {
      /* Set the dimensions of the "page". */
      width: 100%;
      // min-height: 100%;
      height: 100%;
      box-sizing: border-box;

      /* Keep the "page" off the boundaries of the container. */
      padding: 10px;

      // border: 1px hsl( 0,0%,82.7% ) solid;
      // border-radius: 4px;
      border-radius: var(--ck-border-radius);
      background: white;

      /* The "page" should cast a slight shadow (3D illusion). */
      box-shadow: 0 0 5px hsla( 0,0%,0%,.1 );

      /* Center the "page". */
      margin: 0 auto;
    }
  }

  &.A4{
    .document-editor__toolbar{
      /* Create the illusion of the toolbar floating over the editable. */
      box-shadow: 0 0 5px hsla( 0,0%,0%,.2 );

      /* Use the CKEditor CSS variables to keep the UI consistent. */
      border-bottom: 1px solid var(--ck-color-toolbar-border);
    }
    .document-editor__editable-container {
      padding: calc( 2 * var(--ck-spacing-large) );
    background: var(--ck-color-base-foreground);
      .ck-editor__editable{
        /* Set the dimensions of the "page". */
        width: 15.8cm;
        min-height: 21cm;

        /* Keep the "page" off the boundaries of the container. */
        padding: 1cm 2cm 2cm;

        border: 1px hsl( 0,0%,82.7% ) solid;
        border-radius: var(--ck-border-radius);
        background: white;

        /* The "page" should cast a slight shadow (3D illusion). */
        box-shadow: 0 0 5px hsla( 0,0%,0%,.1 );

      }
    }
  }
}
</style>
