<template>
  <div ref="editor"></div>
</template>

<script>
import E from 'wangeditor'
import uploadImage from '../utils/uploadImage'

export default {
  name: 'RichEditor',
  props: [
    'value',
    'setting'
  ],
  data () {
    return {
      editor: undefined,
      html: '',
    }
  },
  watch: {
    'value': {
      handler (newVal) {
        const newTxt = this.getHtmlTxt(newVal)
        const oriTxt = this.getHtmlTxt(this.html)

        if (newTxt != oriTxt) {
          this.updateContent(newVal)
          this.initedContent = true
        }
      },
      immediate: true,
    }
  },
  mounted () {
    this.$nextTick(() => this.initEditor())
  },
  methods: {
    initEditor() {
      if (!this.$refs.editor) return

      const editor = new E(this.$refs.editor)
      this.editor = editor

      if (this.setting) {
        editor.customConfig = this.setting
      }

      // 重定义 index
      editor.customConfig.zIndex = 100

      // 重定义 height
      // 见 style

      // 重新定义图片上传
      editor.customConfig.customUploadImg = this.uploadImg

      editor.customConfig.onchange = (html) => {
        this.html = html
        this.$emit('input', html)
      }

      editor.create()

      if (this.html) {
        editor.txt.html(this.html)
      }
    },
    uploadImg (files, insert) {
      if (files.length > 0) {
        uploadImage(files[0]).then(insert)
      }
    },
    updateContent (html) {
      this.html = html
      if (this.editor) {
        this.editor.txt.html(html)
      }
    },
    getHtmlTxt(html) {
      return (html || '').replace(/<\/?.+?\/?>/g, '')
    }
  }
}
</script>

<style>
.w-e-text-container {
  height: calc(100% - 52px) !important;
}
</style>
