<template>
  <div :class="prefixCls" 
      style="height: 550px">
  <!--files 为后端接收参数一样  -->
    <a-upload
      name="files"
      listType="picture-card"
      class="image-uploader"
      :showUploadList="false"
      :action="uploadUrl"
      :beforeUpload="beforeUpload"
      @change="handleUpload"
    >
    </a-upload>
    <a-spin tip="上传中..." :spinning="spinning">
      <quill-editor
        v-model="content"
        ref="myQuillEditor"
      style="height: 440px"
        :options="editorOption"
        @blur="onEditorBlur($event)"
        @focus="onEditorFocus($event)"
        @ready="onEditorReady($event)"
        @change="onEditorChange($event)">
      </quill-editor>
    </a-spin>

    
    <mk-cropper ref="cropper" buttonText="" @save="selectedImage"></mk-cropper>

  </div>
</template>

<script>
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'

import { quillEditor } from 'vue-quill-editor'
import { uploadUrl } from '@/utils/request'

// 工具栏配置
const toolbarOptions = [
  ['bold', 'italic', 'underline', 'strike'],
  ['blockquote', 'code-block'],
  [{ 'header': 1 }, { 'header': 2 }],
  [{ 'list': 'ordered' }, { 'list': 'bullet' }],
  [{ 'script': 'sub' }, { 'script': 'super' }],
  [{ 'indent': '-1' }, { 'indent': '+1' }],
  [{ 'direction': 'rtl' }],
  [{ 'color': [] }, { 'background': [] }],
  [{ 'align': [] }],
  ['link', 'image', 'video'],
  ['clean']
]

export default {
  name: 'MkFormEditor',
  components: {
    quillEditor
  },
  props: {
    prefixCls: {
      type: String,
      default: 'ant-editor-quill'
    },
    // 表单校验用字段
    // eslint-disable-next-line
    value: {
      type: String
    }
  },
  data () {
    return {
      content: null,
      editorOption: {
       
        modules: {
          toolbar: {
            container: toolbarOptions,  //富文本的toolbar内容
            handlers: {  //用于监听图片上传，绑定图片
              'image': function (value) {
                if (value) {
                  document.querySelector('.image-uploader input').click()
                } else {
                  this.quill.format('image', false)
                }
              }
            }
          }
        }
      },
      uploadUrl: uploadUrl,
      spinning: false
    }
  },
  methods: {
    //验证图片
    beforeUpload (file) {
      const isImg = file.type === 'image/jpeg' || file.type === 'image/gif' || file.type === 'image/png' || file.type === 'image/bmp'
      if (!isImg) {
        this.$message.error('只能上传图片文件!')
        return false
      }
      const isLt10M = file.size / 1024 / 1024 < 10
      if (!isLt10M) {
        this.$message.error('上传图片必须小于10MB!')
        return false
      }

      let fileName = file.name; 
      var suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
      if (suffix == "png" || suffix == "jpg" || suffix == "gif" || suffix == "bmp") {
        this.$refs.cropper.show(file);
        return false;
      }

      this.spinning = true
      this.$mk.uploadFile(file, suffix, (url) => {
        this.spinning = false
        const quill = this.$refs.myQuillEditor.quill  
        // 获取光标所在位置
        const length = quill.getSelection().index
        // 插入图片  res.info为服务器返回的图片地址
        quill.insertEmbed(length, 'image', url)
        // 调整光标到最后
        quill.setSelection(length + 1)
      });


      return false; 
    },
    selectedImage({ url }) { 

      const quill = this.$refs.myQuillEditor.quill  
        // 获取光标所在位置
        const length = quill.getSelection().index
        // 插入图片  res.info为服务器返回的图片地址
        quill.insertEmbed(length, 'image', url)
        // 调整光标到最后
        quill.setSelection(length + 1)

    

    },
    //上传图片的回调函数
    handleUpload (callback) {
      const response = callback.file.response
      if (response) {
        this.spinning = false
        const quill = this.$refs.myQuillEditor.quill
        if (response.status === 10000) {
          this.imageUrl = response.data[0]
          // 获取光标所在位置
          const length = quill.getSelection().index
          // 插入图片  res.info为服务器返回的图片地址
          quill.insertEmbed(length, 'image', this.imageUrl)
          // 调整光标到最后
          quill.setSelection(length + 1)
        } else {
          this.$notification.error({
            message: '上传失败',
            description: response.message
          })
        }
      }
    },
    onEditorBlur (quill) {
      console.log('editor blur!', quill)
    },
    onEditorFocus (quill) {
      console.log('editor focus!', quill)
    },
    onEditorReady (quill) {
      console.log('editor ready!', quill)
    },
    //修改富文本
    onEditorChange ({ quill, html, text }) {
       console.log('editor change!', quill, html, text)
      this.$emit('change', html)
      this.$emit('input', html)
    }
  },
  //监听文本变化
  watch: {
    value (val) {
      this.content = val
    }
  }
}
</script>


