<template>
  <div id="editor"></div>
</template>
<script>
import E from 'wangeditor';
import MyMenu from '@lib/editorButtom.js';
import $axios from '@lib/axios.js';
export default ({
  components: {},
  props: {
    value: {
      type: String,
      default: ''
    },
    isClear: {
      type: Boolean,
      default: false
    }
  },
  watch: {
    isClear (val) {
      // 触发清除文本域内容
      if (val) {
        this.editor.txt.clear();
        this.info_ = null;
      }
    },
    value: function (value) {
      if (value !== this.editor.txt.html()) {
        this.editor.txt.html(this.value);
      }
    }
    // value为编辑框输入的内容，这里我监听了一下值，当父组件调用得时候，如果给value赋值了，子组件将会显示父组件赋给的值
  },
  data() {
    return {
      editor: null,
      html: '',
      toolbarConfig: {
        insertKeys: {
          index: 1, // 插入的位置，基于当前的 toolbarKeys
          keys: ['menu1']
        }
      },
      editorConfig: { placeholder: '请输入内容...' },
      mode: 'default' // or 'simple'
    };
  },
  methods: {
    init() {
      this.editor = new E('#editor');
      E.registerMenu('menu1', MyMenu);
      this.editor.config.height = 500;
      this.editor.config.uploadImgShowBase64 = false; // base 64 存储图片
      this.editor.config.uploadImgMaxSize = 50 * 1024 * 1024; // 将图片大小限制为 2M
      this.editor.config.uploadImgMaxLength = 1; // 限制一次最多上传 3 张图片
      this.editor.config.uploadImgTimeout = 3 * 60 * 1000; // 设置超时时间
      this.editor.config.showLinkImg = false;
      // 自定义文件上传
      this.editor.config.customUploadImg = async function (resultFiles, insertImgFn) {
        // resultFiles 是 input 中选中的文件列表
        var data = new FormData();
        const filesUpload = '/api/files/filestore/upload';
        data.append('file', resultFiles[0]);
        const headers = {
          'Content-Type': 'multipart/form-data'
        };
        const res = await $axios.post(filesUpload, data, null, headers);
        const url = res.data.filePath;
        // 上传图片，返回结果，将图片插入到编辑器中
        insertImgFn(url);
      };
      // 自定义上传视频
      // this.editor.config.onlineVideoCheck = (src) => {
      //   const videoMod = `<iframe src="${src}"> </iframe>`;
      //   // this.editor.txt.append(videoMod);
      //   this.editor.cmd.do('insertHTML', videoMod);
      // };
      this.editor.config.onchange = (html) => {
        this.info_ = html; // 绑定当前逐渐地值
        this.$emit('change', this.info_); // 将内容同步到父组件中
      };
      // this.editor.config.onchangeTimeout = 50;
      this.editor.create();
    }
  },
  mounted() {
    this.init();
    this.editor.txt.html(this.value);
  }
});
</script>
<style lang="scss" scoped>
button {
  background: none;
  border: none;
}
</style>
