<template>
  <div class="tinymce-editor">
    <Editor :id="editorId" v-model="value" :init="editorInit" />
  </div>
</template>
 
<script>
//引入tinymce编辑器
import { useStore } from 'vuex'
import Editor from '@tinymce/tinymce-vue';
//引入方式引入node_modules里的tinymce相关文件文件
import tinymce from 'tinymce/tinymce'; //tinymce默认hidden，不引入则不显示编辑器
import 'tinymce/themes/silver'; //编辑器主题，不引入则报错
import 'tinymce/icons/default'; //引入编辑器图标icon，不引入则不显示对应图标
// 扩展插件
import 'tinymce/plugins/advlist' //高级列表
import 'tinymce/plugins/anchor' //锚点
import 'tinymce/plugins/autolink' //自动链接
import 'tinymce/plugins/autoresize' //编辑器高度自适应,注：plugins里引入此插件时，Init里设置的height将失效
import 'tinymce/plugins/autosave' //自动存稿
import 'tinymce/plugins/charmap' //特殊字符
import 'tinymce/plugins/code' //编辑源码
import 'tinymce/plugins/codesample' //代码示例
import 'tinymce/plugins/directionality' //文字方向
import 'tinymce/plugins/fullscreen' //全屏
import 'tinymce/plugins/help' //帮助
import 'tinymce/plugins/image' //插入编辑图片
import '/public/tinymce/axupimgs/plugin.js' //插入编辑图片
import 'tinymce/plugins/importcss' //引入css
import 'tinymce/plugins/insertdatetime' //插入日期时间
import 'tinymce/plugins/link' //超链接
import 'tinymce/plugins/lists' //列表插件
import 'tinymce/plugins/media' //插入编辑媒体
import 'tinymce/plugins/nonbreaking' //插入不间断空格
import 'tinymce/plugins/pagebreak' //插入分页符
import 'tinymce/plugins/preview' //预览
import 'tinymce/plugins/quickbars' //快速工具栏
import 'tinymce/plugins/save' //保存
import 'tinymce/plugins/searchreplace' //查找替换
import 'tinymce/plugins/table' //表格
import 'tinymce/plugins/template' //内容模板
import 'tinymce/plugins/visualblocks' //显示元素范围
import 'tinymce/plugins/visualchars' //显示不可见字符
import 'tinymce/plugins/wordcount' //字数统计
import 'tinymce/plugins/print'
import 'tinymce/plugins/hr'
import 'tinymce/plugins/textpattern'
import axios from 'axios'
export default {
  name: 'TinymceEditor',
  components: { Editor },
  props: {
    height: {
      type: Number,
      default: 500,
    },
    id: {
      type: String,
      default: 'tinymceEditor',
    },
    curValue: {
      type: String,
      default: '',
    },
    plugins: {
      type: [String, Array],
      default:
        'preview searchreplace autolink directionality visualblocks visualchars fullscreen image link media template code codesample table charmap pagebreak nonbreaking anchor insertdatetime advlist lists wordcount autosave axupimgs',
    },
    toolbar: {
      type: [String, Array],
      default: ' image | preview',
    },
  },
  data () {
    return {
      store: useStore(),
      editorInit: {
        language_url: '/tinymce/langs/zh_CN.js',
        language: 'zh_CN',
        skin_url: '/tinymce/skins/ui/oxide',
        content_css: '/tinymce/skins/content/default/content.css',
        height: this.height,
        content_style:
          '* { padding:0; margin:0; } img {max-width:100% !important }',
        plugin_preview_width: 375, // 预览宽度
        plugin_preview_height: 668,
        lineheight_val:
          '1 1.1 1.2 1.3 1.35 1.4 1.5 1.55 1.6 1.75 1.8 1.9 1.95 2 2.1 2.2 2.3 2.4 2.5 2.6 2.7 2.8 3 3.1 3.2 3.3 3.4 4 5',
        fontsize_formats:
          '8pt 10pt 11pt 12pt 13pt 14pt 15pt 16pt 17pt 18pt 24pt 36pt',
        font_formats:
          "微软雅黑='微软雅黑';宋体='宋体';黑体='黑体';仿宋='仿宋';楷体='楷体';隶书='隶书';幼圆='幼圆';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",
        plugins: this.plugins,
        powerpaste_word_import: 'merge',
        toolbar: this.toolbar,
        paste_data_images: true,
        statusbar: true, // 底部的状态栏
        menubar: false, // 最上方的菜单
        branding: false, // 水印“Powered by TinyMCE”
        images_upload_handler: (blobInfo, success, failure) => {
          if (blobInfo.blob().size / 1024 / 1024 > 2) {
            failure('上传失败，图片大小请控制在2M以内!')
            // ElMessage.error('上传失败，图片大小请控制在2M以内!')
          } else {
            const formdata = new FormData()
            formdata.set('file', blobInfo.blob())
            formdata.set('type', 'images')
            // 上传到服务器后要改地址
            // 这个地址是我自己后台上传图片的地址，改成自己后台上传图片的地址http://localhost:8088/api/upload/img/
            axios.post(process.env.VUE_APP_API_BASEURL + '/admin/project/upload/file', formdata, {
              withCredentials: true,
            },).then((res) => {
              // 上传到服务器后要改地址
              // 这个地址是我图片映射路径http://localhost:8088/images/，可以用nginx
              // success("http://oricoadmin.com/admin/goods/uploadImg"+res.data.data.url)
              // let data = res.data.data
              success(res.data.data.fileurl)
              // data.forEach(ele => {
              //   success(ele.fileurl)
              // })
            })
              .catch((res) => {
                failure('error')
              })
          }
        },
      },
      editorId: this.id,
      value: '',
    }
  },
  watch: {
    // 动态传参
    curValue (newValue) {
      this.value = newValue
    },
    // 动态传参高度
    height (newValue) {
      this.editorInit.height = newValue
      this.$forceUpdate()
    },
    // 读取输入框内的数据
    value (newValue) {
      this.$emit('input', newValue)
    },
  },
  mounted () {
    tinymce.init({
      selector: '#tinydemo',
      plugins: 'code image axupimgs',
      toolbar: 'code axupimgs',
      images_upload_handler: function (blobInfo, succFun, failFun) {
        var xhr, formData
        var file = blobInfo.blob() //转化为易于理解的file对象
        xhr = new XMLHttpRequest()
        xhr.withCredentials = false
        xhr.open(
          'POST',
          process.env.VUE_APP_API_BASEURL + 'admin/upload/addUpload'
        )
        xhr.onload = function () {
          var json
          if (xhr.status != 200) {
            failFun('HTTP Error: ' + xhr.status)
            return
          }
          json = JSON.parse(xhr.responseText)
          if (!json || typeof json.location != 'string') {
            failFun('Invalid JSON: ' + xhr.responseText)
            return
          }
          succFun(json.location)
        }
        formData = new FormData()
        formData.append('file', file, file.name)
        xhr.send(formData)
      },
    })
  },
  computed: {
    editorValue: {
      get () {
        return this.value
      },
      set (val) {
        this.newValue = val
      },
    },
  },
  methods: {
    // https://github.com/tinymce/tinymce-vue => All available events
    clear () {
      this.editorValue = ''
    },
  },
}
</script>