<template>
  <div :class="{'ck-editor-x': true, 'not-show-toolbar': disabled}" ref="uploadFileParent">
    <div ref="uploadFile" class="ck-instance-inner"></div>
  </div>
</template>

<script>
import ClassicEditor from '@ckeditor/ckeditor5-editor-classic/src/classiceditor'
import CKFinder from '@ckeditor/ckeditor5-ckfinder/src/ckfinder.js'
import Essentials from '@ckeditor/ckeditor5-essentials/src/essentials'
import Paragraph from '@ckeditor/ckeditor5-paragraph/src/paragraph'
import Bold from '@ckeditor/ckeditor5-basic-styles/src/bold'
import Italic from '@ckeditor/ckeditor5-basic-styles/src/italic'
import Image from '@ckeditor/ckeditor5-image/src/image'
import ImageCaption from '@ckeditor/ckeditor5-image/src/imagecaption'
import ImageStyle from '@ckeditor/ckeditor5-image/src/imagestyle'
import ImageToolbar from '@ckeditor/ckeditor5-image/src/imagetoolbar'
import ImageUpload from '@ckeditor/ckeditor5-image/src/imageupload'
import Link from '@ckeditor/ckeditor5-link/src/link'
// import Indent from '@ckeditor/ckeditor5-indent/src/indent'
import List from '@ckeditor/ckeditor5-list/src/list'
// import Undo from '@ckeditor/ckeditor5-undo/src/undo'
import Table from '@ckeditor/ckeditor5-table/src/table'
import Heading from '@ckeditor/ckeditor5-heading/src/heading'
import BlockQuote from '@ckeditor/ckeditor5-block-quote/src/blockquote'
// extra
import UploadFileSimple from './mixins/uploadFileSimple.js'

export default {
  name: 'CbimCkEditor',
  props: {
    config: {
      type: Object,
      default: () => {}
    },
    value: {
      type: String,
      default: () => ''
    },
    disabled: {
      type: Boolean,
      default: () => false
    },
    imageUploadAdapter: null,
    fileUploadAdapter: null,
  },
  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
    },
  },
  methods: {
  },
  mounted() {
    if (!this.$refs.uploadFileParent) {
      return
    }
    this.$refs.uploadFileParent.childNodes.forEach(child => {
      if (child !== this.$refs.uploadFile) {
        this.$refs.uploadFileParent.removeChild(child)
      }
    })
    // class UploadAdapter {
    //   constructor(loader) {
    //     this.loader = loader
    //   }
    //   upload() {
    //     return new Promise((resolve, reject) => {
    //       const data = new FormData();
    //       data.append('upload', this.loader.file)
    //       // data.append('allowSize', 10) // 允许图片上传的大小/兆
    //       resolve({
    //         default: 'https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1576265015152&di=7e97b477d4adc10a206985e7a7e4215a&imgtype=0&src=http%3A%2F%2Fnews.youth.cn%2Fjsxw%2F201412%2FW020141205308938726862.jpg'
    //       });
    //     });
    //   }
    //   abort() {
    //     console.log('暂停上传')
    //   }
    // }
    // function MyCreateUploadAdapterOfSimple(editor) {
    //   editor.plugins.get('UploadFileSimple').createUploadAdapter = (loader) => new UploadAdapter(loader)
    // }
    // function MyCustomUploadAdapterPlugin(editor) {
    //   editor.plugins.get('FileRepository').createUploadAdapter = (loader) => new UploadAdapter(loader)
    // }
    const options = {
      // language: 'zh-cn',
      placeholder: '请输入内容',
      fontSize: {
        options: [12, 'default', 14, 16, 18, 20, 22, 24, 26, 28, 36, 44, 48, 72],
      },
      fontFamily: {
        options: [
          '宋体', '黑体', '楷体', '微软雅黑'
        ]
      },
      plugins: [CKFinder, Bold, Italic, Link, Paragraph, Essentials, Table, Image, ImageCaption, ImageStyle, ImageToolbar, ImageUpload, UploadFileSimple, List, Heading, BlockQuote],
      // plugins: [CKFinder, Bold, Italic, Link, Paragraph, Essentials, Table, ImageUpload, UploadFileSimple, ImageCaption, List, Indent, Heading, BlockQuote],
      // toolbar: ['heading', '|', 'bold', 'italic', 'link', 'bulletedList', 'numberedList', '|', 'indent', 'outdent', '|', 'imageUpload', 'uploadFileSimple', '|', 'blockQuote', 'insertTable', 'undo', 'redo'], // 'ckfinder'
      toolbar: ['heading', '|', 'bold', 'italic', 'link', 'bulletedList', 'numberedList', '|', 'imageUpload', 'uploadFileSimple', '|', 'blockQuote', 'insertTable', 'undo', 'redo'], // 'ckfinder'e
      image: {
        toolbar: [
          'imageTextAlternative', '|',
          'imageStyle:alignLeft',
          'imageStyle:full',
          'imageStyle:alignRight'
        ],
        styles: [
          'full',
          'alignLeft',
          'alignRight'
        ]
      },
      extraPlugins: []
    }
    const self = this
    if (Object.prototype.toString.apply(this.imageUploadAdapter) === '[object Function]') {
      options.extraPlugins.push((editor) => {
        editor.plugins.get('FileRepository').createUploadAdapter = (loader) => new self.imageUploadAdapter(loader)
      })
    }
    if (Object.prototype.toString.apply(this.fileUploadAdapter) === '[object Function]') {
      options.extraPlugins.push((editor) => {
        editor.__vueConf = self
        editor.plugins.get('UploadFileSimple').createUploadAdapter = (loader) => new self.fileUploadAdapter(loader)
      })
    }
    ClassicEditor.create(this.$refs.uploadFile, options).then(editor => {
      editor.__vueConf = this
      this.editor = editor
      editor.isReadOnly = this.disabled
      // editor.plugins.get('FileRepository').createUploadAdapter = (loader) => new UploadAdapter(loader)
      // editor.data.model.document.on('change:data', (e) => {
      //   debugger
      //   if (self.once) {
      //     editor.__vueConf.$emit('input', editor.getData())
      //   }
      // })
      // editor.editing.view.focus()
      // editor.execute('enter')
      if (this.value) {
        editor.setData(this.value) // 初始化
        this.editor.data.model.document.on('change:data', (e) => {
          if (self.value !== self.editor.getData()) {
            self.$emit('input', self.editor.getData())
          }
        })
      } else {
        // this.initialNoData = true
        // 解决上传图片报错的问题
        editor.setData('请输入内容')
        setTimeout(() => {
          // this.initialNoData = false
          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', (e) => {
              if (self.value !== self.editor.getData()) {
                self.$emit('input', self.editor.getData())
              }
            })
          }
        }, 0)
      }
    }).catch(error => {
      console.log(error)
    });
  }
}
</script>
<style lang="scss" scoped>
  .ck-editor-x {
    width: 100%;
    min-height: 200px;
    height: auto;
    /*position: relative;*/
  }
</style>
<style lang="scss">
  .ck-editor-x {
    .ck.ck-editor {
      /*position: absolute !important;*/
      width: 100%;
      min-width: 600px;
    }
    .ck-content {
      min-height: 160px;
      max-height: 50vh;
    }
    .ck-content .image {
      display: table;
      clear: both;
      text-align: center;
      margin: 1em auto;
    }
    .ck.ck-dropdown .ck-dropdown__panel.ck-dropdown__panel_ne, .ck.ck-dropdown .ck-dropdown__panel.ck-dropdown__panel_nw {
      top: 100%;
      bottom: auto;
    }
    .ck-rounded-corners .ck.ck-editor__top .ck-sticky-panel .ck-toolbar, .ck.ck-editor__top .ck-sticky-panel .ck-toolbar.ck-rounded-corners {
      border-top-left-radius: 6px !important;
      border-top-right-radius: 6px !important;
    }
    .ck.ck-editor__main>.ck-editor__editable:not(.ck-focused) {
      border-bottom-right-radius: 6px;
      border-bottom-left-radius: 6px;
    }
  }
  .not-show-toolbar {
    .ck-editor__top {
      display: none;
    }
    .ck.ck-editor__main>.ck-editor__editable:not(.ck-focused) {
      border-radius: 6px;
      border-color: #E4E7ED;
    }
  }
</style>
