$Edit={}

$Edit.random=Math.random()

$Edit.init=function(id)
{
	var dom=$M.find(id);
	if(!dom)
	{
		$M.info('[编辑器初始化]未找到元素：',id)
		return false;
	}
	dom.setAttribute('contenteditable','true');
	if(!dom._edit)
	{
		dom._edit=true;
		dom.listener
		(
			'tap','img,video,audio,table',function(eve,dom)
			{
				var res=prompt('请输入宽度',50)
				if(res)
				{
					dom.style.width=res+'%'
				}
			}
		)
	}
	return dom;
}

$Edit.destroy=function(id)
{
	var dom=$M.find(id);
	if(!dom)
	{
		$M.info('[编辑器销毁]未找到元素：',id)
		return false;
	}
	dom.setAttribute('contenteditable','fsale');
}

$M.pasteHtml=function (html) 
{
    var sel, range;
	if (window.getSelection) 
	{
        // IE9 and non-IE
        sel = window.getSelection();
		if (sel.getRangeAt && sel.rangeCount) 
		{
            range = sel.getRangeAt(0);
            range.deleteContents();
            var el = document.createElement("div");
            el.innerHTML = html;
            var frag = document.createDocumentFragment(), node, lastNode;
			while ( (node = el.firstChild) ) 
			{
                lastNode = frag.appendChild(node);
            }
            range.insertNode(frag);

            // Preserve the selection
			if (lastNode) 
			{
                range = range.cloneRange();
                range.setStartAfter(lastNode);
                range.collapse(true);
                sel.removeAllRanges();
                sel.addRange(range);
            }
        }
	} 
	else if (document.selection && document.selection.type != "Control") 
	{
        // IE < 9
        document.selection.createRange().pasteHTML(html);
	}
	return true
}


$Edit.insertHtml=function(sHtml)
{
	let bool
	if($M.isIE())
	{
	  bool=$Edit.pasteHtml(sHtml);
	}
	else
	{ 
	  bool=document.execCommand('InsertHtml',false,sHtml);
	  if(!bool)bool=$Edit.pasteHtml(sHtml);
	  if(!bool)$M.info('【编辑器】','插入html失败,可能编辑器未获取焦点')
	}
	return bool;
}

//获取选择内容
$Edit.select=function(sHtml)
{
	var id="select_"+Date.now();
	document.execCommand('fontName',null,id)
	var result=$M.find("font[face='"+id+"']").innerText   
	document.execCommand('undo',null)
	return result;
}

//选择全部内容
$Edit.selectAll=function()
{
	document.execCommand("selectAll",false,true);
}

$Edit.copy=function(sHtml)
{
	document.execCommand('Copy',false,sHtml);
}

$Edit.copyHide=function(sHtml,tag)
{
	let dom=$M.find(sHtml)
	let value=dom.innerText;
	if(tag)value=dom.outerHTML;
	let oInput = document.createElement('input');
	oInput.value = value;
	document.body.appendChild(oInput);
	oInput.select(); // 选择对象
	document.execCommand("Copy"); // 执行浏览器复制命令
	oInput.setAttribute('$edit_copy_private','true')
	oInput.style.display='none';
	$M.removeChild(oInput)
	return true
}

$Edit.createLink=function(sHtml)
{
	document.execCommand('createLink',false,sHtml);
}

$Edit.unLink=function(sHtml)
{
	document.execCommand('unlink',false,sHtml);
}

$Edit.foreColor=function(sHtml)
{
	document.execCommand('foreColor',false,sHtml);
}

$Edit.backColor=function(sHtml)
{
	document.execCommand('BackColor',false,sHtml);
}

$Edit.bold=function()
{
	document.execCommand('bold',false);
}

$Edit.fontName=function(sHtml)
{
	document.execCommand('fontName',false,sHtml);
}

$Edit.fontSize=function(sHtml='1')
{
	//1-7
	document.execCommand('fontSize',false,sHtml);
}

$Edit.justifyLeft=function()
{
	document.execCommand('justifyLeft',false);
}

$Edit.justifyCenter=function()
{
	document.execCommand('justifyCenter',false);
}

$Edit.justifyRight=function()
{	
	document.execCommand('justifyRight',false);
}



$Edit.parse=function(str)
{
	str = str.replace(/"/g,'\\"');
	return str;
}

$Edit.code=function(id)
{	
	let dom=$M.find(id);
	let html=$Edit.format(dom)
	dom.innerHTML=$M.HTMLEncode(html).replace(/\n/g,'<br/>')
	return html
}

$Edit.fromCode=function(id)
{	
	let dom=$M.find(id);
	let html=dom.innerText.trim().replace(/\xA0/g,' ');
	dom.innerHTML=html;
	return html;
}



$Edit.getAttr=function (attrs)
{
    let str=''
    let attrsLen=attrs.length
    for (let index = 0; index < attrsLen; index++) 
    {
        str=str+' '+attrs[index].name+'="'+$Edit.parse(attrs[index].nodeValue)+'"'
    }
    return str
}

//1dom,3text,8注释
$Edit.format=function (ele,space='')
{
	ele=$M.find(ele);
    let str='';
    let tag='\r\n';
    let tab='    ';
    let childList=ele.childNodes;
    let childListLen=ele.childNodes.length;
    for (let index = 0; index < childListLen; index++) 
    {
        let dom=childList[index];
        let val
        switch (childList[index].nodeType) 
        {
            case 8:   
                val=dom.nodeValue.trim()
                if(val)str=str+space+'<!--'+val+'-->'+tag
            break;
            case 3:
				val=dom.nodeValue.trim()
                if(val)str=str+space+val.replace(/[  |\xA0]/g,'&nbsp;')+tag
            break;
            case 1:
				let name=dom.localName
				if(name.toLowerCase()=='br')
				{
					str=str+space+`<${name} ${$Edit.getAttr(dom.attributes)} />`+tag
					continue
				}
                str=str+space+`<${name} ${$Edit.getAttr(dom.attributes)}>`+tag
                str=str+$Edit.format(dom,space+tab)
                str=str+space+`</${name}>`+tag
                
            break;        

        }
    }
    return str;
}






$Edit.upload=async function(url,val,dom,fun)
{
	if(dom.type=='file')
	{
		if(!val || !val.length)
		{
			alert('文件不符合要求')
			return
		}
		let back=await $Ajax.upload(url,val,dom,fun)
		for (const key in back) 
		{
			if(back[key].code!==0)
			{
				alert('上传错误')
				return
			}
			if(val[key].type.indexOf('image')!=-1)
			{
				$Edit.insertHtml(`<img src="${back[key].data[0].file}">`)
			}
			else if(val[key].type.indexOf('video')!=-1)
			{   
				$Edit.insertHtml(`<br/><br/><video style="max-width:100%;" controls="controls" src="${back[key].data[0].file}"></video><br/><br/>`)
			}
			else if(val[key].type.indexOf('audio')!=-1)
			{
				$Edit.insertHtml(`<br/><br/><audio  controls="controls" src="${back[key].data[0].file}"></audio><br/><br/>`)
			}
		}   
	}
}


$Edit.save=function(name,data,mine='application/binary')
{
	let bold
	if(!data)
	{
		$M.info('请传入需要保存的值：',name)
		return
	}
	if(typeof data =='string')
	{
		mine='application/text'
		blob=new Blob([data],{type : mine})
	}
	else
	{
		try 
		{
			data=JSON.stringify(data)
			mine='application/json'
			blob=new Blob([json],{type : mine})
		} 
		catch (error) 
		{
			blob=data
		}
		
	}
	
	let url=window.URL.createObjectURL(blob)
	var a = document.createElement("a")
	a.href = url
	a.download = name;
	let event = new MouseEvent('click');
	a.dispatchEvent(event);
}

$Edit.file=function()
{
	var input = document.createElement("input")
	input.type = 'file'
	let event = new MouseEvent('click');
	input.dispatchEvent(event);
	return new Promise
	(
		(res,rej)=>
		{
			input.onchange=function()
			{
				res(input.files)
			}
			input.onerror=function(error)
			{
				rej(error)
			}
		}
	)
}

$Edit.load=function(dom,type='readAsText')
{
	if(!dom)
	{

		$M.info('请传入需要加载的值：',name)
		return
	}
	let loder

	loder=dom

	let file=new FileReader()
	let cur=new Promise
	(
		(res,rej)=>
		{
			file.onload=event=>
			{
				res(event.target.result)
			}
			file.onerror=err=>
			{
				rej(err)
			}
		}
	)
	file[type](loder)   
	return cur
}


$Edit.full=function(dom)
{
	var docElm = dom?dom:document.documentElement;  
	//W3C   
	if (docElm.requestFullscreen)docElm.requestFullscreen();  
	//FireFox   
	else if (docElm.mozRequestFullScreen)docElm.mozRequestFullScreen();  
	//Chrome等   
	else if (docElm.webkitRequestFullScreen)docElm.webkitRequestFullScreen();
		//IE11   
	else if (docElm.msRequestFullscreen)docElm.msRequestFullscreen(); 
}
$Edit.fullClose=function(dom)
{
	if (document.exitFullscreen)document.exitFullscreen();  
	else if (document.mozCancelFullScreen)document.mozCancelFullScreen();
	else if (document.webkitCancelFullScreen)document.webkitCancelFullScreen(); 
	else if (document.msExitFullscreen)document.msExitFullscreen();  
}