<template>
  <div
    :class="{ fullscreen: fullscreen }"
    class="tinymce-container"
    :style="{ width: containerWidth }"
  >
    <editor ref="tinymceEditor" v-model="content" :init="init" />
    <div class="editor-custom-btn-container">
      <editorImage
        color="#1890ff"
        class="editor-upload-btn"
        @successCBK="imageSuccessCBK"
      />
    </div>
  </div>
</template>

<script>
import tinymce from 'tinymce/tinymce'
import 'tinymce/icons/default/icons.min.js'
import 'tinymce/themes/silver/theme'
import Editor from '@tinymce/tinymce-vue'
// import plugins from './plugins'

// Here is a list of the plugin(插件)
// Detail list see https://www.tiny.cloud/docs/plugins/a11ychecker
import 'tinymce/plugins/image'
import 'tinymce/plugins/media'
import 'tinymce/plugins/table'
import 'tinymce/plugins/lists'
import 'tinymce/plugins/wordcount'
import 'tinymce/plugins/advlist'
import 'tinymce/plugins/anchor'
import 'tinymce/plugins/autolink'
import 'tinymce/plugins/autosave'
import 'tinymce/plugins/code'
import 'tinymce/plugins/codesample'
import 'tinymce/plugins/directionality'
import 'tinymce/plugins/fullscreen'
import 'tinymce/plugins/hr'
import 'tinymce/plugins/imagetools'
import 'tinymce/plugins/insertdatetime'
import 'tinymce/plugins/link'
import 'tinymce/plugins/nonbreaking'
import 'tinymce/plugins/noneditable'
import 'tinymce/plugins/pagebreak'
import 'tinymce/plugins/paste'
import 'tinymce/plugins/preview'
import 'tinymce/plugins/print'
import 'tinymce/plugins/save'
import 'tinymce/plugins/searchreplace'
import 'tinymce/plugins/spellchecker'
import 'tinymce/plugins/tabfocus'
import 'tinymce/plugins/template'
import 'tinymce/plugins/textpattern'
import 'tinymce/plugins/visualblocks'
import 'tinymce/plugins/visualchars'
import 'tinymce/plugins/wordcount'
const plugins = [
  'advlist',
  'anchor',
  'autolink',
  'autosave',
  'code',
  'codesample',
  'directionality',
  'fullscreen',
  'hr',
  'image',
  'imagetools',
  'insertdatetime',
  'link',
  'lists',
  'media',
  'nonbreaking',
  'noneditable',
  'pagebreak',
  'paste',
  'preview',
  'print',
  'save',
  'searchreplace',
  'spellchecker',
  'tabfocus',
  'table',
  'template',
  'textpattern',
  'visualblocks',
  'visualchars',
  'wordcount'
]

import editorImage from './components/EditorImage'
import toolbar from './toolbar'

import { Message } from 'element-ui'

import { uploadImage } from '@/api/goods'
import { uploadAudio, uploadVideo } from '@/api/community/list'

export default {
  name: 'TinymceEditor',
  components: { editorImage, editor: Editor },
  props: {
    id: {
      type: String,
      default: function() {
        return (
          'vue-tinymce-' +
          +new Date() +
          ((Math.random() * 1000).toFixed(0) + '')
        )
      }
    },
    value: {
      type: String,
      default: ''
    },
    toolbar: {
      type: Array,
      required: false,
      default() {
        return []
      }
    },
    menubar: {
      type: String,
      default: 'file edit insert view format table'
    },
    height: {
      type: [Number, String],
      required: false,
      default: 450
    },
    width: {
      type: [Number, String],
      required: false,
      default: 800
    }
  },
  data() {
    return {
      hasChange: false,
      hasInit: false,
      tinymceId: this.id,
      fullscreen: false,
      init: {},
      content: '',
      resVideo: '', // 上传视频的url
      uploaded: false // 有没有上传完成
    }
  },
  computed: {
    containerWidth() {
      const width = this.width
      if (/^[\d]+(\.[\d]+)?$/.test(width)) {
        // matches `100`, `'100'`
        return `${width}px`
      }
      return width
    }
  },
  watch: {
    value(val) {
      this.$nextTick(() => {
        this.content = val
      })
    }
  },
  mounted() {
    tinymce.init({})
  },
  created() {
    this.initTinymce()
  },
  activated() {
    if (window.tinymce) {
      this.initTinymce()
    }
  },
  deactivated() {
    this.destroyTinymce()
  },
  destroyed() {
    this.destroyTinymce()
  },
  methods: {
    // 初始化
    initTinymce() {
      const _this = this
      this.init = {
        skin_url: '/tinymce/skins/ui/oxide',
        language_url: `/tinymce/langs/zh_CN.js`,
        language: 'zh_CN',
        height: this.height,
        body_class: 'panel-body ',
        object_resizing: false,
        toolbar: this.toolbar.length > 0 ? this.toolbar : toolbar,
        menubar: this.menubar,
        plugins: plugins,
        end_container_on_empty_block: true,
        powerpaste_word_import: 'clean',
        code_dialog_height: 450,
        code_dialog_width: 1000,
        advlist_bullet_styles: 'square',
        advlist_number_styles: 'default',
        default_link_target: '_blank',
        link_title: false,
        nonbreaking_force_tab: true, // inserting nonbreaking space &nbsp; need Nonbreaking Space Plugin
        init_instance_callback: editor => {
          if (_this.value) {
            editor.setContent(_this.value)
          }
          _this.hasInit = true
          editor.on('NodeChange Change KeyUp SetContent', () => {
            this.hasChange = true
            this.$emit('input', editor.getContent())
          })
        },
        // 自定义上传
        file_picker_callback: function(callback, value, meta) {
          if (meta.filetype === 'media') {
            const input = document.createElement('input')
            input.setAttribute('type', 'file')
            input.onchange = function() {
              const file = this.files[0]
              _this.upload(file, 'media')
              if (_this.uploaded) {
                console.log(_this.resVideo, 'true')
                callback(_this.resVideo)
              } else {
                setTimeout(() => {
                  // 设置几秒后再去取数据
                  console.log(_this.resVideo, 'false')
                  callback(_this.resVideo)
                }, 1000)
              }
            }
            input.click()
          }
        },
        setup(editor) {
          editor.on('FullscreenStateChanged', e => {
            _this.fullscreen = e.state
          })
        },
        /**
         * 下面方法是为tinymce添加自定义插入图片按钮
         * 借助iview的Upload组件,将图片先上传到存储云上，再将图片的存储地址放入编辑器内容
         */
        // 图片上传
        images_upload_handler: function(blobInfo, success, failure) {
          var formData
          formData = new FormData()
          formData.append('file', blobInfo.blob())
          uploadImage(formData).then(res => {
            try {
              const { message, code } = res
              if (code === 200) {
                const { data } = res
                success(data)
              } else {
                Message.$message.error(message)
              }
            } catch (e) {
              console.log(`编辑器图片上传失败:${e}`)
            }
          })
        }
      }
    },
    getSub(obj) {
      const index = obj.lastIndexOf('\.')
      obj = obj.substring(index + 1, obj.length)
      return obj
    },
    // 上传音频/视频
    upload(file, type) {
      const name = this.getSub(file.name)
      const audioType = ['mp3', 'wma', 'wav', 'amr']
      if (audioType.includes(name)) {
        // 判断是Mp3格式
        const content = file
        const formData = new FormData()
        formData.append('audio', content)
        console.log(formData.get('audio'))
        uploadAudio(formData).then(res => {
          try {
            const { message, code } = res
            if (code === 200) {
              this.uploaded = true
              const { data } = res
              this.resVideo = res.data.path
              console.log(data)
            } else {
              Message.$message.error(message)
            }
          } catch (e) {
            console.log(`编辑器音频上传失败:${e}`)
          }
        })
        return false
      }
      const videoType = ['mp4', 'rm', 'rmvb', 'avi', 'mpg', 'mpeg']
      if (videoType.includes(name)) {
        // 判断是Mp4格式
        const content = file
        const formData = new FormData()
        formData.append('video', content)
        console.log(formData.get('video'))
        uploadVideo(formData).then(res => {
          try {
            const { message, code } = res
            if (code === 200) {
              this.uploaded = true
              const { data } = res
              this.resVideo = res.data.path
              console.log(data)
            } else {
              Message.$message.error(message)
            }
          } catch (e) {
            console.log(`编辑器视频上传失败:${e}`)
          }
        })
        return false
      }
      this.$message.error('请上传正确音频/视频格式')
    },
    destroyTinymce() {
      const tinymce = this.$refs.tinymceEditor
      if (this.fullscreen) {
        tinymce.execCommand('mceFullScreen')
      }

      if (tinymce) {
        tinymce.destroy()
      }
    },
    setContent(value) {
      this.content = value
    },
    getContent() {
      return this.content
    },
    imageSuccessCBK(arr) {
      const _this = this
      arr.forEach(v => {
        _this.$ref.tinymceEditor.insertContent(
          `<img class="wscnph" src="${v.url}" >`
        )
      })
    }
  }
}
</script>

<style scoped>
.tinymce-container {
  position: relative;
  line-height: normal;
}
.tinymce-container >>> .mce-fullscreen {
  z-index: 10000;
}
.tinymce-textarea {
  visibility: hidden;
  z-index: -1;
}
.editor-custom-btn-container {
  position: absolute;
  right: 4px;
  top: 4px;
  /*z-index: 2005;*/
}
.fullscreen .editor-custom-btn-container {
  z-index: 10000;
  position: fixed;
}
.editor-upload-btn {
  display: inline-block;
}
</style>
