<template>
  <a-spin :spinning="loading">
    <div class="wangeditor-atkj-wrapper">
      <Toolbar
        style="border-bottom: 1px solid #ccc"
        :editor="editor"
        :defaultConfig="toolbarConfig"
        :mode="mode"
      />
      <Editor
        :style="`height: ${height}px; overflow-y: auto`"
        v-model="html"
        :defaultConfig="editorConfig"
        :mode="mode"
        @onCreated="onCreated"
      />
    </div>
  </a-spin>
</template>
<script>
// 引入 wangEditor
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import '@wangeditor/editor/dist/css/style.css'

export default {
  name: 'RichTextEditor',
  components: { Editor, Toolbar },
  props: {
    height: {
      type: Number,
      default: () => 300
    },
    videoSizeLimit: {
      type: Number,
      default: () => 100
    },
    isSessionStorage: {
      type: Boolean,
      default: () => true
    }
  },

  data() {
    return {
      editor: null,
      loading: false,
      html: '<p><br></p>',
      editorConfig: {
        MENU_CONF: {
          uploadImage: {
            server: `${process.env.VUE_APP_URL}upload?fileType=IMG`,
            timeout: 5000,
            fieldName: 'files',
            headers: { Authorization: this.getToken() },
            customInsert: function (result, insertImgFn) {
              insertImgFn(result.data.urls[0])
            }
          },
          uploadVideo: {
            server: `${process.env.VUE_APP_URL}upload?fileType=VIDEO`,
            timeout: 5000,
            fieldName: 'files',
            headers: { Authorization: this.getToken() },
            onBeforeUpload() {
              this.loading = true
            },
            onFailed() {
              this.loading = false
            },
            onError() {
              this.loading = false
            },
            customInsert(res, insertFn) {
              if (res.code == 200) {
                insertFn(res.data.urls[0])
              } else {
                this.$message.error('上传失败')
                this.loading = false
              }
            }
          }
        }
      },
      toolbarConfig: {},
      mode: 'default'
    }
  },
  beforeDestroy() {
    const editor = this.editor
    if (editor == null) return
    editor.destroy()
  },

  methods: {
    onCreated(editor) {
      this.editor = Object.seal(editor) // 一定要用 Object.seal() ，否则会报错
    },
    // 设置内容
    setContent(v) {
      console.info('got data', v)
      this.$nextTick(() => {
        this.html = v
      })
    },
    // 获取内容
    getContent() {
      return this.html
    },
    // 清空内容
    clear() {
      this.html = '<p></p>'
    },
    getToken() {
      return sessionStorage.getItem('Access-Token')
    }
  }
}
</script>

<style lang="less">
.wangeditor-atkj-wrapper {
  border: 1px solid rgb(243, 243, 243);
  z-index: 100; /* 按需定义 */
  .wangeditor-toolbar-container {
    border-bottom: 1px solid #ccc;
  }
}
</style>
