 var ws, RandomTimeData, callNum, extenNum, readyStateBoole, reconnecTion, recon,
 	lockReconnect = false, timesVideoReq = 0,
 	n = 0,
 	loginOr = false,
 	meetingState = null,
 	obj = {},
 	lasttime = new Date().getTime().toString();
 	var xAudio = document.getElementById("music_bg"); 

 var formatDateTime = function(date) {
 	var date = new Date();
 	var y = date.getFullYear().toString();
 	var m = date.getMonth() + 1;
 	m = m < 10 ? ('0' + m) : m;
 	var d = date.getDate();
 	d = d < 10 ? ('0' + d) : d;
 	console.log(y + m + d)
 	return y + m + d
 	// +' '+h+':'+minute+':'+second;
 };

 //创建scoket连接
 createWebSocket()

 function createWebSocket() {

 	try {
 		Connect();
 	} catch(e) {
 		reconnect();
 	}
 }

 //连接
 //Connect();
 function Connect() {
 	ws = new WebSocket(huayi.config.socket_url);
	
 	ws.onopen = function() {
 		lockReconnect = false
 		console.log(new Date() + "    " + "建立连接");
 		console.log(huayi.config.socket_url)

 		// extenNum = "1020"
 		// sip_uri_ = "sip:"+extenNum+"@"+huayi.config.socket_ip;
 		// sip_password_ = "123456"
 		// ws_uri_ = huayi.config.ws_uri_;    //wss://sip.800100.com.cn:7443  218.29.229.185:8011
 		// testStart();

 		//建立连接时获取分机号
 		// lasttime = new Date().getTime().toString();
 		//申请注册分机号
 		if($(".superviseBtn").text() == "我是督办专员") {
 			videoReqExten()
 		}

 	};
 	//接收到消息的回调方法
 	ws.onmessage = function(evt) {
 		//拿到任何消息都说明当前连接是正常的
 		var myDate = new Date();
 		console.log(myDate + "  receive  " + evt.data);
 		var data = JSON.parse(evt.data)[0];
 		if(data) {
 			var rlt = data.Result;
 			if(rlt == true) {
 				var type = data.Type;
 				switch(type.toLowerCase()) {
 					//请求注册分机返回结果
 					case "videoreqexten":
 						videoreqextenBack(data);
 						break;
 						//申请空闲坐席返回结果					
 					case "videoreqideagent":
 						videoreqideagentBack(data);
 						break;
					case "videoreqbindagent":
						videoreqbindagentBack(data);
						break;
 					case "meeting":
 						meetingBack();
 						break;
 						//注销分机返回结果
 					case "videodesexten":
 						videodesextenBack(data);
 						break;
 				}
 			} else {
 				if(data.Type === "VideoReqIdeAgent") {
					
					if (timesVideoReq < 8) {
						$(".registStatus").text("坐席忙，请稍等")
						$(".registStatus").css("color", "#FF8C00")
						xAudio.play()
					}else{
						$(".registStatus").text("当前无人在线，请稍后再拨")
						$(".registStatus").css("color", "red")
						timesVideoReq = 0
						xAudio.pause()
						return
					}
					console.log("data.Result返回为false")
					setTimeout(function(){
						timesVideoReq+=1
						videoReqIdeAgent()
					},5000)
 					
 					
 				}
				if(data.Type === "VideoReqBindAgent"){
					$(".registStatus").text("绑定失败")
				}

 			}
 		}
 	};
 	//连接关闭的回调方法
 	ws.onclose = function(evt) {
 		//nginx   proxy_read_timeout 6000s; 设置的默认关闭时间 
 		reconnect();
 	};
 	//连接发生错误的回调方法
 	ws.onerror = function(evt) {

 		reconnect();
 	};
 }

 //重连
 function reconnect() {

 	if(lockReconnect) return;
 	lockReconnect = true;
 	//没连接上会一直重连，设置延迟避免请求过多
 	setTimeout(function() {
 		console.log(new Date() + "    " + "重连中……");
 		createWebSocket("wss://" + huayi.config.socket_ip + ":" + huayi.config.socket_port);
 	}, 2000);
 }

 //发送
 function Send() {
// 	console.log("ws.readyState==" + ws.readyState)
// 	console.log("ws.OPEN==" + ws.OPEN)
 	readyStateBoole = false

 	if(ws.readyState != ws.OPEN) {
 		readyStateBoole = true
 		alert("页面停留时间过长，导致分机号被占用，请刷新页面后，重新使用")
 		//reconnect();
 	}
 	if(ws.readyState == ws.OPEN) {
 		console.log(new Date() + "  send  " + JSON.stringify(obj));
 		ws.send(JSON.stringify(obj));
 	}
 }

 //申请注册的分机
 function videoReqExten() {
 	
 	obj.Type = "VideoReqExten";
 	obj.AgentID = lasttime.substring(lasttime.length-9);
	obj.AgentExten = "111";
 	RandomTimeData = obj.AgentID;
 	Send();
 }
 //请求注册分机，返回结果
 function videoreqextenBack(data) {
 	
 	
 	console.log(data.AgentExten+"已注册")
 	//当内容是我是督办专员时，是在市民页面
 	if($(".superviseBtn").text() == "我是督办专员") {
 		extenNum = data.AgentExten
 		$("#account").val(extenNum)
 		sip_uri_ = "sip:" + extenNum + "@" + huayi.config.socket_ip;
 		sip_password_ = "123456";
 		ws_uri_ = huayi.config.ws_uri_; //wss://sip.800100.com.cn:7443  218.29.229.185:8011
 		contact_uri =  huayi.config.contact_uri
 		testStart();
 		// setInterval(testStart,600*1000)
 	}

 }

 //申请空闲坐席
 function videoReqIdeAgent() {

 	obj.Type = "VideoReqIdeAgent";
 	obj.AgentID = lasttime.substring(lasttime.length-9); 
 	obj.AgentExten = $("#account").val().toString();
 	console.log(obj)
 	Send();
 }
 //申请空闲坐席，返回结果
 function videoreqideagentBack(data) {
	xAudio.pause()
 	callNum = data.AgentExten;
 	videoCall();
 }
//绑定坐席
 function VideoReqBindAgent() {

 	obj.Type = "VideoReqBindAgent";
 	obj.AgentID = lasttime.substring(lasttime.length-9); 
 	obj.AgentExten = $("#account").val().toString();
 	console.log(obj)
 	Send();
 }
 //绑定坐席 返回结果
 function videoreqbindagentBack(){
	 $(".registStatus").text("登录成功")
	 $(".loginbtn").hide();
	 $(".videoCall").show();
 }
 //注销分机
 function videoDesExten() {
 	obj = {};
 	obj.Type = "VideoDesExten";
 	obj.AgentID = RandomTimeData;
 	obj.AgentExten = extenNum.toString()
 	Send();
 }
 //注销分机，返回结果
 function videodesextenBack(data) {
 	console.log(extenNum+"已注销")
 	$(".registStatus").html("已注销")
 }

 //手机号与分机号关联
 function extenBind() {

 	var signcode = "api/addrelation+" + formatDateTime()
 	var telPhone = /^[1][3,4,5,6,7,8,9][0-9]{9}$/;
 	if(!telPhone.test($("#telephone").val())) {
 		$(".registStatus").text("手机号格式不正确");
 		$(".registStatus").css("color", "red")
 	} else {
// 		$.ajax({
// 			type: "get",
// 			url: "http://222.143.106.45:65525/Api/AddRelation",
// 			dataType: "json",
// 			async: true,
// 			data: {
// 				ext: $("#account").val(),
// 				telephone: $("#telephone").val(),
// 				signcode: $.md5(signcode).toUpperCase()
// 			},
// 			success: function(data) {
// 				if(data.state == "success") {
// 					videoReqIdeAgent()
// 				} else {
// 					$(".registStatus").text("关联失败");
// 					$(".registStatus").css("color", "red")
// 				}
//
// 			}
// 		})
 		videoReqIdeAgent()
 	}

 }

 function meetingBack() {

 	meetingState = true;
 	$(".leftText").html("");
 	$(".videoMy").hide();
	$(".videoYour").unbind();
	
 	videoSize()

 }