
<!--
 * @Author: 曹捷
 * @Date: 2019-08-22 15:24:21
 * @LastEditors: 曹捷
 * @LastEditTime: 2022-02-14 09:51:47
 * @Description: 编辑器组件  基于 wangeditor
    doc 地址  https://www.wangeditor.com/doc
 -->
<template>
  <div ref="editRef"></div>
  <tabWidthVue v-model:open="tableEditVisable" :dom="editRef"></tabWidthVue>
</template>

<script>
import { onMounted, onBeforeUnmount, inject, toRefs, reactive, nextTick } from 'vue'
import tabWidthVue from './tabWidth.vue'

export default {
  emits: ['blur', 'change'],
  components: {
    tabWidthVue
  },
  props: {
    value: {
      type: String
    },
    placeholder: {
      type: String,
      default: '请输入内容'
    }
  },
  setup (props, context) {
    let editor
    const E = window.wangEditor
    const { $, BtnMenu, DropListMenu, PanelMenu, DropList, Panel, Tooltip } = E
    let util = inject('util')
    let _data = reactive({
      editRef: null,
      tableEditVisable: false
    })
    class tableMenu extends BtnMenu {
      constructor(editor) {
        // data-title属性表示当鼠标悬停在该按钮上时提示该按钮的功能简述
        const $elem = E.$(
          `<div class="w-e-menu" data-title="表格宽度">
            <i class="iconfont icon-modular"></i>
            </div>`
        )
        super($elem, editor)
      }
      // 菜单点击事件
      clickHandler () {
        _data.tableEditVisable = true
      }
      tryChangeActive () {
        this.unActive()
      }
    }
    let editEvent = {
      onchange (newHtml) {
        context.emit('update:value', newHtml)
      }
    }
    onMounted(() => {
      nextTick(() => {
        editor = new E(_data.editRef)
        editor.menus.extend('tableWidth', tableMenu)
        editor.config.menus.splice(editor.config.menus.indexOf('table') + 1, 0, "tableWidth");
        editor.config.onchange = editEvent.onchange
        editor.config.placeholder = props.placeholder
        editor.config.uploadImgMaxSize = 100 * 1024 // 100KB
        editor.config.uploadImgMaxLength = 5 // 一次最多上传 5 个图片


        editor.config.uploadImgShowBase64 = true
        editor.create()
        if (props.value) {
          editor.txt.html(props.value) // 重新设置编辑器内容
        }
      })
    })
    onBeforeUnmount(() => {
      editor && editor.destroy()
      editor = null
    })
    return {
      ...toRefs(_data)
    }
  }
}
</script>

<style>
</style>