<template>
  <div :id="editorId" :style="{'height':height+'px','width':width}"></div>
</template>

<script>
  import {loadRes, loadModule} from '../math/load';
  import {Global} from '../math/global';


  export default {
    name: "my-ueditor",
    props: {
      /**
       * 编辑器宽度
       */
      width: {
        type: String,
        default: '100%'
      },
      /**
       * 编辑器高度 单位px
       */
      height: {
        type: Number,
        default: 500
      },
      /**
       * Ueditor的路径
       */
      resPath: {
        type: String,
        default: '/ueditor/'
      },
      /**
       * 初始化时的参数
       */
      config: {
        type: Object,
        default: {}
      },
      /**
       * 是否启用实时监听，默认为false
       * 如果启用，内容发生变化时，会自动抛出'on-change'事件，参数为新的内容
       */
      watch: {
        type: Boolean,
        default: false
      }
    },
    data() {
      return {
        ue: undefined,
        content: '',
        isInit: false,
        editorId: 'editor' + Global.newId()
      }
    },
    mounted() {
      window.UEDITOR_HOME_URL = this.resPath;
      this.init();
    },
    methods: {
      init() {
        loadModule('UE',
          [this.resPath + 'ueditor.config.js', this.resPath + 'ueditor.all.min.js', this.resPath + 'lang/zh-cn/zh-cn.js'],
          [this.resPath + 'themes/default/css/ueditor.css']).then(UE => {

          this.ue = UE.getEditor(this.editorId, this.config);

          if (this.watch) {
            this.ue.addListener("selectionchange", () => {
              this.$emit('on-change', this.ue.getContent());
            });
          }
        });
      },
      getContent() {
        return this.ue.getContent();
      },
      setContent(content) {
        this.content = content;
        this.setValue();
      },
      setValue() {
        if (this.ue) {
          this.ue.ready(() => {
            this.ue.setContent(this.content);
          });
        } else {
          window.setTimeout(() => {
            this.setValue();
          }, 300);
        }
      },

      insertHtml(html) {
        this.ue.execCommand('inserthtml', html);

      }
    },
    destroyed() {
      if (this.ue) {
        this.ue.destroy();
      }
    }
  }
</script>

<style scoped>

</style>
