<template>
  <div>

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

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

  export default {
    name: "my-ueditor",

    props: {
      ossTokenUrl: {
        type: String
      },
      ossWebPath: {
        type: String
      },
      ossDir: {
        type: String
      },
      /**
       * 编辑器宽度
       */
      width: {
        type: String,
        default: '100%'
      },
      /**
       * 编辑器高度 单位px
       */
      height: {
        type: Number,
        default: 500
      },
      /**
       * Ueditor的路径
       */
      resPath: {
        type: String,
        default: '/ueditor/'
      },
      /**
       * 初始化时的参数
       */
      config: {
        type: Object,
        default: {}
      },
      /**
       * 编辑器内容
       */
      value: {
        type: String,
        default: ''
      }
    },
    data() {
      return {
        ue: undefined,
        editorId: 'editor' + Global.newId()
      }
    },
    created() {
      window.UEDITOR_HOME_URL = this.resPath;
    },
    mounted() {
      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);
          this.ue.ready(() => {
            this.ue.setContent(this.value);
            setTimeout(() => {
              this.ue.addListener("selectionchange", () => {
                this.$emit('input', this.ue.getContent());
                this.$emit('change');
              });
            }, 100);
          });
        });
      },
      /**
       * 渲染
       */
      display() {
        if (this.ue) {
          this.ue.ready(() => {
            this.ue.setContent(this.value);
          });
        } else {
          setTimeout(() => {
            this.display();
          }, 300)
        }
      },

      clear() {
        if (this.ue) {
          this.ue.ready(() => {
            this.ue.setContent('');
          });
        } else {
          setTimeout(() => {
            this.clear();
          }, 300)
        }

      },

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

      },
      insertImg(imgUrl) {
        this.ue.execCommand('inserthtml', '<img src="' + imgUrl + '" class="img-responsive" style="max-width:100%;" />');
      }
    },
    destroyed() {
      if (this.ue) {
        this.ue.destroy();
      }
    }
  }
</script>

<style scoped>

</style>
