<template>
  <div>
    <a-row>
      <textarea name="" :id="id"></textarea>
      <!-- <a-col :span="24" style="line-height: 1.5;">
        <span>当前字数：{{tinymceWordCount}}</span>
      </a-col> -->
    </a-row>
  </div>
</template>
<script>

export default {
  name: "myEditor",
  data () {
    return {
      tinymceWordCount: 0,
      hasChange: false,
      fullscreen: false,
    };
  },
  props: {
    id: {
      type: String,
      default: function () {
        return 'vue-tinymce-' + +new Date() + ((Math.random() * 1000).toFixed(0) + '')
      }
    },
    value: {
      type: String,
      default: () => {
        return ''
      }
    },
  },
  created () {
  },
  methods: {
    initTinymce () {
      const _this = this
      tinymce.remove(`#${_this.id}`)
      tinymce.init({
        selector: `#${_this.id}`,
        fontsize_formats: '12px 14px 16px 18px 24px 36px 48px',
        font_formats: 'PingFang SC;微软雅黑=\'微软雅黑\';宋体=\'宋体\';黑体=\'黑体\';仿宋=\'仿宋\';楷体=\'楷体\';隶书=\'隶书\';幼圆=\'幼圆\';Andale Mono=andale mono,times;Arial=arial,helvetica,sans-serif;Arial Black=arial black,avant garde;Book Antiqua=book antiqua,palatino;Comic Sans MS=comic sans ms,sans-serif;Courier New=courier new,courier;Georgia=georgia,palatino;Helvetica=helvetica;Impact=impact,chicago;Symbol=symbol;Tahoma=tahoma,arial,helvetica,sans-serif;Terminal=terminal,monaco;Times New Roman=times new roman,times;Trebuchet MS=trebuchet ms,geneva;Verdana=verdana,geneva;Webdings=webdings;Wingdings=wingdings,;sans-serif',
        language: 'zh_CN',
        body_class: 'panel-body ',
        content_style: "img {max-width:100%;}",
        // menubar: false,
        // 隐藏底部状态栏
        statusbar: false,
        height: 600,
        plugins: 'code advlist autolink link image lists preview table wordcount',
        toolbar: `undo redo | styleselect | fontsizeselect fontselect | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist | image 
                    | table tabledelete | tableprops tablerowprops tablecellprops | tableinsertrowbefore tableinsertrowafter tabledeleterow
                    | tableinsertcolbefore tableinsertcolafter tabledeletecol | wordcount`,
        // 初始化完成回调
        init_instance_callback: (editor) => {
          if (_this.value) {
            editor.setContent(_this.value)
          }
          editor.on('NodeChange Change KeyUp SetContent', () => {
            this.$emit('input', editor.getContent())
          })
        },
        // 图片上传操作
        images_upload_handler: (blobInfo, succFun, failFun) => {
          _this.$api.base.asyncUpload(this.uploadHandle(blobInfo.blob(), blobInfo.filename())).then(({ data = {} }) => {
            if (data) {
              succFun(data.downloadUrl)
            }
          }).catch((err) => {
            failFun(err)
          })
        },
        setup (editor) {
          editor.on('FullscreenStateChanged', (e) => {
            _this.fullscreen = e.state
          })
        },
      })
      // 设置富文本内容
      // tinymce.activeEditor.setContent(htmlText)
      // 监听输入计算字数
      let mark = 1
      tinymce.activeEditor.on('keyup', (e) => {
        if (mark === 1) {
          let wordcount = tinymce.activeEditor.plugins.wordcount
          this.tinymceWordCount = wordcount.body.getWordCount()
          mark = 0
          setTimeout(() => { mark = 1 }, 500)
        }
      })
    },
    uploadHandle (file, fileName) {
      let data = new FormData()
      data.append('file', file)
      data.append('fileName', fileName)
      return data
    },
    destroyTinymce () {
      const tinymce = window.tinymce.get(this.id)
      if (this.fullscreen) {
        tinymce.execCommand('mceFullScreen')
      }
      if (tinymce) {
        tinymce.destroy()
      }
    },
    setContent (value) {
      window.tinymce.get(this.id).setContent(value)
    },
    getContent () {
      window.tinymce.get(this.id).getContent()
    },
  },
  watch: {
    value (val) {
      if (!!val && !this.hasChange) {
        this.$nextTick(() => {
          this.hasChange = true
          window.tinymce.get(this.id).setContent(val)
        })
      }
    },
  },
  mounted () {
    this.initTinymce()
  },
  activated () {
    if (window.tinymce) {
      this.initTinymce()
    }
  },
  deactivated () {
    this.destroyTinymce()
  },
  destroyed () {
    this.destroyTinymce()
  },
}
</script>
