<style>
</style>
<template id="app-rich-text">
  <div class="app-rich-text">
    <textarea style="width: 100%" :id="id"></textarea>
    <app-attachment v-show="attachmentDialogVisible" style="height:0;" :uploadMultple="uploadMultple"
      :openDialog="attachmentDialogVisible" :chooseMultple="chooseMultple" @closed="attachmentClosed"
      @selected="attachmentSelected" :uploadType="uploadType">
    </app-attachment>
  </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: "http://imgfile.oytour.com/static/",
        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)
      },
      //关闭上传文件弹窗
      attachmentClosed() {
        this.attachmentDialogVisible = false;
      },
      //选择文件弹窗
      attachmentSelected(fileArray) {
        if (fileArray && fileArray.length) {
          let html = '';
          //图片
          if (this.uploadType == 1) {
            fileArray.forEach(item => {
              html += '<img src="' + item.fileUrl + '" style="max-width: 100%;">';
            })
          }
          //附件
          else {
            fileArray.forEach(item => {
              var obj = this.getIcon(item.fileName);
              if (obj.fileType == 4) {
                html += this.audioIframeStr(item);
              } else {
                html += this.getIconContent(item);
              }
              //  else if (obj.fileType == 1 || obj.fileType == 2 || obj.fileType == 3) {
              //   html += this.fileIframeList(item, obj.fileType);
              // }
            })
          }
          if (html && html != '') {
            this.ue.execCommand('inserthtml', html);
          }
        }
        this.attachmentDialogVisible = false;
      },
      //获取图标配置内容
      getIconContent(item) {
        var iconObj = this.getIcon(item.fileName);
        var fileUrl = encodeURIComponent(item.fileUrl);
        let dataUrl =
          `${this.ViewDomain + '/read.html?fileName=' + item.fileName + '&url=' + fileUrl + '&fileType=' + iconObj.fileType}`;
        var linkAttr = "";
        if (iconObj.fileType == 1 || iconObj.fileType == 2 || iconObj.fileType == 3) {
          linkAttr = ` class='attachNew' accessKey='${dataUrl}'`;
        }
       var str=
        `<p ${linkAttr}>`+
          `<span ${linkAttr} contenteditable="false" style="display:inline-block;margin-top:10px;background: #F7F8FA;padding: 14px 16px;min-width: 572px;overflow: hidden;cursor:pointer;-webkit-box-align: center;text-align:left;cursor:pointer;" name="${iconObj.dataType}" data="${item.fileName}">`+
            `<img ${linkAttr} src="${iconObj.iconUrl}" style="width:42px; height:42px; overflow:hidden; margin-right:14px;border-radius:4px;float:left;">`+
            `<span ${linkAttr} style="font-size:14px; color:#181E33; line-height:20px; display:block; overflow:hidden;  text-overflow:ellipsis;margin-top:15px;">${item.fileName}</span>`+
          `</span>`+
         `</p>`;
         return str;
      },
      //获取文件图标和类型
      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;
      },
      //音频[MP3]
      audioIframeStr(data) {
        var fileUrl = encodeURIComponent(data.fileUrl);
        return '<p><iframe height="62px" width="auto" frameborder="0"  allowtransparency="true" ' +
          ' style="background-color:transparent;border-radius: 3px;overflow: hidden;z-index: 0;" scrolling="no" ' +
          ' src="' + this.ViewDomain + '/index.html?fileName=' + data.fileName + '&url=' + fileUrl +
          '" class="ans-insertaudio-module" module="_insertaudio">' + ' </iframe></p>';
      },
      //视频、PDF、WORD、PPT、EXCEL
      fileIframeList(data, fileType) {
        //视频1 音频 2  ppt/word 3
        var fileUrl = encodeURIComponent(data.fileUrl);
        return '<p><iframe height="62px" width="auto" frameborder="0"  allowtransparency="true" ' +
          ' style="background-color:transparent;border-radius: 3px;overflow: hidden;z-index: 0;" scrolling="no" ' +
          ' src="' + this.ViewDomain + '/read.html?fileName=' + data.fileName + '&url=' + fileUrl + '&fileType=' +
          fileType +
          '" class="ans-insertaudio-module" module="_insertaudio">' + ' </iframe></p>';
      },
      reloadNewValue(){
        this.isInputChange=false
      },
      loadUe() {
        const _this = this;
        //上传附件
        if (_this.isShowInsertImage) {
          UE.registerUI('self-image', (editor, uiName) => {
            return new UE.ui.Button({
              name: uiName,
              title: _this.labelIcon,
              onclick() {
                _this.ue = editor
                _this.uploadType = "1"
                _this.attachmentDialogVisible = true;
              },
            });
          });
        }
        //上传附件
        if (_this.isShowAttachment) {
          UE.registerUI('self-attachment', (editor, uiName) => {
            return new UE.ui.Button({
              name: uiName,
              title: "附件",
              onclick() {
                _this.ue = editor
                _this.uploadType = "2"
                _this.attachmentDialogVisible = true;
              },
            });
          });
        }
        //是否显示音频
        if (_this.isShowVoice) {
          UE.registerUI('self-video', (editor, uiName) => {
            return new UE.ui.Button({
              name: uiName,
              title: "音频",
              onclick() {
                _this.ue = editor
                _this.uploadType = "3"
                _this.attachmentDialogVisible = true;
              },
            });
          });
        }
        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.$emit('input', this.ue.getContent());
        });
        this.ue.addListener('contentChange', editor => {
          this.isInputChange = true;
          this.$emit('input', this.ue.getContent());
        });
        this.ue.addListener('blur', editor => {
          this.isInputChange = true;
          this.$emit('blur', this.ue.getContent());
        });
        this.ue.addListener('focus', editor => {
          this.$emit('focus');
        });
      }
    },
  }

</script>
