var $ctx = "";
try {
	$ctx = document.scripts[document.scripts.length - 1].src.substr(1).match(new RegExp("(\\?|&)ctx=([^&]*)(&|$)"))[2] || "";
} catch (e) {
}
/**
 * 富文本附件监测器，
 * 监听高度变化，音视频播放事件，附件点击事件
 */
var AttachmentListener = {
	mctx: $ctx,
	mediaDefaultErrorMsg: "暂时无法播放，请稍后再试。。。",//云存储多媒体默认错误提示信息
	cropper: null,//编辑视频封面裁剪图片
	mediaPlay: function () {	}, // 播放音视频文件的方法
	loadedMediaMap: new ALMap(), // 已经加载了的音视频文件
	b64DecodeUnicode: function () {	}, // base64解码
	getVideoPics: function () {	},//获取视频截图列表
	VideoCoverEditEventinit: function () {	},/*修改视频封面点击事件*/
	imgToBase64: function () {	},//图片转base64
	uploadImg: function () {	},//上传blob图片
	blobToFile: function () {	},//blob转文件
	getHost: function (url) {	},
	noteDomain: 'http://note.yd.chaoxing.com',
	noteDomainHttps: 'https://noteyd.chaoxing.com',
	groupWebDomain: '//groupweb.chaoxing.com',
}
//获取镜像域名
try {
	AttachmentListener.noteDomain = window.obj.mirrorDomain.NoteDomain;
	AttachmentListener.noteDomainHttps = window.obj.mirrorDomain.NoteDomainHttps;
	AttachmentListener.groupWebDomain = window.obj.mirrorDomain.GroupWebDomainHttps;
} catch (e) {

}
var ua = navigator.userAgent.toLowerCase();
var isXXT = ua && ua.indexOf("chaoxingstudy") != -1 && ua.indexOf('_pc_') == -1;
AttachmentListener.b64DecodeUnicode = function (str) {
	try {
		str = decodeURIComponent(atob(str));
		//xss过滤规则
		var xssReg = new RegExp("(\\baler(?=t\\s*\\())|(\\bhref(?=\\s*=\\s*['\"]?\\s*javascript:))|(\\bsrc(?=\\s*=\\s*['\"]?\\s*javascript:))|((data|src)\\s*=['\"]?\\s*data(?=:)(?!:\\s*image))|(^[^<]*<(?=/textarea\\s*>))|(<(?=(script)|(/script)))|(<(?=(details)|(/details)))|(\\b(onstart|onafterprint|onbeforeprint|onbeforeunload|onerror|onhaschange|onload|onmessage|onoffline|ononline|onpagehide|onpageshow|onpopstate|onredo|onresize|onstorage|onundo|onunload|onblur|onchange|oncontextmenu|onfocus|onformchange|onforminput|oninput|oninvalid|onreset|onreset|onsubmit|onkey\\w*|onclick|ondblclick|ondrag\\w*|ondrop|onmouse\\w*|onscroll|ontouch\\w*)(?=(\\s*)=))", 'gi');
		str = str.replace(xssReg, function () {
			return arguments[0] + '　';
		})
	} catch (e) {

	}
	return str;
}

window.addEventListener('message', function (e) {
	var data = e.data;
	if (!data) {
		return;
	}

	if (data.msgType == 'playMedia' && !(data.fromType && data.fromType == 'h5')) { //解决h5编辑器（学习通版）编辑页和详情页同时存在时点击音频播放同时出现客户端播放器和网页播放器的问题
		// 播放音视频
		if (data.mediaType == 'video' && window.location.host.indexOf('sharewh') > -1) {
			// 分享页播放视频需要带上参数
			window.open('https://sharewh3.xuexi365.com/share/' + data.media.fileId + '/playVideo?url=' + encodeURIComponent(window.location.href));
			return;
		}else{
			window.open(window.obj.mirrorDomain.panDomain + '/preview/showpreview_' + data.media.resid + '.html');
		}
	} else if (data.msgType == 'dataChanged2') { //音频重命名用到
		// 子页面让父页面数据变化
		var editordivs = $('.edui-editor.edui-default').parent();
		if (editordivs.length > 0) {
			for (var i = 0; i < editordivs.length; i++) {
				var editorid = editordivs.eq(i).attr('id');
				var editor = UE.getEditor(editorid);
				var targetIframe = $(editor.body).find('iframe[cid="' + data.cid + '"]');
				if (targetIframe.length > 0) {
					break;
				}
			}
		}
		if (data.newData && targetIframe) {
			var str = JSON.stringify(data.newData);
			targetIframe.attr("name", RichTextUitl.b64EncodeUnicode(str));
		}
	} else if (data.msgType == 'heightChanged') { //done
		// 部分附件高度不固定，需要根据实际的内容来修改高度，例如笔记附件
		var targetIframe = getTargetIframeEditor(data).iframe
		if (targetIframe) {
			targetIframe.css('height', e.data.height);
		}
		//解决有多个非正常高度的附件时，进编辑页页面没有撑开,注释原因：设置列表会滚动到底部
		// if (typeof editor != 'undefined') {
		// 	// editor.adjustHeight();
		// 	var url = '';
		// 	try {
		// 		url = top.location.href || '';
		// 	} catch(e) {
		// 		url = document.referrer || '';
		// 	}
		// 	if(url && url.indexOf('notice') == -1 && editor.options && !editor.options.notScroll) {
		// 		// 编辑通知时，光标不需要定位到底部
		// 		if(editor.body.lastChild.offsetTop + editor.body.lastChild.clientHeight + $(editor.container).offset().top > $(window).height()) {
		// 			$(window).scrollTop(editor.body.lastChild.offsetTop + $(editor.container).offset().top)
		// 		} else {
		// 			$(window).scrollTop(0)
		// 		}
		// 	}
		// }
	} else if (data.msgType === 'editorIframeSizeChanged') {
		// 设置div.editor-iframe宽高
		var targetIframeEditor = getTargetIframeEditor(data),
			targetIframe = targetIframeEditor.iframe,
			detailIframe = targetIframeEditor.detailIframe,
			width = e.data.size[0], height = e.data.size[1];

		if (targetIframe && targetIframe.length > 0) {
			width && targetIframe.parent().css('width', width);
			height && targetIframe.parent().css('height', height);
			if(RichTextUitl.iframeDragColumn){
				if(!targetIframe.parent().parent().hasClass('drag-iframe-wrap')){
					targetIframe.parent().wrap('<div class="drag-iframe-wrap" contenteditable="false"></div>')
				}
			}else{
				targetIframe.parent().css('margin', '0 auto');
			}
			if(targetIframeEditor.editor) {
				targetIframeEditor.editor.adjustHeight();
			}
		}

		// 图表引擎 编辑详情同时存在 需设置详情视频尺寸
		if(detailIframe) {
			width && detailIframe.parent().css('width', width);
			height && detailIframe.parent().css('height', height);
			if(RichTextUitl.iframeDragColumn) {
				if (!detailIframe.parent().parent().hasClass('drag-iframe-wrap')) {
					detailIframe.parent().wrap('<div class="drag-iframe-wrap" contenteditable="false"></div>')
				}
			}else{
				detailIframe.parent().css('margin', '0 auto');
			}
		}

	} else if (data.msgType == 'getUEditor') {
		if (document.getElementsByClassName(data.className)[0]) {
			var iframeId = document.getElementsByClassName(data.className)[0].getAttribute('id');
			var dialog = window.$EDITORUI[iframeId];
			var att_editor = dialog.editor;
			var targetIframe = $(document).find('iframe[id="' + iframeId + '_iframe"]')[0];
			if (targetIframe) {
				var new_editor = {
					options: {
						themePath: att_editor.options.themePath,
						theme: att_editor.options.theme,
						langPath: att_editor.options.langPath,
						lang: att_editor.options.lang
					},
					lang: att_editor.getLang(dialog.className.split("-")[2]),
				};
				targetIframe.contentWindow.postMessage({'msgType': 'ueditor', 'editor': new_editor}, "*");
			}
		}
	} else if (data.msgType == 'execCommand') { //done
		if (!document.getElementsByClassName(data.className)[0]) {
			return;
		}
		var iframe, iframeId;
		if (!data.iframeId) {
			//未显示的弹窗iframe被移除了，只有显示的弹窗才能获取到
			iframe = $('#edui_fixedlayer').find('.' + data.className.split(' ').join('.')).find('iframe')[0];
			if (!iframe) {
				return
			}
			iframeId = iframe.id.replace(/_iframe$/, '');
		} else {
			iframeId = data.iframeId;
			iframe = $(document).find('iframe[id="' + iframeId + '_iframe"]')[0];
		}
		// 获取 dialog 对象
		var dialog = window.$EDITORUI[iframeId];
		if (!dialog) {
			console.log('未找到对应弹窗');
			return
		}
		if (data.type == 'dialog') {
			if (data.command == 'onok') {
				dialog.onok = function () {
					iframe.contentWindow.postMessage({'msgType': 'dialogOnok'}, "*");
					return false;
				};
			} else if (data.command == 'close') {
				dialog.close();
			}
		} else if (data.type == 'editor') {
			var att_editor = dialog.editor;
			if (data.command == 'insertCloudAttachment') {
				att_editor.insertCloudAttachment(data.data);
			}
			att_editor.execCommand(data.command, data.data);
			dialog.close();
		} else if (data.type == 'updateMathml') {
			//更新公式
			dialog.editor.updateMathml(data.imgindex, data.mml, data.previewUrl);
		} else if (data.type == 'inserthtml') {
			dialog.editor.execCommand('inserthtml', data.data);
			if (!data.noCloseDialog) {
				dialog.close();
			}
		} else if (data.type == 'insertBase64Img') {
			if (typeof (data.data) == 'string') {
				dialog.editor.insertBase64Img(data.data);
			} else {
				dialog.editor.insertBase64Img(data.data[0]);
			}
			dialog.close();
		} else if (data.type == 'replacehtml') {
			dialog.editor.setContent(data.content);
			dialog.close();
		} else if(data.type == 'appendhtml'){
			if(dialog.editor.document.getElementById('signDiv')){
				dialog.editor.document.getElementById('signDiv').remove()
			}
			dialog.editor.body.innerHTML += data.data
			dialog.editor.fireEvent('contentchange');
			dialog.editor.fireEvent('saveScene');
			dialog.close();
		}
	} else if (data.msgType == 'pauseAudioAndVideo') { //done
		// 事件为暂停音频播放、详情页
		var editordivs = $('.edui-editor.edui-default').parent();
		if (editordivs.length > 0) { //编辑页
			for (var i = 0; i < editordivs.length; i++) {
				var editorid = editordivs.eq(i).attr('id');
				var editor = UE.getEditor(editorid);
				var iframes = $(editor.body).find('iframe');
				for (j = 0; j < iframes.length; j++) {
					var src = iframes[j].getAttribute('src');
					if (src && (src.indexOf("insertVoice") > -1 || src.indexOf("insertVideo") > -1 || src.indexOf("insertCloud") > -1)) {
						// 处理音频附件、视频附件和云盘附件（云盘文件可能是音频文件）,通知其他音频视频停止播放，cid：当前在播放的音频iframe 的 cid
						iframes[j].contentWindow.postMessage({'cid': e.data.cid}, '*');
					}
				}
			}
		} else { //详情页
			var iframes = document.getElementsByTagName('iframe');
			for (i = 0; i < iframes.length; i++) {
				var src = iframes[i].getAttribute('src');
				if (src && (src.indexOf("insertVoice") > -1 || src.indexOf("insertVideo") > -1 || src.indexOf("insertCloud") > -1)) {
					// 处理音频附件、视频附件和云盘附件（云盘文件可能是音频文件）,通知其他音频视频停止播放，cid：当前在播放的音频iframe 的 cid
					iframes[i].contentWindow.postMessage({'cid': e.data.cid,'type':'pause'}, '*');
				}
			}
		}

		// 停止回复中的音频附件
		if ($('.Mtion-con').length > 0) {
			$('.Mtion-con').each(function () {
				if ($(this).find('audio')[0] && $(this).find('.attachItem').hasClass('play')) {
					$(this).find('audio')[0].pause();
					if ($(this).attr('type') == 'audio') {
						$(this).find('.attachImg img').attr('src', AttachmentListener.mctx + '/res/pc/images/richtext/voice_play.png');
					}
					$(this).find('.attachItem ').removeClass('play').addClass('pause');
				}
			})
		}
	} else if (data.msgType == 'openCloudPop') {
		//打开云盘弹窗
		CLOUD_POP.openCloudPop(data.att_clouddisks);
	} else if (data.msgType == 'openBatchPop') {
		//打开批量操作弹窗
		CLOUD_POP.openBatchPop();
	} else if (data.msgType == 'CLIENT_OPEN_ATTACHMENT') {
		// 通过客户端协议打开附件
		try {
			jsBridge.postNotification('CLIENT_OPEN_ATTACHMENT', data.data);
		} catch (e) {
		}
		return;
	} else if (data.msgType == 'clickEvent') {
		// 附件的点击事件
		RichtextAttachmentClickUtils.clickEvent(data.attachment, data.operationType);
	} else if (data.msgType == 'previewEvent') {
		// 附件点击打开预览
		if (isPhone) {
			window.location.href = data.previewUrl;
		} else {
			$('body').append('<a style="display:none;" id="open_attachment" target="_blank" href="' + data.previewUrl + '"></a>');
			var el = document.getElementById('open_attachment');
			el.click();//触发打开事件
			$(el).remove();
		}
	} else if (data.msgType == 'openInterfaceEvent') {
		//手机端打开附件中间页
		var att_clouddisk = data.attachment[0].att_clouddisk;
		if (!RichTextUitl.intranetMode) {
			// if(isXXT && RichtextAttachmentClickUtils.getClientVersion() >= '4.3.5.7' && window.self == window.top){
			// 	jsBridge.postNotification('CLIENT_OPEN_ATTACHMENT', data.attachment[0]);
			// }else{
			var noteDomain = window.location.protocol + '//' + AttachmentListener.getHost(AttachmentListener.noteDomainHttps)
			if(att_clouddisk.isMirror && RichTextUitl.annexMirrorPrefix) {
				noteDomain = RichTextUitl.annexMirrorPrefix
			}
			url = noteDomain + '/res/plugin/mnote/attachInterface.html?fileId=' + att_clouddisk.fileId + '&fileName=' + encodeURIComponent(att_clouddisk.name) + '&allowDownload=true&allowPreview=true&fileSize=' + att_clouddisk.fileSize + '&originUrl=' + encodeURIComponent(window.location.href);
			if(isXXT && window.self == window.top) {
				//学习通里，直接用协议打开
				jsBridge.postNotification('CLIENT_OPEN_ATTACHMENT', data.attachment[0]);
			}else if(isXXT && window.self != window.top){
				//嵌套页面
				try{
				 if(top.jsBridge){
					 top.jsBridge.postNotification('CLIENT_OPEN_ATTACHMENT', data.attachment[0]);
				 }
				}catch (e) {
					window.top.location.href = url
				}
			}else{
				window.top.location.href = url
			}
						// }
		} else {
			//镜像
			var url = RichTextUitl.prefix + 'attachment/attachInterface.html?fileId=' + att_clouddisk.fileId +
				'&fileName=' + encodeURIComponent(att_clouddisk.name) + '&isIntranetMode=' + RichTextUitl.intranetMode
				+ '&allowDownload=true&allowPreview=true&fileSize=' + att_clouddisk.fileSize
				+ '&originUrl=' + encodeURIComponent(window.location.href);
			if (att_cloud.previewUrl) {
				url += '&previewUrl=' + att_clouddisk.previewUrl;
			}
			if (att_cloud.downloadUrl) {
				url += '&downloadUrl=' + att_clouddisk.downloadUrl;
			}
			window.location.href = url;
		}
	} else if (data.msgType == 'videoCoverEdit') {
		var editordivs = $('.edui-editor.edui-default').parent();
		var editorId;
		if (editordivs.length > 0) { //编辑页
			for (var i = 0; i < editordivs.length; i++) {
				var editorid = editordivs.eq(i).attr('id');
				var editor = UE.getEditor(editorid);
				var targetIframe = $(editor.body).find('iframe[cid="' + data.cid + '"]');
				if (targetIframe.length > 0) {
					editorId = editorid;
					break;
				}
			}
		}
		//编辑视频封面
		if ($('body').children('#videoCoverEdit').length == 0) {
			var html = '<div class="maskEditor" id="videoCoverEdit"><div class="editor-opration"><div class="editorCover-top"><span>编辑封面</span><i class="close"></i></div> <div class="editorCover-center"><div class="center-topImg"><img alt="" src="' + data.media.coverUrl + '"></div> <div class="center-bottomOperation"><div class="upload-local"><div class="local-img"></div> <div class="text">上传</div> <input type="file" accept="image/*"></div> <div class="line"></div> <div class="upload-Yun"><ul class="yun-ul" style="left: 0px;"></ul> <div class="video-page-left" style="display: none;"></div> <div class="video-page-right"></div></div></div></div> <div class="editorCover-bottom"><div class="editorCover-ok">确定</div> <div class="editorCover-cancel">取消</div></div></div></div>'
			$('body').append(html);

			/*修改视频封面点击事件*/
			AttachmentListener.VideoCoverEditEventinit()
		} else {
			$('body').children('#videoCoverEdit').show();
		}
		if (data.media.playUrl) {
			//镜像
			if (!AttachmentListener.cropper) {
				AttachmentListener.cropper = new Cropper($('#videoCoverEdit .center-topImg img')[0], {
					viewMode: 2,
				});
			}
			$('#videoCoverEdit .upload-Yun').hide();
		} else {
			//公网
			var url = data.media.coverUrl;
			var objectId;
			if (url) {
				if (url.indexOf('pan-yz.chaoxing.com') > -1) {
					objectId = url.split('/')[url.split('/').length - 1].split('?')[0];
				} else if (url.indexOf('p.ananas.chaoxing.com') > -1 || url.indexOf('p.cldisk.com') > -1) {
					if(url.indexOf('star3') > -1){
						objectId = url.substring(url.lastIndexOf("/") + 1, url.lastIndexOf("."))
					}else if(url.indexOf('star4') > -1){
						objectId = url.substring(url.indexOf("star4") + 6, url.lastIndexOf("/"))
					}
				} else {
					objectId = data.media.objectId2;
				}
				if (objectId) {
					AttachmentListener.imgToBase64('objectId', objectId, function (srcdata) {
						$('#videoCoverEdit .center-topImg img').attr('src', srcdata);
						if (AttachmentListener.cropper) {
							AttachmentListener.cropper.replace(srcdata);
						} else {
							AttachmentListener.cropper = new Cropper($('#videoCoverEdit .center-topImg img')[0], {
								viewMode: 2,
							});
						}
					})
				}
				AttachmentListener.getVideoPics(data.media.objectId2);
			} else {
				if (AttachmentListener.cropper) {
					AttachmentListener.cropper.replace($('#videoCoverEdit .center-topImg img')[0]);
				} else {
					AttachmentListener.cropper = new Cropper($('#videoCoverEdit .center-topImg img')[0], {
						viewMode: 2,
					});
				}
			}
		}
		$('#videoCoverEdit').attr('iframecid', data.cid).attr('editorId', editorId);

	} else if (data.msgType == 'loadJs') {
		// 视频加载裁剪插件
		if (data.jsName == 'cropper') {
			if (typeof RichTextUitl != 'undefined') {
				if (typeof Cropper == 'undefined') {
					if (RichTextUitl.intranetMode) {
						data.url = RichTextUitl.prefix + data.url;
						data.href = RichTextUitl.prefix + data.href;
					}
					setTimeout(function () {
						if (typeof RichTextUitl != 'undefined') {
							RichTextUitl.loadScript(data.url);
							RichTextUitl.loadCssFile(data.href);
						}
					}, 1000)
				}
				RichTextUitl.loadCssFile(data.href);
			}
		}
	} else if (data.msgType == 'editTitle' && data.cid) {
		// 修改在线表格的标题(通过url传递editorId)
		var editor;
		if (data.editorId) {
			editor = UE.getEditor(data.editorId)
		} else {
			editor = ue;
		}
		var iframe = editor.iframe;
		var doc = iframe.contentDocument || iframe.document;
		var $iframe = $(doc).find('iframe[cid="' + data.cid + '"]')
		var name = $iframe.attr('name');
		var att = RichTextUitl.b64DecodeUnicode(name);
		att.att_web.title = data.title;
		name = RichTextUitl.b64EncodeUnicode(JSON.stringify(att));
		$iframe.attr('name', name);
	} else if (data.msgType == 'showTips') {
		//附件内弹提示框，用于不允许下载和预览的附件点击时弹提示
		RichTextUitl.showTips(data.msg, data.type)
	}else if (data.msgType == "drawboard") {
		var drawDialog = document.getElementsByClassName('edui-dialog edui-for-draw edui-default')[0];
		var iframe, iframeId;
		if (!drawDialog || !data.iframeId && !drawDialog.querySelector('iframe')) {
			//点击添加或修改电子签名的回调
			if(RichTextUitl.editorReplaceTarget && document.body.querySelector('#electronSignPop')){
				if(data.type == 'confirm'){
					//选中target
					var editor = UE.getEditor(document.body.querySelector('#electronSignPop').getAttribute('editorId')) || ue;
					var target = $(RichTextUitl.editorReplaceTarget).parents('.drag-image-wrap')[0] || $(RichTextUitl.editorReplaceTarget).parents('.editor-image')[0] || RichTextUitl.editorReplaceTarget
					var range = editor.selection.getRange();
					range.selectNode(target).select(true)
					var divStyle = RichTextUitl.editorReplaceTarget.tagName == 'IMG' ? RichTextUitl.editorReplaceTarget.parentNode.style.cssText : 'float:right;';
					var imgStyle = 'width:'+ RichTextUitl.editorReplaceTarget.clientWidth + 'px;'
					if (typeof (data.imgdata) == 'string') {
						editor.insertBase64Img(data.imgdata,divStyle,imgStyle,'electronSign');
					} else {
						editor.insertBase64Img(data.imgdata[0],divStyle,imgStyle,'electronSign');
					}
				}
				document.body.removeChild(document.body.querySelector('#electronSignPop'))
			}

			return;
		}else{
			//选择白板弹窗
			if (!data.iframeId) {
				//未显示的弹窗iframe被移除了，只有显示的弹窗才能获取到
				iframe = $(drawDialog).find('iframe')[0];
				iframeId = iframe.id.replace(/_iframe$/, '');
			} else {
				iframeId = data.iframeId;
				iframe = $(document).find('iframe[id="' + iframeId + '_iframe"]')[0];
			}
			// 获取 dialog 对象
			var dialog = window.$EDITORUI[iframeId];
			if (data.type == "confirm") {
				if(RichTextUitl.editorReplaceTarget){ //img标签
					var range = dialog.editor.selection.getRange();
					range.selectNode($(RichTextUitl.editorReplaceTarget).parents('.drag-image-wrap')[0] || $(RichTextUitl.editorReplaceTarget).parents('.editor-image')[0]);
					var divStyle = RichTextUitl.editorReplaceTarget.parentNode.style.cssText;
					var imgStyle = 'width:'+ RichTextUitl.editorReplaceTarget.clientWidth + 'px;'
					if (typeof (data.imgdata) == 'string') {
						dialog.editor.insertBase64Img(data.imgdata,divStyle,imgStyle);
					} else {
						dialog.editor.insertBase64Img(data.imgdata[0]);
					}
				}else{
					if (typeof (data.imgdata) == 'string') {
						dialog.editor.insertBase64Img(data.imgdata);
					} else {
						dialog.editor.insertBase64Img(data.imgdata[0]);
					}
				}
			}
			dialog.close();
		}
	}else if(data.msgType == "openCloudEvent"){
		//点击附件子页面传过来的方法来实现ppt、word点击掉“调用方”穿过来的方法
		if(data.msg && data.msg.name && typeof window[data.msg.name] == 'function' && data.msg.cid){
			window[data.msg.name](data.msg.cid,data.data)
		}
	} else if(data.msgType == 'getVideoWrapSize' && data.cid) {
		var targetIframe = getTargetIframeEditor(data).iframe
		if (targetIframe && targetIframe[0]) {
			targetIframe[0].contentWindow.postMessage({
				msgType: 'setVideoWrapSize',
				cid: data.cid,
				videoWidth: targetIframe[0].getAttribute('video-width'),
				videoHeight: targetIframe[0].getAttribute('video-height'),
				isRange: targetIframe.parents('.drag-iframe-wrap').length > 0 && targetIframe.parents('.drag-iframe-wrap').find('iframe').length > 1 ? true : false
			}, '*')
		}
	}
})


/**
 * description ：播放富文本中的音视频
 * mediaType : 播放的资源类型（audio：音频； video：视频）
 * media : 对应的音视频文件
 */
AttachmentListener.mediaPlay = function (mediaType, media) {
	//异步获取附件文件地址
	var mediaErrorMsg = AttachmentListener.mediaDefaultErrorMsg;
	// 镜像编辑器是直接在附件上存的播放地址
	var url = AttachmentListener.loadedMediaMap.get(media.fileId) || media.playUrl;
	if (!url && mediaType != "audio") {//非音频获取下载地址
		if (!media.fileId) {
			return;
		}
		var noteDomain = AttachmentListener.noteDomainHttps
		if (typeof RichTextUitl != 'undefined' && RichTextUitl.intranetMode) {
			// 镜像模式，有一些数据可能是从线上迁移过去的，根据当前页面协议判断要使用的笔记服务
			if (window.location.protocol == 'http:') {
				noteDomain = AttachmentListener.noteDomain
			}
		} else {
			if (window.location.host.indexOf('course.ustc.edu.cn') != -1 || window.location.host.indexOf('istudy.szpt.edu.cn') != -1) {
				// 这两个域名做了云盘镜像，要请求定制的笔记域名，才能请求到镜像云盘
				noteDomain = RichTextUitl.convertUrl(noteDomain);
			} else if (window.location.protocol == 'http:') {
				// 其他的地址，换下域名即可
				noteDomain = AttachmentListener.noteDomain
			}
			//处理视频类型附件 存在 isMirror 并且 ==0 走公网
			try {
				if (media && Number(media.isMirror) === 0){
					noteDomain = document.location.protocol + '//' + AttachmentListener.getHost ("https://noteyd.chaoxing.com")
				}
			}catch (e){
			}
		}
		//先从镜像获取 如果失败 并且是镜像域名，从公网获取一遍
		if (window.location.host.indexOf("course.ustc.edu.cn") != -1 || window.location.host.indexOf("istudy.szpt.edu.cn") != -1
			|| window.location.host.indexOf("mooc.ucas.edu.cn") != -1) {
			let result = getCommonFileDownLoadUrl(noteDomain + "/screen/note_note/files/status/" + (media.fileId || ""));
			if ( !result ){
				noteDomain = document.location.protocol + '//' + AttachmentListener.getHost ("https://noteyd.chaoxing.com")
			}
		}
		if(media.isMirror && RichTextUitl.annexMirrorPrefix){
			noteDomain = RichTextUitl.annexMirrorPrefix
		}
		$.ajax({
			url: noteDomain + "/screen/note_note/files/status/" + (media.fileId || ""),
			data: {isMedia: mediaType == "video"},
			type: "get",
			async: false,
			xhrFields: {
				withCredentials: true
			},
			success: function (backData) {
				if (backData && backData["status"] && backData["status"] == true) {
					url = backData["url"] || "";
					if (!url) {
						if (backData["fileStatus"] == 'waiting') {
							// 文件还在转码中
							mediaErrorMsg = '文件转码中，请稍后再试'
						}
					} else {
						AttachmentListener.loadedMediaMap.put(media.fileId, url);
						return;
					}

				} else {
					if (backData && backData["msg"] && (backData["msg"] || "") != "") {
						mediaErrorMsg = backData["msg"];
					}
				}
			},
			error: function (xhr, textStatus, errorThrown) {
				var status = xhr.status;
				var errorMsg = "";
				if (status == 0) {
					mediaErrorMsg = "网络错误，请稍后重试";
				} else if (status == 503) {
					mediaErrorMsg = "请求超时，请稍后重试";
				} else {
					mediaErrorMsg = "操作失败(code:" + status + ")";
				}
			}
		});
		if (url == "") {
			if (typeof RichTextUitl != 'undefined'
				&& typeof RichTextUitl.showTips == 'function'
				&& mediaErrorMsg) {
				RichTextUitl.showTips(mediaErrorMsg, 0)
			}
			//alert(mediaErrorMsg);
			return false;
		}
	}

	//在线预览或者下载附件文件
	if (mediaType == "video") {
		//视频
		if (typeof videoPlayer != 'undefined' && videoPlayer.vars && videoPlayer.vars.video && videoPlayer.vars.video == encodeURIComponent(url)) {//如果视频存在且已经加载了，直接播放即可
			videoPlayer.videoPlay();
		} else {
			var videoObject = {
				playerID: 'ckplayer01',//播放器ID，第一个字符不能是数字，用来在使用多个播放器时监听到的函数将在所有参数最后添加一个参数用来获取播放器的内容
				container: '#video', //容器的ID或className
				//variable: 'player', //播放函数名称
				//loaded: 'loadedHandler', //当播放器加载后执行的函数
				//loop: true, //播放结束是否循环播放
				autoplay: true, //是否自动播放
				//duration: 500, //设置视频总时间
				config: '', //指定配置函数
				flashplayer: false, //强制使用flashplayer
				drag: 'start', //拖动的属性
				seek: 0, //默认跳转的时间
				video: url //视频地址
			};
			videoPlayer = new ckplayer(videoObject);
		}
		//暂停详情页的音视频播放
		var iframes = document.getElementsByTagName('iframe')
		for (i = 0; i < iframes.length; i++) {
			var src = iframes[i].getAttribute('src');
			if (src && (src.indexOf("insertVoice") > -1 || src.indexOf("insertVideo") > -1 || src.indexOf("insertCloud") > -1)) {
				// 处理音频附件、视频附件和云盘附件（云盘文件可能是音频文件）,通知其他音频视频停止播放，cid：当前在播放的音频iframe 的 cid
				iframes[i].contentWindow.postMessage({'cid': 'video'}, '*');
			}
		}
		// 停止回复中的音频附件
		if ($('.Mtion-con').length > 0) {
			$('.Mtion-con').each(function () {
				if ($(this).find('audio')[0] && $(this).find('.attachItem').hasClass('play')) {
					$(this).find('audio')[0].pause();
					if ($(this).attr('type') == 'audio') {
						$(this).find('.attachImg img').attr('src', AttachmentListener.mctx + '/res/pc/images/richtext/voice_play.png');
					}
					$(this).find('.attachItem ').removeClass('play').addClass('pause');
				}
			})
		}
		// console.log('media.fromType dasai', media.fromType);
		// console.log(media.fromType!= undefined , media.fromType == 'dasai');
		if(media.fromType!= undefined && media.fromType == 'dasai'){
			easyDialog.open({
				container: 'videoDiv',
				noFn: true,
				drag: true,
				overlay:false,
			})
		}else{
		easyDialog.open({
			container: 'videoDiv',
			noFn: true,
			drag: true
		});
		}
	} else if (mediaType == "audio") {
		//音频
		if (musicPlayer) {
			var exists = false;
			for (i in musicPlayer.musicList) {
				if (musicPlayer.musicList[i]["resid"] == media.fileId) {
					exists = true;
					break;
				}
			}
			if (!exists) {
				var title = media.name;
				musicPlayer.addMusic({resid: media.fileId, title: title, src: url});
			}
			musicPlayer.play(media.fileId);
			$("#audioDiv").show();
		} else {
			var musicList = new Array();
			var defaultIdx = 0;
			if (media.infoJsonStr) {
				// 云盘里面的音频，单独处理一下处理一下
				musicList.push({resid: media.fileId, title: media.name, src: media.playUrl || ""});
			}

			var iframes;
			var ueditor_iframe = window.frames["ueditor_0"];
			if (ueditor_iframe) {
				// 编辑页
				var doc = ueditor_iframe.contentDocument || ueditor_iframe.document;
				if (doc) {
					iframes = doc.getElementsByTagName('iframe');
				}
			} else {
				// 详情页
				iframes = document.getElementsByTagName('iframe');
			}
			// 遍历iframe，找到所有的音频附件，云盘中的音频暂不考虑
			if (iframes && iframes.length > 0) {
				var audio_index = 0;
				for (i = 0; i < iframes.length; i++) {
					var src = iframes[i].getAttribute('src');
					if (src && src.indexOf("insertVoice") > -1) {
						try {
							json = JSON.parse(AttachmentListener.b64DecodeUnicode(iframes[i].getAttribute('name')));
						} catch (e) {
							console.log(e);
							json = "";
						}
						if (json && json.att_voice) {
							var name = "";
							if (json.att_voice.titleEdited == 1) {
								name = json.att_voice.fileTitle || "";
							} else {
								name = "录音-" + timeformat(json.att_voice.voiceLength || 0);
							}
							musicList.push({resid: json.att_voice.objectId2, title: name, src: "", iframe_cid: json.cid});
							if (media.fileId == json.att_voice.objectId2) {
								// 获取点击的那个音频在列表中的位置，用于后面播放相应位置的音频
								defaultIdx = audio_index;
							}
							audio_index++;
						}
					}
				}
			}
			musicPlayer = new SMusic({
				musicList: musicList,
				autoPlay: true,  //是否自动播放
				defaultIndex: defaultIdx,//默认为选中
				defaultMode: 1,   //默认播放模式，列表模式
				callback: function (thisPlayer, curMusic) {
					var $musicListDiv = $(thisPlayer.musicDom.listWrap);
					var $scrollToContainer = $musicListDiv.find("[musicresid='" + curMusic["resid"] + "']");
					$musicListDiv.animate({
						scrollTop: $scrollToContainer.offset().top - $musicListDiv.offset().top + $musicListDiv.scrollTop()
					}, 1000);//2秒滑动到指定位置
				},
				loadMusic: function (thisPlayer, curMusic) {//歌曲不在时，开始加载
					var loaded = false;
					if ($.trim(curMusic["resid"] || "") != "") {
						var noteDomain = AttachmentListener.noteDomainHttps
						if (RichTextUitl.intranetMode) {
							// 镜像模式，有一些数据可能是从线上迁移过去的，根据当前页面协议判断要使用的笔记服务
							if (window.location.protocol == 'http:') {
								noteDomain = AttachmentListener.noteDomain
							}
						} else {
							noteDomain = RichTextUitl.convertUrl(noteDomain);
						}
						//先从镜像获取 如果失败 并且是镜像域名，从公网获取一遍
						if (window.location.host.indexOf("course.ustc.edu.cn") != -1 || window.location.host.indexOf("istudy.szpu.edu.cn") != -1
							|| window.location.host.indexOf("mooc.ucas.edu.cn") != -1) {
							let result = getCommonFileDownLoadUrl(noteDomain + "/screen/note_note/files/status/" + (media.fileId || ""));
							if ( !result ){
								noteDomain = document.location.protocol + '//' + AttachmentListener.getHost ("https://noteyd.chaoxing.com")
							}
						}
						$.ajax({
							url: noteDomain + "/screen/note_note/files/status/" + (curMusic["resid"] || ""),
							data: {isMedia: mediaType == "video"},
							type: "get",
							async: false,
							xhrFields: {
								withCredentials: true
							},
							success: function (backData) {
								if (backData && backData["status"] && backData["status"] == true && (backData["url"] || "") != "") {
									var curMusicUrl = backData["url"] || "";
									curMusic["src"] = curMusicUrl;
									AttachmentListener.loadedMediaMap.put(media.fileId, curMusicUrl);
									loaded = true;
								} else {
									if (backData && backData["msg"] && (backData["msg"] || "") != "") {
										alert(backData["msg"]);
									} else {
										alert(AttachmentListener.mediaDefaultErrorMsg);
									}
								}
							},
							error: function (xhr) {
								alert(AttachmentListener.mediaDefaultErrorMsg);
							}
						});
						// $.ajax({
						// 	url: noteDomain + "/pc/files/status/" + (curMusic["resid"] || ""),
						// 	data: {isMedia: true},
						// 	type: "get",
						// 	async: false,
						// 	xhrFields: {
						// 		withCredentials: true
						// 	},
						// 	success: function (backData) {
						// 		if (backData && backData["status"] && backData["status"] == true && (backData["url"] || "") != "") {
						// 			var curMusicUrl = backData["url"] || "";
						// 			curMusic["src"] = curMusicUrl;
						// 			AttachmentListener.loadedMediaMap.put(media.fileId, curMusicUrl);
						// 			loaded = true;
						// 		} else {
						// 			if (backData && backData["msg"] && (backData["msg"] || "") != "") {
						// 				alert(backData["msg"]);
						// 			} else {
						// 				alert(AttachmentListener.mediaDefaultErrorMsg);
						// 			}
						// 		}
						// 	},
						// 	error: function (xhr) {
						// 		alert(AttachmentListener.mediaDefaultErrorMsg);
						// 	}
						// });
					}
					return loaded;
				}
			});
			$("#audioDiv").show().hqzDrag(".headBar");
		}
	}
}

/*获取视频截图列表*/
AttachmentListener.getVideoPics = function (objectId) {
	$('#videoCoverEdit .yun-ul').empty();
	$('#videoCoverEdit .upload-Yun, #videoCoverEdit .line').hide();
	var url = AttachmentListener.noteDomainHttps + '/pc/files/getThumbnails?objectId=' + objectId;
	$.ajax({
		url: RichTextUitl.convertUrl(url),
		type: "get",
		xhrFields: {
			withCredentials: true
		},
		success: function (backData) {
			if (backData.result != 1) {
				RichTextUitl.showTips(backData.msg, 0);
				return;
			}
			//如果成功，加载图片列表
			var coverHtml = '';
			var imgUrl = backData.msg.imgUrl
			for (var i = 1; i < backData.msg.data.length; i++) {
				coverHtml += '<li class="cover-item"><img src="' + (imgUrl + backData.msg.fileNameFormat.replace('$index', backData.msg.data[i])) + '"> <div class="cover-mask"></div></li>'
			}

			$('#videoCoverEdit .yun-ul').html(coverHtml);
			$('#videoCoverEdit .upload-Yun, #videoCoverEdit .line').show();
			var i = 0;
			$('#videoCoverEdit .yun-ul img').each(function (index, item) {
				item.onload = function () {
					i++;
					if (i == $('#videoCoverEdit .yun-ul img').length) {
						if ($('#videoCoverEdit .yun-ul')[0].scrollWidth > $('#videoCoverEdit .yun-ul').width()) {
							$('#videoCoverEdit .video-page-left,#videoCoverEdit .video-page-right').show();
						} else {
							$('#videoCoverEdit .video-page-left,#videoCoverEdit .video-page-right').hide();
						}
					}
				}
			})
		}
	})
}
/*修改视频封面点击事件*/
AttachmentListener.VideoCoverEditEventinit = function () {
	//左翻页
	$('body').on('click', '#videoCoverEdit .video-page-left', function () {
		var nowindex = $('#videoCoverEdit .cover-item.active').index();
		$('#videoCoverEdit .cover-item.active').removeClass('active');
		if (nowindex == 0) {
			//翻到第一个
			nowindex = $('#videoCoverEdit .yun-ul li').length - 1;
			$('#videoCoverEdit .yun-ul li').eq(nowindex).addClass('active');
			$('#videoCoverEdit .yun-ul').scrollLeft(($('#videoCoverEdit .yun-ul li').eq(0).width() + 6) * nowindex);
		} else {
			nowindex--;
			$('#videoCoverEdit .yun-ul li').eq(nowindex).addClass('active');
			$('#videoCoverEdit .yun-ul').scrollLeft(($('#videoCoverEdit .yun-ul li').eq(0).width() + 6) * (nowindex - 1));
		}
		var src = $('#videoCoverEdit .cover-item.active img').attr('src');
		AttachmentListener.imgToBase64('url', src, function (data) {
			$('#videoCoverEdit .center-topImg img').attr('src', data);
			AttachmentListener.cropper.replace(data);
		})
	});
	//右翻页
	$('body').on('click', '#videoCoverEdit .video-page-right', function () {
		$('#videoCoverEdit .video-page-left').show();
		var nowindex = $('#videoCoverEdit .cover-item.active').index();
		$('#videoCoverEdit .cover-item.active').removeClass('active');
		if (nowindex == $('#videoCoverEdit .yun-ul li').length - 1) {
			//翻到最后一个
			$('#videoCoverEdit .yun-ul li').eq(0).addClass('active');
			$('#videoCoverEdit .yun-ul').scrollLeft(0);
		} else {
			$('#videoCoverEdit .yun-ul li').eq(nowindex + 1).addClass('active');
			$('#videoCoverEdit .yun-ul').scrollLeft(($('#videoCoverEdit .yun-ul li').eq(0).width() + 6) * nowindex);
		}
		var src = $('#videoCoverEdit .cover-item.active img').attr('src');
		AttachmentListener.imgToBase64('url', src, function (data) {
			$('#videoCoverEdit .center-topImg img').attr('src', data);
			AttachmentListener.cropper.replace(data);
		})
	});
	//点击封面列表的图片
	$('body').on('click', '#videoCoverEdit .cover-item', function () {
		$('#videoCoverEdit .cover-item.active').removeClass('active');
		$(this).addClass('active');
		var src = $('#videoCoverEdit .cover-item.active img').attr('src');
		AttachmentListener.imgToBase64('url', src, function (data) {
			$('#videoCoverEdit .center-topImg img').attr('src', data);
			AttachmentListener.cropper.replace(data);
		})
	})
	//关闭修改封面弹窗
	$('body').on('click', '#videoCoverEdit .close,#videoCoverEdit .editorCover-cancel', function () {
		$('#videoCoverEdit').hide();
		if (AttachmentListener.cropper != null) {
			AttachmentListener.cropper.destroy();
		}
	});
	//关闭修改封面弹窗
	$('body').on('click', '#videoCoverEdit .editor-opration', function (e) {
		e.stopPropagation();
	});
	//确定修改封面
	$('body').on('click', '#videoCoverEdit .editorCover-ok', function () {
		var editor = UE.getEditor($('#videoCoverEdit').attr('editorId'));
		$('#videoCoverEdit').hide();
		var canvas = AttachmentListener.cropper.getCroppedCanvas();
		var iframe = editor.iframe;
		if (iframe) {
			var doc = iframe.contentDocument || iframe.document;
			var cid = $('#videoCoverEdit').attr('iframecid');
			var videoIframe = $(doc).find('iframe[cid="' + cid + '"]')[0];
			// 修改视频附件的封面
			canvas.toBlob(function (blob) {
				AttachmentListener.uploadImg(blob, function (res) {
					var previewUrl;
					if (RichTextUitl.intranetMode) {
						previewUrl = res.imgUrl;
					} else {
						previewUrl = res.previewUrl;
					}
					var iframeData = RichTextUitl.b64DecodeUnicode(videoIframe.name);
					iframeData.att_video.coverUrl = previewUrl;
					videoIframe.name = RichTextUitl.b64EncodeUnicode(JSON.stringify(iframeData));
					// 将上传后的内容传到iframe里面去
					videoIframe.contentWindow.postMessage({
						'msgType': 'dataChanged',
						'cid': cid,
						'name': videoIframe.name,
						'editorId': $('#videoCoverEdit').attr('editorId')
					}, "*");
				});
			})

		}
		if (AttachmentListener.cropper != null) {
			AttachmentListener.cropper.destroy();
		}
	})

	/**
	 * 上传文件
	 */
	$('#videoCoverEdit').on('change', 'input', function () {
		var file = this.files[0];
		var reader = new FileReader();
		reader.readAsDataURL(file);
		reader.onload = function (e) {
			$('#videoCoverEdit .center-topImg img').attr('src', this.result);
			AttachmentListener.cropper.replace(this.result);
		}
	})

}
//图片转base64
AttachmentListener.imgToBase64 = function (type, param, callback) { //type可以传url和objectId
	var url = document.location.protocol + '//' + AttachmentListener.getHost(AttachmentListener.noteDomainHttps) + '/pc/files/getImageBase64?' + type + '=' + param;
	$.ajax({
		url: url,
		type: "get",
		crossDomain: true,
		xhrFields: {
			withCredentials: true
		},
		success: function (res) {
			var data = res.msg;
			if (res.result && data.imageData) {
				callback(data.imageData);
			}
		}
	})
}

//上传blob图片
AttachmentListener.uploadImg = function (blob, callback) {
	var imageName = (new Date()).getTime() + ".png";
	if (!!(window.File && window.FileList && window.FileReader)) {
		file = AttachmentListener.blobToFile(blob, imageName);
		file.name = imageName;
		var url;
		if(RichTextUitl.puid && RichTextUitl.yunToken){
			url = RichTextUitl.uploadUrl;
		}else{
			url = RichTextUitl.getV2UploadUrl();
		}
		var xhr = new XMLHttpRequest(),
			fd = new FormData();
		fd.append('file', file, file.name);
		fd.append('type', 'ajax');
		if( RichTextUitl.puid && RichTextUitl.yunToken){
			fd.append("puid", RichTextUitl.puid);
			fd.append("_token", RichTextUitl.yunToken);
		}
		xhr.open("post", url, true);
		xhr.addEventListener('load', function (e) {
			try {
				var res = JSON.parse(e.target.response);
				if (RichTextUitl.intranetMode && typeof RichTextUitl.customUploadDataAnalysis == 'function') {
					// 镜像版本需要处理下接口返回值
					res = RichTextUitl.customUploadDataAnalysis(res);
				}
				if (res.result) {
					if (callback) {
						callback(res.data);
					}
				}
			} catch (er) {
				RichTextUitl.showTips('上传图片失败', 0)
			}
		});
		xhr.send(fd);
	}
}
//将blob转换为file
AttachmentListener.blobToFile = function (theBlob, fileName) {
	theBlob.lastModifiedDate = new Date();
	theBlob.name = fileName;
	return theBlob;
}

/**
 * 截取域名，去掉协议 http:// 和 https://
 * 例: http://noteyd.chaoxing.com -> noteyd.chaoxing.com
 */
AttachmentListener.getHost = function (url) {
	if (!url) {
		return ''
	}
	if (url.startsWith('http:') || url.startsWith('https:')) {
		return url.substring(url.indexOf('://') + 3);
	}
	return url;
}

function ALMap() {
	this.elements = new Array();

	//向MAP中增加元素（key, value)
	this.put = function (_key, _value) {
		this.removeByKey(_key);
		this.elements.push({
			key: _key,
			value: _value
		});
	};
	//获取指定KEY的元素值VALUE，失败返回NULL
	this.get = function (_key) {
		try {
			for (i = 0; i < this.elements.length; i++) {
				if (this.elements[i].key == _key) {
					return this.elements[i].value;
				}
			}
		} catch (e) {
			return false;
		}
		return false;
	};
	//删除指定KEY的元素，成功返回True，失败返回False
	this.removeByKey = function (_key) {
		var bln = false;
		try {
			for (i = 0; i < this.elements.length; i++) {
				if (this.elements[i].key == _key) {
					this.elements.splice(i, 1);
					return true;
				}
			}
		} catch (e) {
			bln = false;
		}
		return bln;
	};
}

function getTargetIframeEditor(data){
	var targetIframe = null, editor = null, detailIframe = null
	var editordivs = $('.edui-editor.edui-default').parent();
	if (editordivs.length == 0) { //详情页
		targetIframe = $('body').find('iframe[cid=' + data.cid + ']')
	} else { //找到编辑页对应的iframe
		for (var i = 0; i < editordivs.length; i++) {
			var editorid = editordivs.eq(i).attr('id');
			if(!editorid) continue;
			editor = UE.getEditor(editorid);
			if (editor && editor.iframe) {
				targetIframe = $(editor.body).find('iframe[cid="' + data.cid + '"]');
				if (targetIframe.length > 0) {
					break;
				}
			}
		}
	}

	// 表单页面 可能同时存在详情、编辑两种状态的两个编辑器 导致iframe获取不到 故再取一遍
	if(editordivs.length != 0 && targetIframe && targetIframe.length == 0) {
		targetIframe = $('body').find('iframe[cid=' + data.cid + ']')
	}

	// 是否含有详情页iframe
	if($('.richtext').find('iframe[cid=' + data.cid + ']').length > 0)  {
		detailIframe = $('.richtext').find('iframe[cid=' + data.cid + ']')
	}

	return {
		iframe: targetIframe,
		detailIframe: detailIframe,
		editor: editor
	}
}
