<template>
  <div :id="id" class="edit-box"> </div>
</template>

<script>
import WangEditor from 'wangeditor'
export default {
  props: ['value'],
  data() {
    return {
      id: '',
      editor: null,
    }
  },
  created() {
    let date = new Date()
    this.id = 'wangeditor_' + date.getTime()
  },
  mounted() {
    this.init()
  },
  methods: {
    init() {
      let domId = `#${this.id}`
      this.editor = new WangEditor(domId)
      this.editor.config.uploadImgShowBase64 = true

      this.editor.config.uploadImgServer =this.config.apiUrl + 'sys_file/upload_oos_img'
      this.editor.config.uploadImgHooks = {
        customInsert: (insertImg, result, editor) => {
          var url = result.data.path
          insertImg(url)
        },
      }

      this.editor.config.menus = [
        'head', // 标题
        'bold', // 粗体
        'fontSize', // 字号
        'fontName', // 字体
        'italic', // 斜体
        'underline', // 下划线
        'strikeThrough', // 删除线
        'foreColor', // 文字颜色
        'backColor', // 背景颜色
        'link', // 插入链接
        'list', // 列表
        'justify', // 对齐方式
        'image', // 插入图片
        'fullscreen', // 全屏
      ]

      this.editor.config.pasteTextHandle = function (content) {
        if (content === '' && !content) return ''
        var str = content
        str = str.replace(/<xml>[\s\S]*?<\/xml>/gi, '')
        str = str.replace(/<style>[\s\S]*?<\/style>/gi, '')
        str = str.replace(/<\/?[^>]*>/g, '')
        str = str.replace(/[ | ]*\n/g, '\n')
        str = str.replace(/&nbsp;/gi, '')
        str = str.replace(/spanyes'/gi, 'div')
        str = str.replace(/spanyes'/gi, '')
        str = str.replace(/';/gi, '')
        str = str.replace(/spanyes'/gi, 'span')
        str = str.replace(/<\/font>/gi, '')
        return str
      }

      this.editor.config.onchange = (newHtml) => {
        this.$emit('input', newHtml)
      }

      this.editor.create()

      this.editor.$textElem.css('text-align', 'left')
      // 初始化设置值
      if (this.value) {
        this.setHtml(this.value)
      }
    },
    getHtml() {
      return this.editor.txt.html()
    },
    setHtml(text) {
      this.editor.txt.html(text)
    },
  },
}
</script>

<style lang="less" scoped>
.edit-box {
  width: 100%;
}
</style>
