//电话操作
var becallout = false; //呼出
var becallcome = true; //来电
var CallOutRecordIsWrite = false; //呼出记录是否已写入

$(document).ready(function() {

	var Phone = document.getElementById("Phone");
	console.log(Phone);
	if(/mobile/i.test(navigator.userAgent) || /android/i.test(navigator.userAgent)) {
		$(".title-box").hide();
	}

	if($.cookie("token") == null) {
		window.location.href = "login.html";
	}
	$('#extenNum').val($.cookie("extno")); //分机号
	if($('#extenNum').val() == undefined) {
		$(".Gnumbox").hide();
	}
	$(".Gnum").text($.cookie("extno"));
	$.ajax({
		type: "get",
		url: huayi.config.callcenter_url + 'UserAccount/GetNowUser',
		async: true,
		dataType: 'json',
		data: {
			"token": $.cookie("token")
		},
		success: function(result) {
			if(result.state.toLowerCase() == "success") {
				$(".username").text(result.data.user.F_UserName);
				$('.user_code').text(result.data.user.F_UserCode);
				$('#userCode').val(result.data.user.F_UserCode);
				$('#userName').val(result.data.user.F_UserName);
				$('#userId').val(result.data.user.F_UserId);
				$('.gd_whNum').text(result.data.user.F_WXNo);
				localStorage.setItem('F_UserCode', result.data.user.F_UserCode)
				$('.group').text(result.data.user.F_SeartGroup);
				if(result.data.role) {
					$(".rolename").text(result.data.role.F_RoleName);
				}
				$(".yhtx").attr("src", huayi.config.callcenter_url.substr(0, huayi.config.callcenter_url.length - 1) + result.data.user.F_See);
				if(result.data.user.F_SeatFlag) {
					$("#top-search").css('display', 'block');
					$(".phoneBZ").show();
					$(".zts").show();
				}
			}
		}
	});
	//分机号
	//话务相关
	$("#top-search li").click(function() {
		if($(this).find("i").hasClass("active")) {
			if($('#extenNum').val()) {
				var fun = $(this).attr("datafun");
				switch(fun) {
					case "DropCall":
						ReleaseAnswer();
						break; //挂断
					case "SayBusy":
						AgentBusy();
						break; //置忙
					case "SayFree":
						AgentFree();
						break; //置闲
					case "MakeCall":
						//otype 1外呼 2转移 3多方通话
						AgentBusy();
						becallout = true;
						becallcome = false;
						$(".hidCallID").val("");
						$("#hidwhtype").val(fun);
						$("#hfOtype").val(1);
						whtp();
						break; //外呼
					case "Meeting":
						$("#hidwhtype").val(fun);
						$("#hfOtype").val(3);
						whtp();
						break; //多方通话
					case "Transfer":
						$("#hidwhtype").val(fun);
						$("#hfOtype").val(2);
						whtp();
						break; //转移
					case "Hold":
						KeepCall();
						break; //保持
					case "Retrieve":
						GetKeepCall();
						break; //接回
					case "Login":
						LoginAgent();
						break; //签入
					case "Logout":
						logoutAgent();
						break; //签出
					default:
						Send();
						break;

				}
			}
		}
	});
	//关闭外呼弹屏
	$(".closes").click(function() {
		$(".WH").removeClass("fadeInDown").addClass("fadeOutUp");
		$(".WH").addClass("hidens");
		AgentFree();

	})
	//键盘事件外呼
	document.onkeydown = function(e) {
		var theEvent = window.event || e;
		var code = theEvent.keyCode || theEvent.which;
		if(code == 13) {
			$(".CallOut").click();
		}
	}
	//外呼呼出
	$('.CallOut').click(function(event) {
		event.stopPropagation();
		if($("#Result").val()) {
			switch($("#hfOtype").val()) {
				case "1":
					PhoneCallOut(1, $("#Result").val()); //外呼
					break;
				case "2":
					PhoneCallZY($("#Result").val()); //转移
					break;
				case "3":
					PhoneCallDFTH($("#Result").val()); //三方通话
					break;
			}
			$('#callOutNumber').val($("#Result").val());
			$('#Result').val('');
			$(".WH").addClass("hidens");

		}
	})

	//外呼弹屏数字键盘样式
	$(".Num_ul div").mousedown(function() {
		$(this).addClass("actives");
		$(".img").removeClass("hidens");
	}).mouseup(function() {
		$(this).removeClass("actives");
	})
	//外呼弹屏数字键盘号码输入
	$(".Num_ul li div").click(function() {
		var rt = $("#Result").val() + "";
		if(rt.length < 18) {
			rt = rt + $(this).find("a").text();
			$("#Result").val(rt);
		}
	});
	//外呼弹屏数字键盘号码截取
	$(".img").click(function() {
		var Result = $("#Result").val() + "";
		Result = Result.substr(0, Result.length - 1);
		$("#Result").val(Result);
		if(Result.length == 0) {
			$(".img").addClass("hidens");
		}
	})

	//外呼电话列表
	$(".bg_title li").click(function() {
		$(this).addClass("lactive").siblings().removeClass("lactive");
		loadWH();
	})
	$(".ty").click(function() {
		loadWH();
	})
	//加载部门人员
	$("#zrbmname").click(function() {
		if($(".zrbmmenu").is(":hidden")) {
			$(".zrbmmenu").show();
		} else {
			$(".zrbmmenu").hide();
		}
	})
	$("#clbmname").click(function() {
		if($(".clbmmenu").is(":hidden")) {
			$(".clbmmenu").show();
		} else {
			$(".clbmmenu").hide();
		}
	})
	$(".col-sm-3").mouseleave(function() {
		$(".ztree").parent().hide();
	})

	//加载左侧导航菜单
	loadMenu();

	//	workcount();
//	setInterval(function() {
//		//		workcount();
//	}, huayi.config.menuworktime);
	//关闭录音弹出
	$(".setwin").click(function() {
		$(".t-shade").removeClass("cx");
		$('audio')[0].pause();
	});

	//修改密码开始
	$('.shezhi').click(function() {
		Dialog('dialogDrag', 'dialogMove');
		showDialog();
		//侦听浏览器窗口大小变化
		//window.onresize = showDialog;
		$.ajax({
			type: "get",
			url: huayi.config.callcenter_url + "UserAccount/GetNowUser",
			async: true,
			dataType: 'json',
			data: {
				token: $.cookie("token")
			},
			success: function(result) {

				if(result.state.toLowerCase() == "success") {
					var con = result.data.user;
					console.log(con)
					$('.mgh').val(con.F_UserId);
					$('.mn').val(con.F_UserName);
					$('.mobile').val(con.F_Mobile);
					$('.fenji').val($.cookie("extno"));
					//$('.wxno').val(con.F_WXNo);
					//		          		$('.spwd').val(con.F_Password);
				}
			}
		});
	})
	//tab切换
	$('.perTab li').click(function() {
		$(this).addClass('sel').siblings().removeClass('sel');
		var index = $(this).index();
		$('.perTab_con').children('div').eq(index).show().siblings().hide();
	})
	//编辑个人资料
	$('.grzl tbody>tr>td input.zhidu').attr('readonly', true);
	$('.grbj').click(function() {
		$('.grzl tbody>tr>td input.zhidu').attr('readonly', false);
		$('.grzl tbody>tr>td input.zhidu').css('border-bottom', "1px solid #b3b3b3");
		$('.grbtn').attr('disabled', false);
	})
	//取消编辑
	$('.grqx').click(function() {
		$('.grzl tbody>tr>td input.zhidu').attr('readonly', true);
		$('.grzl tbody>tr>td input.zhidu').css('border-bottom', "none");
		$('.grbtn').attr('disabled', true);
	})
	//关闭按钮
	$('.ptr').click(function() {
		hideDialog();
	})
	$('.grbtn').click(function() {
		var gh = $('.mgh').val();
		var xm = $('.mn').val();
		var ymm = $('.spwd').val();
		var xmm = $('.npwd').val();
		var qmm = $('.epwd').val();
		if(xmm !== qmm) {
			$('.wrong').show();
			$('.npwd').val('')
			$('.epwd').val('')
		} else if(xmm == '') {
			layer.msg("密码不允许为空！");
		} else {
			$('.wrong').hide();
			$('.grzl tbody>tr>td input').attr('readonly', true);
			$('.grzl tbody>tr>td input').css('border-bottom', "none");
			$.ajax({
				type: "post",
				url: huayi.config.callcenter_url + "UserAccount/UpdatePwd",
				async: true,
				dataType: 'json',
				data: {
					token: $.cookie("token"),
					usercode: gh,
					pwd: xmm,
					oldpwd: ymm,
					mobile: $('.mobile').val()
				},
				success: function(result) {
					//                		result = $.parseJSON(result);
					if(result.state.toLowerCase() == "success") {
						layer.msg("修改成功！");
					}
				}
			});
		}
	})

	//图片裁剪
	var o = $(".image-crop > img");
	$(o).cropper({
		aspectRatio: 1 / 1,
		resizable: false,
		dragCrop: false,
		preview: ".img-preview",
		done: function() {}
	});
	var r = $("#inputImage");
	if(window.FileReader) {
		r.change(function() {
			var e, i = new FileReader,
				t = this.files;
			if(t.length && (e = t[0], /^image\/\w+$/.test(e.type))) {
				i.readAsDataURL(e);
				i.onload = function() {
					r.val("");
					o.cropper("reset", !0).cropper("replace", this.result);
				}

			} else {
				alert("请选择图片文件");
			}
		});
		$("#setDrag").click(function() {
			o.cropper("setDragMode", "crop");
			var img = o.cropper("getDataURL");
			$.post(huayi.config.callcenter_url + "Index/UploadTX64", {
				dataurl: encodeURIComponent(img),
				"token": $.cookie("token")
			}, function(result) {
				result = $.parseJSON(result);
				if(result.state.toLowerCase() == "success") {
					$(".yhtx").attr("src", huayi.config.callcenter_url.substr(0, huayi.config.callcenter_url.length - 1) + result.data);
					layer.msg("上传成功");
					hideDialog();
				}
			})
		});
		$("#zoomIn").click(function() {
			o.cropper("zoom", .1)
		});
		$("#zoomOut").click(function() {
			o.cropper("zoom", -.1)
		});
		$("#rotateLeft").click(function() {
			o.cropper("rotate", 45)
		});
		$("#rotateRight").click(function() {
			o.cropper("rotate", -45)
		});
	} else {
		r.addClass("hide");
	}

	$('.pre-add').click(function() {
		var par = $(this).parent().parent();
		par.hide().siblings().show();
	})

})
//签出
function logoutAgent() {
	try {
		var rtn = Phone.SignOutEx();
		if(rtn == 0) {
			Phone.EndTask();
			Form_setWinfromenble("false", "false", "false", "false", "false", "false", "false", "false", "True", "false");
			setLinkStatus("false");
			setAgentStatus("离席");
		}
	} catch(e) {
		$('.hwzt').html(e.message);
	}
}
setInterval(function() {
		RequestWaitCallNum();
	}, 30000);
//获取排队等到数量
function RequestWaitCallNum(){
	//查询系统中配置的技能队列、座席、IVR 这些设备的状态信息.1代表技能队列
	Phone.QueryDeviceStatusEx(1,2); //2 代表 技能队列ID
	$('.waitCallerNum').text(Phone.DeviceStatus_CallNum);
//	console.log('排队数量：'+ Phone.DeviceStatus_CallNum);
}

//签入
function LoginAgent() {
	Init();
}
//初始化页面
function Init() {
	//show();
	var typed = $("#HdIswin").val(); //是否是坐席用户
	console.log($("#HdIswin").val());
	//				if($("#HdIswin").val()) {
	var timeno = new Date().getTime();
	//					$.ligerDialog.waitting('电话服务连接中...');
	//					$.ajax({
	//						type: 'get',
	//						url: '../telmanage/ajax/telrecords.ashx?action=insertCallLogs&serverip=' + $("#txtMostlyAddress").val() + '&ctiusercode=' + $("#userCode").value + '&timeno=' + timeno,
	//						dataType: 'html',
	//						success: function(res) {
	Initialize();
	//						}
	//					});
	//				} else {
	//					$('.hwzt').html("非坐席登录");
	//				}
}

function Initialize() {
	try {
		//alert("ip" + document.getElementById("txtMostlyAddress").value + "服务器类型" + document.getElementById("ServerType").value + "工号" + document.getElementById("txtLabourNo").value + "密码" + document.getElementById("pwd").value + "通讯进程号" + document.getElementById("txtPhoneID").value + "备用ip" + document.getElementById("txtSubordinationAddress").value);
		//var result = OCX_AgentLogin(document.getElementById("txtMostlyAddress").value, document.getElementById("txtServerPort").value, document.getElementById("txtLabourNo").value, document.getElementById("txtAgentGroup").value, document.getElementById("txtPhoneNum").value);
		Phone = document.getElementById("Phone");
		Phone.MainCcsIp = $("#txtMostlyAddress").val(); // （主用CTI服务器IP）
		Phone.CcsID = "22"; //服务器类型
		Phone.WorkNo = $('#userCode').val(); //工号
		Phone.Password = "123456"; //$("#passWord").val(); //密码(与cti关联密码)
		Phone.MyID = "43"; //通讯进程号
		Phone.BackCcsIP = $("#txtMostlyAddress").val(); //备用CTI服务器IP
		//alert("ip" + document.getElementById("txtMostlyAddress").value + "服务器类型" + document.getElementById("ServerType").value + "工号" + document.getElementById("txtLabourNo").value + "分机" + document.getElementById("txtPhoneNum").value);
		var result = Phone.Initial();
		console.log(Phone.GetPromptByErrorCode(result))
		if(result == '0') {
			$('.hwzt').html('坐席开始签入');
			AutographJoin(); //签入
		} else {
			$('.hwzt').html('初始化失败');
			GetErrorDesc(result);
		}
	} catch(e) {
		$('.hwzt').html(e.message)
	}
}
//弹出错误描述
function GetErrorDesc(errorCode) {
	//					$('.hwzt').html(Phone.GetPromptByErrorCode(errorCode))
	alert(Phone.GetPromptByErrorCode(errorCode));
}
//签入 2.1.1
function AutographJoin() {
	//签入CTI服务器,WEBM服务器以及MAIL服务器
	//备注 第一个参数指 要签入的服务器类型T代表签入F代表不签入
	//var result = Phone.SignInEx('TFF', SeatType.value, txtPhoneNum.value);
	var phoneNumberOne = $("#extenNum").val(); //分机号
	var result = Phone.SignInEx('TFF', "4", phoneNumberOne);
	if(result == '0') {
		$('.hwzt').html("坐席签入成功");
		setLinkStatus("True");
		//AjaxPost("../WinIVR/GetAjaxPageInf.aspx?PgType=12&extnumber=" + document.getElementById("txtPhoneNum").value);
		//签入成功日志 并且处理当前坐席当前的分机号
		//setAutoWork(); //登录自动签入
	} else {
		setLinkStatus("false");
	}

	setAutoRelease();

}
//服务状态
function setLinkStatus(str) {
	str = str.toLowerCase();
	if(str == "true") {
		//						$(".zxzt").removeClass("br").addClass("bl");
		$(".fwzt").removeClass("br").addClass("bl");
	} else {
		$(".fwzt").removeClass("bl").addClass("br");
		//AutographJoin();
	}
}
//自动进入工作态  2.1.4
function setAutoWork() {
	/*如果设置了自动进入空闲态，则座席通话结束将自动进入空闲态，系统将自动给座席分配新的呼叫
	如果没有设置自动进入空闲态，则座席通话结束将自动进入工作态，在工作态时系统不会自动分配新的呼叫。
	*/
	Phone.SetAgentAutoEnterIdle(false);
}

//自动释放呼叫
function setAutoRelease() {
	/*如果AutoRelease 设置为True，接续控件将自动释放话路
	如果AutoRelease 设置为False，则需座席主动释放。
	*/
	Phone.AutoRelease = true;
}
//坐席状态
function setAgentStatus(str) {
	switch(str) {
		case "离席":
			$(".zxzt").removeClass("bl").addClass("br");
			$('.hwzt').html("坐席未登录");
			break;
		case "空闲":
			$(".zxzt").removeClass("br").addClass("bl");
			$('.hwzt').html("坐席空闲");
			break;
		case "忙":
			$(".zxzt").removeClass("bl").addClass("br");
			$('.hwzt').html("坐席忙");
			break;
		case "业务处理":
			$(".zxzt").removeClass("bl").addClass("br");
			$('.hwzt').html("业务处理");
			break;
	}
}
//变换按钮图标 挂断转满意度 .外乎。置忙。置闲。三方通话。转移。保持。接回
function Form_setWinfromenble(begd, beMakeCall, bezm, bezx, behy, beTransfer, bebc, bejh, beqr, beqc) {
	if(begd == "True") { //挂断
		$('.DropCall').addClass("active")
	} else {
		$('.DropCall').removeClass("active")
	}
	if(beMakeCall == "True") { //外呼
		$('.MakeCall').addClass("active")
	} else {
		$('.MakeCall').removeClass("active")
	}
	if(bezm == "True") { //示忙可以用
		$('.SayBusy').addClass("active")
	} else {
		$('.SayBusy').removeClass("active")
	}
	if(bezx == "True") { //示闲可以用
		$('.SayFree').addClass("active")
	} else {
		$('.SayFree').removeClass("active")
	}
	if(behy == "True") { //多方通话
		$('.Meeting').addClass("active")
	} else {
		$('.Meeting').removeClass("active")
	}
	if(beTransfer == "True") { //转移
		$('.Transfer').addClass("active")
	} else {
		$('.Transfer').removeClass("active")
	}
	if(bebc == "True") { //保持
		$('.Hold').addClass("active")
	} else {
		$('.Hold').removeClass("active")
	}

	if(bejh == "True") { //接回
		$('.Retrieve').addClass("active")
	} else {
		$('.Retrieve').removeClass("active")
	}
	if(beqr == "True") { //签入
		$('.Login').addClass("active")
	} else {
		$('.Login').removeClass("active")
	}
	if(beqc == "True") { //签出
		$('.Logout').addClass("active")
	} else {
		$('.Logout').removeClass("active")
	}
}
///外呼
function PhoneCallOut(type, tel) {
	becallout = true;
	becallcome = false;
	//添加外呼记录
	var userid = $("#userId").val();
	var usercode = $("#userCode").val();
	var username = $("#userName").val();
	var extnumber = $("#extenNum").val();
	var timeno = new Date().getTime();
	username = encodeURI(username);
	$('.hwzt').html('开始呼叫...');
	$.ajax({
		type: "get",
		url: huayi.config.callcenter_url + "CallOutOpt/CallOut",
		async: true,
		dataType: 'json',
		data: {
			token: $.cookie("token"),
			phone: tel,
			workorderid: ''
		},
		success: function(res) {
			if(res.state.toLowerCase() == "success") {
				var DialIsOK = false;
				$('#callId').val(res.data.callid);
				//成功执行外呼叫
				if(res.data.type + '' == '0') { //呼叫内部（座席）电话
					//2015-04-20
					becallout = true;
					becallcome = false;
					console.log("电话类型：" + res.data.type + "号码：" + res.data.phone);
					DialIsOK = Phone.CallOutEx3(5, '', res.data.phone, '', 0, 3, '');
				} else { //呼叫外部电话
					console.log("电话类型：" + res.data.type + "号码：" + res.data.phone);
					DialIsOK = Phone.CallOutEx3(5, $('.gd_whNum').text(), res.data.phone, '', 0, 3, '');
				}
				$('#Result').val('');
				$(".WH").addClass("hidens");
				if(DialIsOK != 0) {
					console.log(Phone.GetPromptByErrorCode(DialIsOK))
					layer.msg('外呼失败', {
						time: 20000, //20s后自动关闭
						btn: ['确认']
					});
				}
			}

		}
	});
}
///转移
function PhoneCallZY(tel) {
	try {
		Form_setWinfromenble("false", "false", "false", "false", "false", "false", "false", "false", "false", "false");
		var callinphone = $("#ZYNumber").val();
		Phone.TransOutEx2(5, callinphone, tel, 2, 0, '');
		console.log('转移' + Phone.GetPromptByErrorCode(Phone.TransOutEx2(5, callinphone, tel, 2, 0, '')))
	} catch(e) {
		layer.msg(e.message);
		console.log(e.message);

	}

}
///多方通话
function PhoneCallDFTH(tel) {
	try {
		Form_setWinfromenble("false", "false", "false", "false", "false", "false", "false", "false", "false", "false");
		var callinphone = $("#ZYNumber").val();
		Phone.TransOutEx2(5, callinphone, tel, 4, 0, '');
		console.log('三方' + Phone.GetPromptByErrorCode(Phone.TransOutEx2(5, callinphone, tel, 4, 0, '')))
	} catch(e) {
		layer.msg(e.message);
	}
}
//释放呼叫  2.1.8  挂断
function ReleaseAnswer() { //挂机
	MydTransToIVR();
	try {
		var rtn = Phone.ReleaseCallEx(5);
		LineStatus = 2; //调用释放方法后，直接挂机，收不到OnPhoneStatusNotify反馈的LineStatus状态值，这里手动赋值
	} catch(e) {}

}
//满意度
function MydTransToIVR() {
	var rtn = Phone.TransToIVR(5, 0, '9999');
}
//座席置忙 2.1.12
function AgentBusy() {
	//将座席状态设置为忙态。
	Phone.SayBusy();
	console.log(Phone.GetPromptByErrorCode(Phone.SayBusy()))
	//2014-10-22
	becallout = true;
	becallcome = false;

	//置忙日志
	$.get(huayi.config.callcenter_url + 'CallInScreen/AddTelBusyDelgate', {
		"token": $.cookie("token")
	}, function(res) {
		//			if(res.state.toLowerCase() == "success") {
		res = JSON.parse(res);
		console.log(res);
		console.log(res.data);
		if(res.state == "success") {
			$('#callLogid').val(res.data);
		}
	});

}
//座席置闲 2.1.13
function AgentFree() {
	//将座席状态设置为闲态。
	var rtn = Phone.SayFree();
	console.log(Phone.GetPromptByErrorCode(rtn))
	//2014-10-22
	becallout = false;
	becallcome = true;
	//置闲日志
	console.log("置闲日志" + $('#callLogid').val());
	$.get(huayi.config.callcenter_url + 'CallInScreen/UpdateTelFreeDelgate', {
		calllogid: $('#callLogid').val(),
		"token": $.cookie("token")
	}, function(res) {});

	return rtn;
}
//保持 2.1.17	
function KeepCall() {
	//该方法把座席正在通话的普通语音呼叫保持（只对语音呼叫有效）。
	//var rtn = OCX_Hold();
	var rtn = Phone.HoldEx();
	//查询座席当前保持的所有语音呼叫。
	Phone.QueryHoldListEx();
	var option = "";
	if(rtn == '0') {
		for(i = 0; i < Phone.CallIDNum; i++) {
			//获取callid
			var holdcallid = Phone.GetCallIDByIdx(i);
			if(holdcallid > 0) {
				//查询呼叫扩展详细信息
				if(Phone.QueryCallInfoEx(holdcallid) == '0') {
					var callerno = Phone.CallInfoEx_Ani; //获取主叫号码
					$("#ZYNumber").val(callerno);
				}
			}
		}

	} else {
		alert("保持失败");
	}
}
//取保持  2.1.18    接回
function GetKeepCall() {
	//查询座席当前保持的所有语音呼叫
	//var rtn = OCX_UnHold();
	//查询座席当前保持的所有语音呼叫
	var rtn = Phone.QueryHoldListEx();
	if(rtn != '0') {
		alert("接回失败");
	} else {
		if(Phone.CallIDNum > 0) {
			for(i = 0; i < Phone.CallIDNum; i++) {
				//获取callid
				var holdcallid = Phone.GetCallIDByIdx(i);
				if(holdcallid > 0) {
					//查询呼叫扩展详细信息
					if(Phone.QueryCallInfoEx(holdcallid) == '0') {
						var callerno = Phone.CallInfoEx_Ani; //获取主叫号码
						if(callerno == $("#ZYNumber").val()) {
							//座席取回一个被保持的普通语音呼叫进行通话（只对普通语音呼叫有效）。
							var rtn = Phone.GetHoldEx(holdcallid);
							if(rtn == '0') {
								console.log('接回成功！')
								return;
							} else {
								alert("操作失败");
							}
						}
					}
				}
			}
		} else {
			alert("对方已经挂机！");
			ReleaseAnswer(); //挂断
		}
	}
}
//获得随路数据
var IVRSelKey = "";

function GetIVRMsg() {
	var _callid = 0;
	if(Phone.QueryCallIDOnAgentEx(Phone.WorkNo) == 0) {
		_callid = Phone.GetCallIDByIdx(0);
		if(_callid != 0) {
			if(Phone.QueryCallInfoEx(_callid) == 0) {
				IVRSelKey = Phone.CallInfoEx_CallData;
			}
		}
	}
	return "";
}

//电话操作事件
//话机状态改变事件
function OnPhoneStatusNotify(status) {

	var timeno = new Date().getTime();
	var _UserNo = $('#userCode').val();
	try {
		Phone.QueryCallIDOnAgentEx(_UserNo);
		for(i = 0; i < Phone.CallIDNum; i++) {
			var _CallId = Phone.GetCallIDByIdx(i);
		}
		Phone.QueryCallInfoEx(_CallId);
		var CallId = IVRSelKey;
		var NowCallerPhoneCode = Phone.CallInfoEx_Ani;
		if(becallcome) {
			//获取呼叫编号callId
			$.ajax({
				type: "get",
				url: huayi.config.callcenter_url + 'CallInScreen/GetCallIdByPhone',
				async: false,
				dataType: 'json',
				data: {
					telphone: NowCallerPhoneCode,
					"token": $.cookie("token")
				},
				success: function(res) {
					if(res.state == "success") {
						console.log('获取callId' + res.data.CallId)
						$('#callId').val(res.data.CallId);
						$('#BusinessType').val(res.data.BusinessType);
						updateCallLogs(NowCallerPhoneCode, status, becallcome);
					}
				}
			});

		} else {
			updateCallLogs($('#callOutNumber').val(), status, becallcome);
		}

	} catch(e) {}

	/*
	0; //振铃
	1; //摘机
	2; //挂机
	*/
	if(status == 0) {
		Phone.QueryCallIDOnAgentEx(_UserNo);
		for(i = 0; i < Phone.CallIDNum; i++) {
			var _CallId = Phone.GetCallIDByIdx(i)
		}
		Phone.QueryCallInfoEx(_CallId);
		var telphone = Phone.CallInfoEx_Ani;//获取主叫号码
	    //CallInfoEx_DialedNumber 获取被叫号码
		if(becallcome) {
			console.log('zlzl前' + $('#callId').val());
			updateZL($('#callId').val());
			Form_callCommingCaller(telphone, $('#callId').val(), $('#BusinessType').val());
		}
		becallout = false;
		becallcome = true;
	} else if(status == 1) {
		console.log($('#callId').val());
		//更新摘机事件
		$.get(huayi.config.callcenter_url + 'CallInScreen/UpdateZJ', {
			callid: $('#callId').val(),
			timeno: timeno,
			"token": $.cookie("token")
		}, function(res) {
			console.log("CallInScreen/UpdateZJ");
			console.log(res);
		});
		//改变按钮图片
		Form_setWinfromenble("True", "false", "false", "false", "True", "True", "True", "false", "false", "false");
		setAgentStatus("忙");

	} else if(status == 2) {
		console.log("CallInScreen/UpdateGJ");
		//更新挂机事件
		$.get(huayi.config.callcenter_url + 'CallInScreen/UpdateGJ', {
			callid: $('#callId').val(),
			timeno: timeno,
			"token": $.cookie("token")
		}, function(res) {
			console.log(res);
		});
		Form_setWinfromenble("false", "True", "True", "false", "false", "false", "false", "false", "false", "false");
		setAgentStatus("空闲");
		becallout = false;
		becallcome = true;
	}
	//					} catch(e) {
	//						console.log(e.message)
	////						layer.msg();
	//					}
	console.log("话机状态：" + status);
}
//更新振铃事件
function updateZL(callids) {
	$.get(huayi.config.callcenter_url + 'CallInScreen/UpdateZL', {
		callid: callids,
		"token": $.cookie("token")
	}, function(res) {
		console.log("CallInScreen/UpdateZL");
		console.log(res);
	});

}
//添加话务日志
function updateCallLogs(telNum, status, callcomes) {
	$.get(huayi.config.callcenter_url + 'CallInScreen/AddCallLogs', {
		telno: telNum,
		Status: status,
		becallcome: callcomes,
		hjbh: $('#callId').val(),
		"token": $.cookie("token")
	}, function(res) {});
}
//来电弹屏事件
function Form_callCommingCaller(callerNum, callid, calledType) {
	console.log('callid' + callid + 'calledType' + calledType);
	becallout = false;
	becallcome = true;
	var p = '<a href="javascript:;" class="active J_menuTab" data-id="./callScreen/callScreen.html?Number=' + callerNum + '&CallID=' + callid + '&callType=' + calledType + '">来电' + callerNum + ' <i class="fa fa-times-circle"></i></a>';
	$(".J_menuTab").removeClass("active");
	var nif = '<iframe class="J_iframe J_iframeNew" name="iframe' + callid + '"  width="100%" height="100%" src="./callScreen/callScreen.html?Number=' + callerNum + '&CallID=' + callid + '&callType=' + calledType + '" frameborder="0" data-id="./callScreen/callScreen.html?Number=' + callerNum + '&CallID=' + callid + '&callType=' + calledType + '" seamless></iframe>';
	$(".J_mainContent").find("iframe.J_iframe").hide().parents(".J_mainContent").append(nif);
	$(".J_menuTabs .page-tabs-content").append(p);
	$("#ZYNumber").val(callerNum); //转移号码
	$("#callNumber").val(callerNum); //来电号码
}
//录音成功
function Form_callComming(callerNum, parth) {
	console.log('CallInScreen/UpdateLY');
	console.log(parth);
	console.log(callerNum);
	console.log($('#callId').val());
	var timeno = new Date().getTime();
	$.get(huayi.config.callcenter_url + 'CallInScreen/UpdateLY', {
		callid: $('#callId').val(),
		path: parth,
		timeno: timeno,
		"token": $.cookie("token")
	}, function(res) {
		console.log(res);
		//						if(res.state.toLowerCase() == "success") {
		//						}
	});
	Form_setWinfromenble("True", "false", "false", "false", "True", "True", "True", "false", "false", "false");
}

//==========================OCX结束===========================================================================================
//菜单数字
function workcount() {
	$.getJSON(huayi.config.callcenter_url + 'Index/GetWorkOrderCount', {
		"token": $.cookie("token")
	}, function(result) {
		if(result.state.toLowerCase() == "success") {
			$(".dpd").text(result.data.dpd);
			$(".djd").text(result.data.djd);
			//   $(".dcl").text(result.data.dcl);
		}
	})
}
//上传头像
function uploadtx() {
	if(document.getElementById("upFile").files.length > 0) {
		var formData = new FormData();
		formData.append("upFile", document.getElementById("upFile").files[0]);
		formData.append("token", $.cookie("token"));
		$.ajax({
			url: huayi.config.callcenter_url + "Index/UploadTX",
			type: "POST",
			data: formData,
			/**
			 *必须false才会自动加上正确的Content-Type
			 */
			contentType: false,
			/**
			 * 必须false才会避开jQuery对 formdata 的默认处理
			 * XMLHttpRequest会对 formdata 进行正确的处理
			 */
			processData: false,
			success: function(result) {
				document.getElementById("upFile").outerHTML = document.getElementById("upFile").outerHTML;
				$("#upFile").change(function() {
					uploadtx();
				});
				var r = $.parseJSON(result);
				if(r.state.toLowerCase() == "success") {
					$(".yhtx").attr("src", huayi.config.callcenter_url.substr(0, huayi.config.callcenter_url.length - 1) + r.data);

					layer.msg("上传成功");
				}
			}
		});
	} else {
		layer.confirm('请上传文件！', {
			btn: ['确定']
		});
	}
}

function GetCallState(val) {
	if(val == '1') {
		return '已接通';
	} else {
		return '未接通';
	}
}

//音频
function setCode(val) {
	if(val) {
		return '<div class="imgs" style="cursor: pointer;">' +
			'<img src="./img/vice.png" alt="" onclick= ck(this) item="' + val + '" />' +
			'</div>';
	} else {
		return '';
	}
}
//录音
function ck(val) {
	var path = $(val).attr("item");
	$(".t-shade").addClass("cx");
	$(".Ly_box").empty();
	$(".down").attr("href", path);
	$('<audio style="width: 100%;"class=" " src="' + path + '" loop="loop" controls="controls" ></audio>').appendTo(".Ly_box");
}

function GetDealState(val) {
	if(val == '1') {
		return '已处理';
	} else {
		return '未处理';
	}
}

function GetStateName(val) {
	var str = '';
	//switch (val + '') {
	//    case '0':
	//        str = "待指派";
	//        break;
	//    case '1':
	//        str = "处理中";
	//        break;
	//    case '2':
	//        str = "已完结";
	//        break;
	//}
	switch(val + '') {
		case '0':
			str = "待处理";
			break;
		case '1':
			str = "已处理";
			break;
	}
	return str;
}

function GetCont(val) {
	var str = '<div '
	if(val.length > 20) {
		str = str + ' title="' + val + '" ';
		val = val.substr(0, 20) + "...";
	}
	return str + '>' + val + '</div>';
}

//获取类型
function getLX(obj, type) {
	obj.empty();
	$.getJSON(huayi.config.callcenter_url + 'Dictionary/GetDicValueListByFlag', {
		"flag": type,
		"token": $.cookie("token")
	}, function(result) {
		if(result.state.toLowerCase() == "success") {
			$(result.data).each(function(i, n) {
				obj.append('<option value="' + n.F_DictionaryValueId + '">' + n.F_Name + '</option>');
			})
		}
	})
}
//获取部门
var setting = {
	data: {
		key: {
			name: "F_DeptName"
		},
		simpleData: {
			enable: true,
			idKey: "F_DeptId",
			pIdKey: "F_ParentId",
			rootPId: 0
		}
	},
	callback: {
		onClick: zTreeOnClick
	}
};

function getBM(obj) {
	$.getJSON(huayi.config.callcenter_url + 'Department/GetAllList', {
		"token": $.cookie("token")
	}, function(result) {
		if(result.state.toLowerCase() == "success") {
			$.fn.zTree.init(obj, setting, result.data);
		}
	})
}

function zTreeOnClick(event, treeId, treeNode) {
	var obj = $("#" + event.data.treeId).parent();
	obj.parent().find("input").eq(0).val(treeNode.F_DeptName);
	obj.parent().find("input").eq(1).val(treeNode.F_DeptId);
	obj.hide();
	if(event.data.treeId == "zrbmtree") {
		getRY($("#zrid"), $("#zrbm").val());
	}
	if(event.data.treeId == "clbmtree") {
		getRY($("#clid"), $("#clbm").val());
	}
};
//获取人员
function getRY(obj, deptid) {
	obj.empty();
	obj.append('<option value="">--请选择--</option>');
	$.getJSON(huayi.config.callcenter_url + 'UserAccount/GetDeptUserList', {
		"deptid": deptid,
		"token": $.cookie("token")
	}, function(result) {
		if(result.state.toLowerCase() == "success") {
			$(result.data).each(function(i, n) {
				obj.append('<option value="' + n.F_UserId + '">' + n.F_UserName + '</option>');
			})
		}
	})
}
//外呼弹屏
function whtp() {
	$("#Result").val("");
	if($(".WH").hasClass("fadeOutUp")) {
		$(".WH").removeClass("fadeOutUp").addClass("fadeInDown");
	}
	$(".WH").removeClass("hidens");

	$('.first').removeClass('first');
	$('.WH').addClass('first');

	loadWH();
}
//加载外呼电话列表
function loadWH() {
	$(".phonediv").hide();
	var n = $(".bg_title .lactive").attr("itemid");
	switch(n) {
		case '0':
			var obj = $(".phonediv").eq(0);
			obj.show();

			//先销毁表格
			var table = obj.find(".phonelist");
			table.bootstrapTable('destroy');
			//初始化表格,动态从服务器加载数据
			table.bootstrapTable({
				method: "get", //使用get请求到服务器获取数据
				url: huayi.config.callcenter_url + "CallOutScreen/GetPhoneList", //获取数据的Servlet地址
				contentType: 'application/x-www-form-urlencoded',
				striped: true, //表格显示条纹
				pagination: true, //启动分页
				pageSize: 10, //每页显示的记录数
				pageNumber: 1, //当前第几页
				pageList: [10, 20, 50, 100], //记录数可选列表
				search: false, //是否启用查询
				showColumns: false, //显示下拉框勾选要显示的列
				showRefresh: false, //显示刷新按钮
				sidePagination: "server", //表示服务端请求
				//设置为undefined可以获取pageNumber，pageSize，searchText，sortName，sortOrder
				//设置为limit可以获取limit, offset, search, sort, order
				queryParamsType: "undefined",
				queryParams: function queryParams(params) { //设置查询参数
					var param = {
						page: params.pageNumber,
						pagesize: params.pageSize,
						tel: $("#lastphone").val(),
						token: $.cookie("token")
					};
					return param;
				},
				onLoadSuccess: function() { //加载成功时执行
					//layer.msg("加载成功");
				},
				onLoadError: function() { //加载失败时执行
					//layer.msg("加载数据失败", { time: 1500, icon: 2 });
				}
			});
			break;
		case '1':
			var obj = $(".phonediv").eq(1);
			obj.show();
			getDepts(); //获取部门下拉

			var table = obj.find(".phonelist");
			table.bootstrapTable('destroy');
			//初始化表格,动态从服务器加载数据
			table.bootstrapTable({
				method: "get", //使用get请求到服务器获取数据
				url: huayi.config.callcenter_url + "CallOutScreen/GetUserList", //获取数据的Servlet地址
				contentType: 'application/x-www-form-urlencoded',
				striped: true, //表格显示条纹
				pagination: true, //启动分页
				pageSize: 10, //每页显示的记录数
				pageNumber: 1, //当前第几页
				pageList: [10, 20, 50, 100], //记录数可选列表
				search: false, //是否启用查询
				showColumns: false, //显示下拉框勾选要显示的列
				showRefresh: false, //显示刷新按钮
				sidePagination: "server", //表示服务端请求
				//设置为undefined可以获取pageNumber，pageSize，searchText，sortName，sortOrder
				//设置为limit可以获取limit, offset, search, sort, order
				queryParamsType: "undefined",
				queryParams: function queryParams(params) { //设置查询参数
					var param = {
						page: params.pageNumber,
						pagesize: params.pageSize,
						zxzid: $('#s_department').val(),
						tel: $("#gsphone").val(),
						name: $("#gsname").val(),
						token: $.cookie("token")
					};
					return param;
				},
				onLoadSuccess: function() { //加载成功时执行
					//layer.msg("加载成功");
				},
				onLoadError: function() { //加载失败时执行
					//layer.msg("加载数据失败", { time: 1500, icon: 2 });
				}
			});
			break;
		case '2':
			var obj = $(".phonediv").eq(2);
			obj.show();

			var table = obj.find(".phonelist");
			table.bootstrapTable('destroy');
			//初始化表格,动态从服务器加载数据
			table.bootstrapTable({
				method: "get", //使用get请求到服务器获取数据
				url: huayi.config.callcenter_url + "CallOutScreen/GetCustomerList", //获取数据的Servlet地址
				contentType: 'application/x-www-form-urlencoded',
				striped: true, //表格显示条纹
				pagination: true, //启动分页
				pageSize: 10, //每页显示的记录数
				pageNumber: 1, //当前第几页
				pageList: [10, 20, 50, 100], //记录数可选列表
				search: false, //是否启用查询
				showColumns: false, //显示下拉框勾选要显示的列
				showRefresh: false, //显示刷新按钮
				sidePagination: "server", //表示服务端请求
				//设置为undefined可以获取pageNumber，pageSize，searchText，sortName，sortOrder
				//设置为limit可以获取limit, offset, search, sort, order
				queryParamsType: "undefined",
				queryParams: function queryParams(params) { //设置查询参数
					var param = {
						page: params.pageNumber,
						pagesize: params.pageSize,
						tel: $("#khphone").val(),
						name: $("#khname").val(),
						token: $.cookie("token")
					};
					return param;
				},
				onLoadSuccess: function() { //加载成功时执行
					//layer.msg("加载成功");
				},
				onLoadError: function() { //加载失败时执行
					//layer.msg("加载数据失败", { time: 1500, icon: 2 });
				}
			});
			break;
	}
}
//格式化最近电话处理方式
function formatterDealType(val, row) {
	//处理方式0:IVR处理1骚扰电话2自助服务3转值班电话4留言5呼损6人工处理
	var str = '-';
	switch(val) {
		case 0:
			str = 'IVR处理';
			break;
		case 1:
			str = '骚扰电话';
			break;
		case 2:
			str = '自助服务';
			break;
		case 3:
			str = '转值班电话';
			break;
		case 4:
			str = '留言';
			break;
		case 5:
			str = '呼损';
			break;
		case 6:
			str = '人工处理';
			break;
	}
	return str;
}
//获取外呼公司电话下 部门下拉
function getDepts() {
	$.getJSON(huayi.config.callcenter_url + "SeatGroup/GetList", {
		token: $.cookie("token"),
	}, function(data) {
		if(data.rows && data.rows.length > 0) {
			$('#s_department').html('');
			$('#s_department').append('<option value="">请选择</option>');
			$.each(data.rows, function(i, v) {
				$('<option value="' + v.F_ZXZID + '">' + v.F_ZXZName + '</option>').appendTo($('#s_department'));
			});
		}
	});
}

function view(val) {
	var str = '';
	if(val) {
		str = '<a onclick="call(\'' + val + '\')">' + val + '</a>';
	}
	return str;
}

function call(val) {
	$("#Result").val(val);
	$(".img").removeClass("hidens");
}

function logout() {
	//	if(!$('.Logout').hasClass('active')) {
	$.ajax({
		url: huayi.config.callcenter_url + "Login/Logout",
		data: {
			token: $.cookie("token")
		},
		dataType: "json",
		success: function(res) {
			if(res.state) {
				location.href = "./login.html";
			}
		}
	});
	//	} else {
	//		layer.msg("退出失败！");
	//	}

}
//用于实施记录登录时长
function GetLoginPermission() {
	$.ajax({
		url: huayi.config.callcenter_url + "Login/SummaryOnlinTime",
		data: {
			token: $.cookie("token")
		},
		dataType: "json",
		error: function(XMLHttpRequest, textStatus, errorThrown) {
			location.href = "./login.html";
		},
		success: function(res) {
			if(res.state.toLowerCase() !== 'success') {
				location.href = "./login.html";
			}
		}
	});
	setTimeout('GetLoginPermission', 120000);
};
GetLoginPermission();

//加载左侧导航菜单
function loadMenu() {
	$.ajaxSettings.async = false;
	$.getJSON(huayi.config.callcenter_url + 'Index/GetMenu', {
		"token": $.cookie("token")
	}, function(result) {
		$.ajaxSettings.async = true;
		if(result.state.toLowerCase() == "success") {
			var data = result.data;

			var _html = "";
			$.each(data, function(i) {
				var row = data[i];
				if(row.F_ParentID == "0") {
					_html += '<li>';
					_html += '<a  class="Click"data-id="Menu_' + row.F_ModuleId + '" href="' + row.F_OptUrl + '"><i class="fa iconfont">' + row.F_ImgUrl + '</i><span class="nav-label">' + row.F_ModuleName + '</span><span class="fa arrow"></span></a>';
					var childNodes = row.ChildNodes; //二级
					if(childNodes.length > 0) {
						_html += '<ul class="nav nav-second-level">';
						$.each(childNodes, function(i) {
							var subrow = childNodes[i];

							var childNodsThird = subrow.ChildNodes; //三级
							if(childNodsThird.length > 0) {
								_html += '<li>';
								_html += '<a href="' + subrow.F_OptUrl + '">';
								_html += '<span class="nav-label">' + subrow.F_ModuleName + '</span>';
								_html += '<span class="fa arrow"></span>';
								_html += '</a>';
								_html += '<ul class="nav nav-third-level">';
								$.each(childNodsThird, function(i) {
									var subrowThird = childNodsThird[i];
									_html += '<li>';
									_html += '<a class="J_menuItem" data-id="Menu_' + subrowThird.F_ModuleId + '" href="' + subrowThird.F_OptUrl + '" >' + subrowThird.F_ModuleName + '</a>';
									_html += '</li>';
								});
								_html += '</ul>';
							} else {
								_html += '<li>';
								_html += '<a class="J_menuItem" data-id="Menu_' + subrow.F_ModuleId + '" href="' + subrow.F_OptUrl + '" >' + subrow.F_ModuleName + '</a>';
								if(subrow.F_Button != '') {
									_html += '<span class="' + subrow.F_Button + '"></span>';
								}
								_html += '</li>';
							}

						});
						_html += '</ul>';
					}
					_html += '</li>';
				}
			});
			//			            $("#sidebar-nav ul").prepend(_html);
			$(_html).appendTo("#side-menu");
		} else {
			window.location.href = "/login.html";
		}
	})
}

////跳转
function Jumps(urlStr, phoneNum) {
	//window.parent.frames[ "iframe0"].location.reload();
	//	$("iframe:visible")[0].src = "widgets.html"
	var l = '工单单据';
	var p = '<a href="javascript:;" class="active J_menuTab" data-id="' + urlStr + '">' + l + ' <i class="fa fa-times-circle"></i></a>';
	$(".J_menuTab").removeClass("active");
	var n = '<iframe class="J_iframe J_iframeNew" name="iframe' + phoneNum + '" width="100%" height="100%" src="' + urlStr + '" frameborder="0" data-id="' + urlStr + '" seamless></iframe>';
	$(".J_mainContent").find("iframe.J_iframe").hide().parents(".J_mainContent").append(n);
	$(".J_menuTabs .page-tabs-content").append(p);
}