<template>
  <div class="vue-quill-editor">
    <vab-quill ref="quillRef" v-model="html" :options="editorOption" />
    <media ref="media" :append-to-body="true" @save-file="handleAddImg" />
  </div>
</template>
<script>
  import VabQuill from '@/extra/VabQuill'
  import media from '@/components/material/Media'
  export default {
    name: 'QuillEditor',
    components: {
      VabQuill,
      media,
    },
    props: {
      value: {
        type: [Number, Object, Array, String],
        default: '',
      },
    },
    data() {
      return {
        html: this.value,
        editorOption: {
          theme: 'snow',
          bounds: document.body,
          debug: 'warn',
          placeholder: '内容...',
          readOnly: false,
          modules: {
            toolbar: {
              container: [
                ['bold', 'italic', 'underline', 'strike'],
                [{ header: [1, 2, 3, 4, 5, 6, false] }],
                [{ size: ['small', false, 'large', 'huge'] }],
                [{ color: [] }, { background: [] }],
                ['blockquote', 'code-block'],
                [{ list: 'ordered' }, { list: 'bullet' }],
                [{ script: 'sub' }, { script: 'super' }],
                [{ indent: '-1' }, { indent: '+1' }],
                [{ align: [] }],
                [{ direction: 'rtl' }], // 文本方向-----[{'direction': 'rtl'}]
                [{ font: [] }],
                ['clean'],
                // ['link', 'image', 'vab-upload-image'],
                ['link', 'vab-upload-image'],
              ],
              handlers: {
                'vab-upload-image': () => {
                  this.quillRef = 'detail-quill'
                  this.$refs['media'].showEdit()
                },
              },
            },
          },
        },
      }
    },
    watch: {
      html: {
        handler(newValue) {
          this.$emit('input', newValue)
        },
        deep: true,
      },
      value: {
        handler(newValue, oldValue) {
          if (newValue !== oldValue) this.html = newValue
        },
        deep: true,
      },
    },
    mounted() {},
    created() {},
    methods: {
      handleAddImg(images) {
        let quill = this.$refs.quillRef.Quill
        // 获取光标所在位置
        let length = quill.selection.savedRange.index
        // 插入图片 res.info为服务器返回的图片地址
        images.forEach((image) => {
          quill.insertEmbed(length, 'image', image.media_url)
          length++
        })
        // 调整光标到最后
        quill.setSelection(length)
      },
    },
  }
</script>
<style>
  .vue-quill-editor .ql-editor {
    height: 400px;
  }
  .vue-quill-editor .quill {
    padding-bottom: 100px;
  }

  .vue-quill-editor .vab-quill .ql-vab-upload-image {
    font-family: 'remixicon' !important;
    font-size: 16px;
    font-weight: 580;
  }

  .vue-quill-editor .vab-quill .ql-vab-upload-image:before {
    content: '\ee46';
  }
</style>
