var phoneServerConnection , isConnected , connectCount=0 ,isLoginOn ,loginCount=0 ,uuid ,startcall=0, stopcall=1, callFlag=false;
function phoneServer(){}

phoneServer.childframe = null; 

phoneServer.setReqPage=function(childframe){
	console.log("phoneServer.setReqPage:" + childframe.location.href);
	phoneServer.childframe = childframe;
}
//与websocket服务端建立连接
phoneServer.connectServer = function(){
		try{
			 phoneServerConnection = new WebSocket('ws://127.0.0.1:17070/knockknock');
			 phoneServerConnection.onmessage = phoneServer.handleResponse;
			 phoneServerConnection.onopen = function(evt) {
				console.log("phoneServer:Connection ready.");
				//top.phoneConnectServer = phoneServerConnection;
				//console.log('*********对象已添加********',top.phoneConnectServer);
			    isConnected=true;
			 };
			 phoneServerConnection.onclose = function(evt) {
				isConnected=false;
				phoneServerConnection = null ;
				top.connectServer = null;
				console.log("phoneServer:Connection closed.");
			 }; 
		}catch(e){
			console.error(e);
			$.showMsg("获取一键通话地址失败，请先配置！");
			return;	
		}
		$.ajax({
			 type:'post',
			 dataType : 'json',
			 url:'menuConfigAction!getDacLoginInfo.do',
			 success:function(m){
				 console.log("查询DacLogin返回数据==",m);
				 var loginparam = JSON.stringify({'login': {'ip':m.serverIP, 'port':1*(m.serverPort), 'user':m.yhzh, 'password':m.yhmm}, 'uuid': null,'ua': navigator.userAgent});
				 phoneServer.getServerData(loginparam);
			 }
		});
}
//建立连接后，登录websocket
phoneServer.login = function(loginparam){
    phoneServerConnection.send(loginparam);
}
//服务端登录判断，循环登录10次，成功退出，失败10次后提示登录失败
phoneServer.getServerData = function(loginparam){
	//与服务端建立连接
	var checkConnect = function(){
		if(connectCount>=10){
			$.showMsg("一键通话尝试连接服务器失败！");
			//$("#rtc-container").html("<p class=\"alert-title\">尝试连接服务器失败！</p>");
			return ;
		}
		connectCount++;
		if(isConnected){
			phoneServer.login(loginparam);
			checkOpen();
			return;
		}
		console.log("phoneServer: try Connecting WS server...." + connectCount );
		
		setTimeout(checkConnect,3000);
		
	}
	//建立连接后，登录平台
	var checkOpen = function(){
		if(loginCount>10){
			$.showMsg("一键通话尝试登录平台失败！");
			//$("#rtc-container").html("<p class=\"alert-title\">尝试登录平台失败！</p>");
			return ;
		}
		
		if(isLoginOn){
			return;
		}
		
		console.log("phoneServer: try login pt ...." +  (++loginCount));
		
		setTimeout(checkOpen,3000);
	}
	
	checkConnect();
}
//与服务端建立心跳
phoneServer.serverHeartbeat = function() {
	setInterval(function(){
		console.log('======【一键通话心跳】======',phoneServerConnection);
		phoneServerConnection && phoneServerConnection.send(JSON.stringify({'heartbeat':'hello', 'uuid': $.uniqueId()}));
		//phoneServerConnection && (console.log("phoneServer   serverHeartbeat.........................."));
	},5000);
    
}
//websocket返回信息
phoneServer.handleResponse = function(message) {
    var signal = JSON.parse(message.data);
    console.log('==phoneServer.handleResponse==',signal);
    var uuid = signal.uuid;
    if(signal.login){
        isLoginOn =  signal.login === 'ok' ;
        console.log("==signal.login:"+signal.login);
        console.log("==isLoginOn:"+isLoginOn);
        phoneServer.serverHeartbeat();
    }
    if(signal.makecall){
    	console.log('++++++++makecall++++++++++++++++++');
    }
}
//一键通话
phoneServer.startPhoneCall = function(phoneNumber){
	try{
	if(!phoneNumber){
		$.showMsg("呼叫号码为空，请重新选择！");
		return false;
	}
	var uuid = $.uniqueId();
	var reg = new RegExp("-","g");//g,表示全部替换。
	uuid = uuid.replace(reg,'');
	console.log('==$.uniqueId()===',uuid);
    phoneServerConnection.send(JSON.stringify({ 'makecall': { 'action': startcall, 'phonenumber': phoneNumber},  'uuid': uuid }));
	return uuid;
	}catch(e){
		console.error(e);
		$.showMsg("一键通话拨号失败，请重新呼叫！");
		return false;	
	}
}
//结束通话
phoneServer.stopPhoneCall = function(phoneNumber){
	try{
		if(!phoneNumber){
			$.showMsg("呼叫号码为空，请重新选择！");
			return false;
		}
		phoneServerConnection.send(JSON.stringify({ 'makecall': { 'action': stopcall, 'phonenumber': phoneNumber } }));
		return true;
	}catch(e){
		console.error(e);
		$.showMsg("结束通话失败，请重新操作！");
		return false;
	}
}

//结束通话
closePhoneCall = function(){
	phoneServerConnection.close();
}