<template id="app-rich-text">
  <div class="app-rich-text">
    <textarea style="width: 100%" :id="id"></textarea>
  </div>
</template>
<script>
  //   import appAttachment from '../attachment/app-attachment'
  export default {
    props: {
      value: null,
      //上传单选还是多选
      uploadMultple: false,
      //文件单选还是多选
      chooseMultple: false,
      //插入图片图标
      labelIcon: {
        type: String,
        default: '插入图片',
      },
      //是否显示插入图片
      isShowInsertImage: {
        type: Boolean,
        default: true
      },
      //是否显示上传附件
      isShowAttachment: {
        type: Boolean,
        default: true
      },
      //是否显示音频
      isShowVoice: {
        type: Boolean,
        default: true
      },
      //UEEditor配置信息
      config: {
        type: Object
      },
      noMargin: {
        type: Boolean,
        default: false
      },
      placeHolder: {
        type: String,
        default: '请输入内容',
      },
    },
    components: {
      //   appAttachment
    },
    data() {
      return {
        attachmentDialogVisible: false, //上传附件弹窗
        id: 'app-rich-text-' + (Math.floor((Math.random() * 10000) + 1)),
        ue: null,
        tempContent: this.value,
        isInputChange: false,
        uploadType: "1", //1-上传图片，2-上传附件,3-上传音频
        //默认图片域名
        defaultImgDomain: "",
        ViewDomain: "",
      };
    },
    watch: {
      value(newVal, oldVal) {
        if (!this.isInputChange) {
          if (this.ue) {
            if (this.ue.isReady !== 1) {
              let self = this;

              let time = setInterval(() => {
                //循环查
                if (self.ue.isReady === 1) {
                  clearInterval(time);
                  self.ue.setContent(newVal);
                  self.isInputChange = false;
                }
              }, 100);
              return;
            }
            ("监听到变化", newVal)
            this.ue.setContent(newVal);
          } else {
            this.tempContent = newVal;
          }
        }
        this.isInputChange = false;
      },
    },
    created() {
      this.ViewDomain = this.domainManager().ViewFileUrl;
    },
    mounted() {
      this.loadUe();
    },
    methods: {
      focus() {
        this.ue.focus(true)
      },
      //插入图片
      instertImage(fileArray) {
        if (fileArray && fileArray.length) {
          let html = '';
          //s视频
          fileArray.forEach(item => {
            html += '<img src="' + item.fileUrl + '" style="max-width: 100%;">';
          })
          if (html && html != '') {
            this.ue.execCommand('inserthtml', html);
          }
        }

      },
      insertVideo(fileArray) { //插入视频
        if (fileArray && fileArray.length) {
          let html = '';
          //s视频
          fileArray.forEach(item => {
            html +=
              "<iframe frameborder='0' width='100%' height='200px' src='https://v.qq.com/iframe/player.html?vid=v326875u4ek' allowfullscreen='true'></iframe>"

          })
          if (html && html != '') {
            this.ue.execCommand('inserthtml', html);
          }
        }
      },
      insertaudio(fileArray) { //插入音频

        if (fileArray && fileArray.length) {
          let html = '';
          //音频
          fileArray.forEach(item => {
            html += `<p><audio src="${item.fileUrl}" controls="controls"></audio></p>`
            // html += `<mpvoice class="js_editor_audio audio_iframe js_uneditable custom_select_card" 
            // src="/cgi-bin/readtemplate?t=tmpl/audio_tmpl&amp;name=111111.mp3&amp;play_length=04:47"  name="3343434.mp3" play_length="287000" 
            // voice_encode_fileid="LZ-rcf9d76p-zSl-cKLq1df9pxdAefsq406nXcoz4Zc" data-topic_id="" data-topic_name="" data-pluginname="insertaudio"></mpvoice>`

          })
          if (html && html != '') {
            this.ue.execCommand('inserthtml', html);
          }
        }
      },
      hyperlinks(fileArray) {
        if (fileArray && fileArray.length) {
          let html = '';
          //超链接
          fileArray.forEach(item => {
            html +=
              `<p><a class='weapp_text_link' style="color: #576b95;text-decoration: none;" target="_self" href="${item.fileUrl}" data-itemshowtype="0" tab="innerlink" style='text-decoration:none;color: #576b95;' _href="${item.fileUrl}">${item.fileName}</a></p>`;
          })
          if (html && html != '') {
            // html.setAttr('style','display:block;margin:0 auto;');
            this.ue.execCommand('inserthtml', html);
          }
        }
      },
      applet(data) {
        let html = '';
        if (data.type == 1) { //文字小程序
          html +=
            `<p><a data-miniprogram-appid="${data.appletmsg.AppID}" data-miniprogram-path="${data.route}" href="">${data.title}</a></p>`;

        } else if (data.type == 2) { //图片小程序
          html +=
            `<p><a data-miniprogram-appid="${data.appletmsg.AppID}" data-miniprogram-path="${data.route}" href=""><img src="${data.imgUrl}" alt="" data-width="null" ></a></p>`
        } else if (data.type == 3) {
          let dataTime = Date.parse(new Date())
          // 给公众号的写法
          html +=
            `<mp-miniprogram data-time="${dataTime}" data-miniprogram-appid="${data.appletmsg.AppID}" data-miniprogram-path="${data.route}"   
          data-miniprogram-title="${data.title}" 
          data-miniprogram-imageurl="${data.imgUrl}" 
          data-miniprogram-type="card" data-miniprogram-servicetype="0"></mp-miniprogram><span data-time="${dataTime}"></span>`
          //自己看的写法
          html += '<p><iframe height="320" width="auto" data-time=' + dataTime + ' data-miniprogram-appid=' + data
            .appletmsg.AppID + ' frameborder="0"  allowtransparency="true" ' +
            ' style="background-color:transparent;border-radius: 3px;overflow: hidden;z-index: 0;" scrolling="no" ' +
            ' src="http://edu.oytour.com/#/teacher/contribution/graphicType?Name=' + data.appletmsg.Name + '&Image=' +
            data.appletmsg.Image + '&title=' + data.title + '&imgUrl=' + data.imgUrl +
            '" class="ans-insertaudio-module" module="_insertaudio">' + ' </iframe><span data-time=' + dataTime +
            '></span></p>';

        }

        if (html && html != '') {
          this.ue.execCommand('inserthtml', html);
        }
      },


      //获取文件图标和类型
      getIcon(fileName) {
        var obj = {
          iconUrl: "",
          dataType: "",
          fileType: 0, //1视频，2-pdf,3-word、ppt、xls,4-mp3
        }
        if (!fileName) {
          obj.iconUrl = this.defaultImgDomain + "file.png";
          obj.dataType = "";
          return obj;
        }
        var index = fileName.lastIndexOf('.');
        var type = fileName.substr(index + 1);
        type = type.toLowerCase();
        obj.dataType = type;
        if (type === 'video' || type === 'svideo') {
          obj.iconUrl = this.defaultImgDomain + "video.png";
          obj.fileType = 1;
        } else if (type === 'txt' || type === 'text') {
          obj.iconUrl = this.defaultImgDomain + "txt.png";
        } else if (type === 'xls' || type === 'xlsx') {
          obj.iconUrl = this.defaultImgDomain + "excel.png";
          obj.fileType = 3;
        } else if (type === 'doc' || type === 'docx') {
          obj.iconUrl = this.defaultImgDomain + "word.png";
          obj.fileType = 3;
        } else if (type === 'zip' || type === 'rar' || type === 'gz') {
          obj.iconUrl = this.defaultImgDomain + "zip.png";
        } else if (type === 'mp3') {
          obj.iconUrl = this.defaultImgDomain + "sound.png";
          obj.fileType = 4;
        } else if (type === 'pdf') {
          obj.iconUrl = this.defaultImgDomain + "pdf.png";
          obj.fileType = 2;
        } else if (type === 'ppt' || type === 'pptx') {
          obj.iconUrl = this.defaultImgDomain + "ppt.png";
          obj.fileType = 3;
        } else if (type === 'avi' || type === 'rmvb' || type === '3gp' || type === 'mpg' ||
          type === 'mpeg' || type === 'mov' || type === 'wmv' || type === 'asf' ||
          type === 'mkv' || type === 'mp4' || type === 'vob' || type === 'f4v' ||
          type === 'flv') {
          obj.iconUrl = this.defaultImgDomain + "movie.png";
          obj.fileType = 1;
        } else {
          obj.iconUrl = this.defaultImgDomain + "unknown.png";
        }
        return obj;
      },



      loadUe() {
        const _this = this;

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

        this.ue.addListener('ready', editor => {
          this.$emit("ready")
          if (this.tempContent) {
            this.ue.setContent(this.tempContent);
          }
          if (this.noMargin) {
            UE.dom.domUtils.setStyles(this.ue.body, {
              'margin': '0px'
            });
          }
        });
        this.ue.addListener('keyup', editor => {
          this.isInputChange = true;
        });
        this.ue.addListener('contentChange', (editor, e) => {
          this.isInputChange = true;
          this.$emit('input', this.ue.getContent(), this.ue.getContentTxt().length);
        });
        this.ue.addListener('blur', editor => {
          this.isInputChange = true;
          this.$emit('blur', this.ue.getContent());
        });
        this.ue.addListener('focus', editor => {
          this.$emit('focus');
        });
        this.ue.addListener('selectionchange', editor => {

        })
        this.ue.addListener('click', (editor, a) => {

        })
      }
    },
  }
</script>
<style scoped>

</style>