<template>
  <div v-loading="loading" element-loading-text="拼命加载中">
    <div ref="editor"></div>
  </div>
</template>

<script>
// 引入 wangEditor
import wangEditor from "wangeditor";

import ExtService from "@/api/ext";

export default {
  name: "wangEditorEx",
  props: {
    //  编辑器内容文本
    contentText: {
      type: String,
      default: "",
    },
    height: {
      type: Number,
      default: 300,
    },
  },
  data() {
    return {
      loading: false,
      editor: null,
      editorData: "",
    };
  },
  mounted() {
    // eslint-disable-next-line new-cap
    const editor = new wangEditor(this.$refs["editor"]);

    // 设置编辑区域高度
    editor.config.height = this.height;

    const _this = this;

    // 默认情况下，显示所有菜单
    editor.config.menus = [
      "head",
      "bold",
      "fontSize",
      "fontName",
      "italic",
      "underline",
      "strikeThrough",
      "indent",
      "lineHeight",
      "foreColor",
      "backColor",
      "link",
      "list",
      // "todo",
      "justify",
      "quote",
      // "emoticon",
      "image",
      // "video",
      "table",
      // "code",
      "splitLine",
      // "undo",
      // "redo",
    ];

    // 配置 onchange 回调函数，将数据同步到 vue 中
    editor.config.onchange = (newHtml) => {
      _this.editorData = newHtml;
      _this.$emit("change", newHtml);
    };

    // 自定义实现图片上传的过程
    editor.config.customUploadImg = function(resultFiles, insertImgFn) {
      // resultFiles 是 input 中选中的文件列表
      // insertImgFn 是获取图片 url 后，插入到编辑器的方法

      _this.loading = true;
      ExtService.attachedFileUpload(resultFiles, "message-create")
        .then((val) => {
          // 上传图片，返回结果，将图片插入到编辑器中
          insertImgFn(val.data.fileUrl);
        })
        .catch((err) => {
          _this.$message.error(err);
        })
        .finally(() => {
          _this.loading = false;
        });
    };

    editor.config.zIndex = 0;

    // 创建编辑器
    editor.create();
    this.editor = editor;

    // 设置编辑器初始化文本
    editor.txt.html(this.contentText);
  },
  methods: {
    /**
     * 获取编辑器内容
     */
    getEditorData() {
      // 通过代码获取编辑器内容
      return this.editor.txt.html();
    },

    /**
     * 设置内容；
     */
    set(content) {
      this.editor.txt.html(content);
    },

    /**
     * 清空内容;
     */
    clear() {
      this.editor.txt.clear();
    },
  },
  beforeDestroy() {
    // 调用销毁 API 对当前编辑器实例进行销毁
    this.editor.destroy();
    this.editor = null;
  },
};
</script>

<style lang="stylus"></style>
