<template>
  <div class="n-editor quill-editor">
    <div ref="editor"></div>
  </div>
</template>

<script>
import {loadQuill, loadQuillStyle, getDefaultOptions} from './options'
import {prop} from '@uif/next/lib/utils/tools'

export default {
  name: 'n-editor',
  props: {
    // 富文本数据
    value: prop.string(),
    // 配置项
    options: prop.object(),
    // 禁用
    disabled: prop.boolean()
  },
  data () {
    return {
      nValue: this.value
    }
  },
  watch: {
    value (value) {
      if (this.nValue !== value) {
        this.nValue = value
        this.setValue(this.nValue)
      }
    },
    nValue (nValue) {
      if (this.value !== nValue) {
        this.$emit('input', nValue)
        this.$emit('update:value', nValue)
      }
    },
    disabled (value) {
      if (this.quill) {
        this.quill.enable(!value)
      }
    }
  },
  created () {
    loadQuillStyle()
    loadQuill()
  },
  mounted () {
    this.quillInit()
  },
  beforeDestroy () {
    this.quill = null
  },
  methods: {
    quillInit () {
      loadQuill().then(Quill => {
        this.quill = new Quill(this.$refs.editor, Object.assign(getDefaultOptions(), this.options))
        this.quill.enable(!this.disabled)
        this.setValue(this.nValue)
        // 上传图片
        this.quill.getModule('toolbar').addHandler('image', () => {
          this.$emit('upload', (image) => this.insertImage(image))
        })
        this.quill.on('selection-change', range => range ? this.onFocus() : this.onBlur())
        this.quill.on('text-change', () => this.onUpdate())
        this.$emit('u-mounted', this.quill)
      })
    },
    insertImage (image) {
      const range = this.quill.getSelection(true)
      this.quill.insertEmbed(range.index, 'image', image)
      this.quill.setSelection(range.index + 1)
    },
    onUpdate () {
      const value = this.$refs.editor.children[0].innerHTML
        .replace(/^<p><br><\/p>$/ig, '')
      if (this.nValue !== value) {
        this.nValue = value
        this.$emit('u-update', this.nValue)
      }
    },
    onFocus () {
      this.backup = this.nValue
      this.$emit('u-focus', this)
    },
    onBlur () {
      this.$emit('u-blur', this)
      if (this.nValue !== this.backup) {
        this.$emit('u-change', this.nValue)
      }
    },
    setValue (value) {
      if (this.quill && value) {
        this.quill.clipboard.dangerouslyPasteHTML(value)
      }
      if (this.quill && !value) {
        this.quill.setText('')
      }
    }
  }
}
</script>
