<template>
  <textarea :id="editorId" />
</template>

<script>
import tinymce from 'tinymce/tinymce'
import './plugin'
import { guid } from '@/utils/tools'

export default {
  name: 'HEditor',
  props: {
    // 富文本内容
    value: {
      type: String,
      default: ''
    },
    // 自定义选项
    config: {
      type: Object,
      default: () => ({})
    },
    // 控制禁用状态
    disabled: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      editor: null,
      editorId: guid()
    }
  },
  watch: {
    value(newVal, oldVal) {
      if (this.editor && newVal !== oldVal && newVal !== this.editor.getContent()) {
        this.editor.setContent(newVal)
      }
    },
    // 控制禁用
    disabled(val) {
      if (this.editor !== null) {
        this.editor.setMode(val ? 'readonly' : 'design')
      }
    }
  },
  mounted() {
    this.init()
  },
  methods: {
    init() {
      const configure = {
        selector: '#' + this.editorId,
        menubar: false,
        language: 'zh_CN',
        height: 300,
        plugins: 'table lists wordcount charmap preview code fullscreen',
        toolbar_mode: 'wrap',
        toolbar_drawer: false,
        toolbar:
          'code | undo redo | bold italic underline strikethrough | fontselect | fontsizeselect | formatselect | alignleft aligncenter alignright alignjustify | outdent indent | numlist bullist | forecolor backcolor | fullscreen preview',
        content_style: 'img {max-width: 100%;}',
        branding: false,
        skin: false,
        content_css: false,
        // 合并配置
        ...this.config,
        setup: editor => {
          this.editor = editor
          editor.on('init', e => this.initSetup(e))
        }
      }
      tinymce.init(configure)
    },
    initSetup() {
      if (!this.editor) return
      this.editor.setContent(this.value)

      this.editor.on('change keyup undo redo', () => {
        const value = this.editor.getContent()
        this.$emit('input', value)
      })
    }
  }
}
</script>

<style scoped>
@import '~tinymce/skins/ui/oxide/skin.css';

textarea {
  visibility: hidden;
}
</style>
