$(document).ready(function() {
	initTable();
	initTables();
	$(".ss").click(function() {
		stype = 1;
		initTable();
		initTables();
	})
	/*高级查询*/
	$(".gjss").click(function() {
		$(".t-shade").addClass("cx");
		$(".gjsu").addClass("cx");
	});
	$("#gjss").click(function() {
		stype = 2;
		initTable();
		initTables();
		$(".t-shade").removeClass("cx");
		$(".gjsu").removeClass("cx");
	})
	$(".setwin").click(function() {
		$(".t-shade").removeClass("cx");
		$(".gjsu").removeClass("cx");
		$(".cbgd").removeClass("cx");
	})
	//详情
	$(".ckxq ul li").click(function() {
		$(this).addClass("Active").siblings().removeClass("Active");
		var i = $(this).index();
		$(".gdxq").hide();
		$(".gdxq").eq(i).show();
		if(i > 0) {
			cljl(i);
		}
	});
	$(".Closed").click(function() {
		$(".ckxq").addClass("Hidens");
	});
	/*tree下拉框效果*/
	$(".inpBox .tree").click(function() {
		if($(this).parent().find(".addTree").is(":hidden")) {
			$(this).parent().find(".addTree").show();
		} else {
			$(this).parent().find(".addTree").hide();
		}
	});
	/*普通下拉框效果*/
	$(".inpBox .select").click(function() {
		if($(this).parent().find(".xl_common").is(":hidden")) {
			$(this).parent().find(".xl_common").show();
		} else {
			$(this).parent().find(".xl_common").hide();
		}
	});
	$(".xl").click(function() {
		if($(this).parent().find(".addTree").is(":hidden")) {
			$(this).parent().find(".addTree").show();
		} else {
			$(this).parent().find(".addTree").hide();
		}
		if($(this).parent().find(".xl_common").is(":hidden")) {
			$(this).parent().find(".xl_common").show();
		} else {
			$(this).parent().find(".xl_common").hide();
		}
	});
	$(".inpBox").mouseleave(function() {
		$(this).children(".addTree").hide();
		$(this).children(".xl_common").hide();
	})
	$(".xl_box").on("click", "li", function() {
		var obj = $(this).parent().parent().parent();
		obj.find("input").eq(0).val($(this).text());
		obj.find("input").eq(1).val($(this).attr("itemid"));
		obj.find(".xl_common").hide();
	})
	$("input[name='ltype']").click(function() {
		var val = $("input[name='ltype']:checked").val();
		if(val == '0') {
			$(".js").show();
		} else if(val == '1') {
			$(".js").hide();
		}
	})
	if($("#zrbmtree")) {
		getBM($("#zrbmtree"));
	}

	laydate.render({
		elem: '#greetingTimes',
		range: '~',
		//							type: 'datetime',
		//max : 31,
		//										min: 0,
		theme: '#1ab394',
	});
	getAccount()
	//反馈单位
	getAccounts()

	function getAccount() {
		$.ajax({
			type: "get",
			url: huayi.config.callcenter_url + "Customer/BindLDdep",
			dataType: 'json',
			async: true,
			data: {
				token: $.cookie("token")
			},
			success: function(data) {
				var Count = data.data.dep;
				$(Count).each(function(i, n) {
					$("<option value='" + n + "'>" + n + "</option>").appendTo($("#comeCall_dep"));
				})
				$('#comeCall_dep').selectpicker('refresh');
			}
		});
	}

	function getAccounts() {
		$.ajax({
			type: "get",
			url: huayi.config.callcenter_url + "Customer/BindLDdep",
			dataType: 'json',
			async: true,
			data: {
				token: $.cookie("token")
			},
			success: function(data) {
				var Count = data.data.dep;
				$(Count).each(function(i, n) {
					$("<option value='" + n + "'>" + n + "</option>").appendTo($("#comeCall_deps"));
				})
				$('#comeCall_deps').selectpicker('refresh');
			}
		});
	}

	//工单来源
	getOrderSource()

	function getOrderSource() {
		$.ajax({
			type: "get",
			url: huayi.config.callcenter_url + "Dictionary/GetDicValueListByFlag",
			dataType: 'json',
			async: true,
			data: {
				token: $.cookie("token"),
				flag: "GDLY"
			},
			success: function(data) {
				var Count = data.data;
				$(Count).each(function(i, n) {
					$("<option value='" + n.F_DictionaryValueId + "'>" + n.F_Name + "</option>").appendTo($("#orderSource"));
				})
				$('#orderSource').selectpicker('refresh');
			}
		});
	}

	//工单类型
	getOrderType();

	function getOrderType() {
		$.get(huayi.config.callcenter_url + 'WorkType/GetTreeList', {
			"token": $.cookie("token"),
		}, function(result) {
			result = $.parseJSON(result);
			$.fn.zTree.init($("#TreeDemo"), setting3, result.data); //实例化树形图
		});
	}
	var setting3 = {
		data: {
			key: {
				name: "text"
			},
			simpleData: {
				enable: true,
				idKey: "id",
				rootPId: 0
			}
		},
		callback: {
			onClick: changeTreeClick
		}
	}

	function changeTreeClick(event, treeId, treeNode) {
		var chanId = treeNode.id;
		var changeName = treeNode.text;
		$('#typeclass').val(changeName);
		$('#typeclassId').val(chanId);
		var pidnode = treeNode.getParentNode();
	};

	$('.down').click(function() {
		if($('.treeList').css('display') == 'block') {
			$('.treeList').css('display', 'none')
		} else {
			$('.treeList').css('display', 'block')
		}
	})

	$('#typeclass').click(function() {
		$('.treeList').css('display', 'block')
	})
	$('.treeList').mouseleave(function() {
		$(this).css('display', 'none')
	})
	//坐席
	getSeating()

	function getSeating() {
		$.ajax({
			type: "get",
			url: huayi.config.callcenter_url + "CallInScreen/GetUsers",
			dataType: 'json',
			async: true,
			data: {
				token: $.cookie("token")
			},
			success: function(data) {
				var Count = data.data.user;
				$(Count).each(function(i, n) {
					$("<option value='" + n.F_UserCode + "'>" + n.F_UserName + "</option>").appendTo($("#userid"));
				})
				$('#userid').selectpicker('refresh');
			}
		});
	}

})
//编辑器配置
KindEditor.ready(function(K) {
	window.changeEditor = K.create('#cl_gdnr'); //修改弹出框编辑器
});
var F_UserCode = localStorage.getItem('F_UserCode');

function View(val, row) {
	return '<div class="imgs" ><a class="xg" index="' + row.CreateUser + '" onclick= ck("' + val + '") >' + val + '</a></div>';
	$("#F_UserCode").val(row.CreateUser);
}

function OverTime(val, row) {
	var cs = 'Ctime';
	if(row.LimitTime || row.State == 1) {
		if(row.totalhour * 1 > row.LimitTime * 1) {
			cs = 'overTime_';
		}
	}
	return '<div class="' + cs + '" ><a class="xg" ></a></div>';
}

function ck(val) {
	selid = val;
	$('.modify').attr('index', selid)
	$(".ckxq").removeClass("Hidens");
	$(".ckxq ul li").eq(0).trigger("click");
	xq();
}

function Detail(val) {
	if(val) {
		var strD = decodeURIComponent(val);
		strD = helper.filter.filterHTMLTag(strD);
		if(strD.length > 10){
			strD = strD.substring(1,10) + '...';
		}
		return strD;
	}

}

function xq() {
	$.getJSON(huayi.config.callcenter_url + 'WorkOrder/GetWorkOrder', {
		"orderid": selid,
		"token": $.cookie("token")
	}, function(result) {
		if(result.state.toLowerCase() == "success") {
			if(result.data.data.length > 0) {
				var data = result.data.data[0];
				$("#xq_gdbh").text(data.WorkOrderID);
				$("#xq_gdlx").text(data.GDLXName);
				$("#xq_cjsj").text(data.CreateTime);
				$("#xq_gdzt").html(GetStateName(data.State));
				$("#xq_khxm").text(data.Customer);
				$("#xq_khdh").text(data.CustomerTel);
				$("#xq_wtlx").text(data.Address);
				$("#xq_zxgh").text(data.Source);
				$("#xq_gdnr").html(decodeURIComponent(data.Detail)); //工单详情
				$('#bz-1').text(data.County);
				$("#bz-2").text(data.Province);
				$("#bz-3").text(data.City);
				$("#xq_kdxx").text(data.Files);

				$(".gdxq").eq(0).find(".allbc").remove();
				if(result.data.item.length > 0) {
					var html = '<div class="allbc">补充记录' +
						'<table class="table table-hover table-striped"><thead><tr><th><div class="th-inner">补充人</div></th>' +
						'<th><div class="th-inner">补充详情</div></th><th><div class="th-inner">创建时间</div></th></tr></thead><tbody>';

					$(result.data.item).each(function(i, n) {
						html += '<td>' + n.CreateUserName + '</td><td>' + n.Detail + '</td><td>' + n.CreateTime + '</td>';
					})
					html += '</tbody></table></div>';
					$(".gdxq").eq(0).append($(html));
				}
			}
		}
	})
}

function cljl(type) {
	//先销毁表格
	var table = $(".gdxq").eq(type).find("table");
	table.bootstrapTable('destroy');
	//初始化表格,动态从服务器加载数据
	table.bootstrapTable({
		method: "get", //使用get请求到服务器获取数据
		url: huayi.config.callcenter_url + "WorkOrder/GetItemList", //获取数据的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,
				type: type,
				id: selid,
				token: $.cookie("token")
			};
			return param;
		},
		onLoadSuccess: function() { //加载成功时执行
			//layer.msg("加载成功");
		},
		onLoadError: function() { //加载失败时执行
			//layer.msg("加载数据失败", { time: 1500, icon: 2 });
		}
	});
}

function GetTypeName(val) {
	var str = '';
	switch(val + '') {
		case '1':
			str = "咨询";
			break;
		case '2':
			str = "报修服务";
			break;
		case '3':
			str = "投诉建议";
			break;
	}
	return str;
}

function GetStateName(val) {
	//  var str = '';
	//  switch (val + '') {
	//      case '0': str = "待指派"; break;
	//      case '1': str = "处理中"; break;
	//      case '2': str = "已完结"; break;
	//  }
	//if(val==0){
	//	return '<div class="warning">待指派</div>'
	//}else if(val==1){
	//	return '<div class="primary">处理中</div>'
	//}else if(val==2){
	//	return '<div class="defauli">已完结</div>'
	//    }
	if(val == 0) {
		return '<div class="warning">待处理</div> '
	} else {
		return '<div class="defauli">已处理</div>'

	}
	return str;
}

function ComXQ(val, row) {
	var str = '';
	if(row.IsLast) {
		str = str + row.CreateUser + " 完结工单。" + "<br>";
	}
	if(row.DealTime) {
		str = str + row.CreateUser + " 处理工单：" + "<br>";
		str = str + row.Detail + "<br>";
	}
	if(row.SureUserName) {
		str = str + row.SureUserName + " 接单。" + "<br>";
	}
	if(row.ToDeptName) {
		str = str + row.CreateUserName + " 指派工单给 " + row.ToDeptName + " ";
		if(row.ToUserName) {
			str = str + row.ToUserName;
		}
		str = str + "<br>";
	}
	if(row.IsStart) {
		str = str + row.CreateUserName + " 重新开启工单。" + "<br>";
	}
	return str;
}
//获取部门
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) {
	if(event) {
		event.stopPropagation();
	}
	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();
	getRY($(".clid"), $("#clbm").val());
};
//获取人员
function getRY(obj, deptid) {
	obj.empty();
	obj.append('<li itemid="">--请选择--</li>');
	obj.parent().parent().find("input").eq(0).val("--请选择--");
	obj.parent().parent().find("input").eq(1).val("");
	$.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('<li itemid="' + n.F_UserCode + '">' + n.F_UserName + '</li>');
			})

			obj.find("li").click(function(event) {
				if(event) {
					event.stopPropagation();
				}
				$(this).parent().parent().parent().find("input").eq(0).val($(this).text());
				$(this).parent().parent().parent().find("input").eq(1).val($(this).attr("itemid"));
				$(this).parent().parent().hide();
			});
		}
	})
}

function Appoint(val, row) {
	return czhtml(val, row, "处理");
}

function Dispose(val, row) {
	return czhtml(val, row, "处理");
}

function czhtml(val, row, str) {
	if(row.CreateUser == F_UserCode) {
		return '<div class="imgs" ><a class="xg" itemstr=\'' + JSON.stringify(row) + '\' onclick= oper("' + val + '",this) >' + str + '</a></div>';
	}

}

function oper(val, obj) {
	zpid = val;
	var zp = JSON.parse($(obj).attr("itemstr"));
	$("#cl_gdbh").text(zp.WorkOrderID);
	$("#cl_gdlx").text(zp.TypeClassName);
	$("#cl_khxm").text(zp.Customer);
	$("#cl_khdh").text(zp.CustomerTel);
	changeEditor.html(decodeURIComponent(zp.Detail))

	$("#clbmname").val("");
	$("#clbm").val("");
	$("#clidname").val("");
	$("#clid").val("");
	$(".clid").empty();

	$("#cont").val("");

	$(".t-shade").addClass("cx");
	$(".clgd").addClass("cx");
}
//点解
$('.modify').click(function() {
	var id = $(this).attr('index');
	layer.open({
		type: 2,
		title: '修改工单',
		maxmin: true, //开启最大化最小化按钮
		area: ['80%', '90%'],
		content: '../WorkOrder/Xga.html?id=' + id
		//              content: 'addZhiShiKuManger.html?addId=' + id + '&addPid='+ pid +'&addName='+ name +''
	});
})
//
function TZ(val) {
	var id = val;
	layer.open({
		type: 2,
		title: '修改工单',
		maxmin: true, //开启最大化最小化按钮
		area: ['80%', '90%'],
		content: '../WorkOrder/Xga.html?id=' + id
		//              content: 'addZhiShiKuManger.html?addId=' + id + '&addPid='+ pid +'&addName='+ name +''
	});
}

function Remove(val, row) {
	if(row.CreateUser == F_UserCode) {
		return '<div class="imgs RemoveC" ><a  onclick= remove("' + val + '") >删除</a> <a  onclick= TZ("' + row.WorkOrderID + '") >修改</a> </div>';
	}

}

function remove(str, row) {
	var type = $('#orderSource').val(); //工单来源
	var typeclass = $('#typeclassId').val(); //工单类型
	var starttime = $('#greetingTimes').val() && $('#greetingTimes').val().split(' ~ ')[0]; //开始时间
	var endtime = $('#greetingTimes').val() && $('#greetingTimes').val().split(' ~ ')[1]; //结束时间
	var lddep = $('#comeCall_dep').val(); //来电单位
	var fkdep = $('#comeCall_deps').val(); //来电单位
	var userid = $('#userid').val(); //坐席
	layer.confirm('确定删除当前记录？', {
		btn: ['是', '否'] //按钮
	}, function(index) {
		/*执行删除*/
		$.ajax({
			type: "get",
			url: huayi.config.callcenter_url + "WorkOrder/DelWorkOrder",
			dataType: 'json',
			async: true,
			data: {
				ids: str,
				token: $.cookie("token")
			},
			success: function(data) {
				layer.msg("删除成功！");
				initTable(type, typeclass, starttime, endtime, lddep, fkdep, userid);
				initTables(type, typeclass, starttime, endtime, lddep, fkdep, userid);
				layer.close(index);
			}
		});
	});
}

//受理人判断
function GetState(val, row) {
	if(val == 0) {
		return '<div class="defauli">' + row.CreateUserNameRel + '</div>'
	} else {
		return '<div class="defauli">' + row.LastDealUserNameRel + '</div>'
	}
}