$Ws={}
$Ws.stat=false;//websocket是否可用
$Ws.int=1000*60;//心跳间隔
$Ws.inter=0;//关闭心跳时，断开连接多久关闭
$Ws.heart=0;//标记是否已发心跳
$Ws.fun=[];//初始化，处理的函数列表
$Ws.param={};//通用参数
$Ws.make=[];//收到消息后，处理的函数列表
$Ws.url;//websocket地址
$Ws.end=''

$Ws.heartTag='\\a'//心跳包


if($Ws.int)setInterval
(
	function()
	{
		if(!$Ws.url)return
		var dat=new Date();
		dat=dat.getTime();
		if(dat<($Ws.heart+$Ws.int))
		{
			return;
		}
		if($Ws.stat)
		{
			$M.info('[ws]','发送心跳包')	
			$Ws.stat.send($Ws.heartTag)
		}
		else
		{
			$M.info('[ws]','连接断开,重新连接')
			$Ws.connect($Ws.url,$Ws.urls)
		} 
	},$Ws.int
)

$Ws.connect=function(url,urls)
{
	var ws
	try 
	{
		let tag=location.protocol
		$Ws.url=$Ws.url?$Ws.url:url;
		$Ws.urls=$Ws.urls?$Ws.urls:urls;

		let cul
		if(tag.indexOf('https')===-1)
		{
			tag='ws://'
			cul=url
		}
		else 
		{
			tag='wss://'
			cul=urls
		}

		if(!cul)return
		if(cul.indexOf(tag)!==0)
		{
			cul=tag+location.hostname.split(':')[0]+":"+cul
		}
		ws=new WebSocket(cul); 				
	} 
	catch (error) 
	{
		$M.info('[ws]连接失败',error);	
		return
	}

	ws.onmessage = function(event) 
	{ 
		if(!event.data)
		{
			$M.info('[ws]','收到心跳包');	
		}
		else
		{
			var data=event.data;
			try 
			{
				data=JSON.parse(event.data);
			} 
			catch (error)
			{
				data=event.data;
			}
			for (var key in $Ws.make) 
			{
				if(!$Ws.make[key])continue;
				$Ws.make[key](data);
			}
		}
	};  
	
	ws.onclose = function(event) 
	{
		$Ws.stat=false;
		$M.info('[ws]',event)
		if(!$Ws.int && $Ws.inter)setTimeout
		(
			()=>
			{
				$Ws.connect($Ws.url,$Ws.urls)
			},$Ws.inter
		)
	};
	ws.onopen = function() 
	{ 
		$Ws.stat=ws; 
		for (var key in $Ws.fun) 
		{
			if(!$Ws.fun[key])continue;
			$Ws.fun[key](ws);
		}
	}; 
	ws.onerror =function(event)
	{
		// $Ws.stat=false;
		$M.info('[ws]',event)
	};

	return ws;
}

$Ws.send=function(body)
{
	if(body instanceof Object)
	{
		try 
		{
			body=JSON.stringify(body);
		} 
		catch (error) 
		{
			$M.info('[ws]解析发送对象错误',body,error);
			return false;
		}
	}
	if($Ws.stat)
	{
		var dat=new Date();
		dat=dat.getTime();
		$Ws.heart=dat;
		$Ws.stat.send(body+$Ws.end)
	}
	else
	{
		return false;
	}
}

$Ws.hot=function(type,tag)
{
	type=type?type:Math.random();
	$Ws.make.push
	(
		function(data) 
		{   
			if(!tag && data && data.path=="/$update")
			{  
				location.href=location.href;
				location.reload();
			}
		}
	)

	$Ws.fun.push
	(
		function(event)
		{
			var msg='{"path":"/request/web/start","data":"'+type+'"}';
			$Ws.send(msg);  
		}
	)
}