var token = $.cookie("token");
var id; //当前节点id
var pid; //当前父节点ID
var name; //选择的name
var pidName; //父节点name
var keyWord = $('.searCon').val(); //关键字
var xlName; //添加下拉框节点name
var table = $('#table1'); //右边表格
//搜索按钮
$('.searchGo').click(function() {
	keyWord = $('.searCon').val();
	initTable(token, id, keyWord);
	//if (keyWord) {
	//    initTable(token, id, keyWord);
	//} else {
	//    layer.confirm('请输入搜索内容！', {
	//        btn: ['确定']
	//    });
	//    return;
	//}

})
$.get(huayi.config.callcenter_url + "Department/GetDeptList", {
	"token": $.cookie("token"),
	"pid": pid
}, function(result) {
	result = $.parseJSON(result);
	$.fn.zTree.init($("#treeDemo"), setting1, result.data); //实例化树形图
});
var setting1 = {
	data: {
		key: {
			name: "text"
		},
		simpleData: {
			enable: true,
			idKey: "id",
			rootPId: 0
		}
	},
	callback: {
		onClick: zTreeOnClick
	}
};

function zTreeOnClick(event, treeId, treeNode) {
	id = treeNode.id;
	name = treeNode.text;
	var pidnode = treeNode.getParentNode();
	if(pidnode) {
		pidName = pidnode.text;
		pid = pidnode.id;
		console.log(pid);
	} else {
		pidName = "顶级分类";
		pid == 0;
		console.log(pid);
	}
	keyWord = $('.searCon').val();
	initTable(token, id, keyWord)
};

//===============添加功能开始=============================
//用户生日
laydate.render({
	elem: '#ygbirth',
	theme: '#1ab394',
	calendar: 'true'
});
//下拉
$('.inps').focus(function() {
	$(this).siblings('.addTree').css('display', 'block');
})

$('.xl').click(function() {
	var xl = $(this).siblings('.addTree');
	if(xl.css('display') == 'block') {
		xl.css('display', 'none')
	} else {
		xl.css('display', 'block')
	}
})
$('.addTree').mouseleave(function() {
	$(this).css('display', 'none')
})

//添加按钮
$('.add').click(function() {
	$('.addModel').css('display', 'block');
	addjs(token); //获取所属角色
	adddep(); //获取所属部门
	addzxz(); //获取坐席组
})
$('.addBtr').click(function() {
	$('.addModel').css('display', 'none');
	Clean();
})

//保存添加按钮
$('.addCun').click(function() {
	if($('.add_ygName').val() == '' || $('.add_ygCode').val() == '' || $('.add_pwd').val() == '' || $('.inps1').val() == '' || $('.inps2').val() == '') {
		layer.confirm('标红内容不允许为空！', {
			btn: ['确定']
		});
		return;
	} else if($('.add_pwd').val() !== $('.add_pwd2').val()) {
		layer.confirm('密码输入不一致！', {
			btn: ['确定']
		});
		return;
	} else {
		addCun(did, jsid, zxid)

	}
})
//保存所调方法
function addCun(did, jsid, zxid) {
	$.ajax({
		type: "post",
		url: huayi.config.callcenter_url + "UserAccount/AddUsers",
		async: true,
		dataType: 'json',
		data: {
			token: $.cookie("token"),
			usercode: $('.add_ygCode').val(),
			username: $('.add_ygName').val(),
			password: $('.add_pwd').val(),
			extno: $('.add_fenji').val(),
			//wxno:$('.add_wxno').val(),
			deptid: did,
			roleid: jsid,
			groupid: zxid, //'组id?'
			isseat: $('.addhwb input[name="huwu"]:checked ').val(),
			searright: $('.addzxqx input[name="zxqx"]:checked ').val(),
			sex: $('.addSex input[name="sex"]:checked ').val(),
			mobile: $('.add_mobile').val(),
			telphone: $('.add_telphone').val(),
			birth: $('.add_birth').val(),
			hjtype: $('.add_zxlx input[name="zxqx"]:checked ').val(),
			remark: $('.add_remark').val()
		},
		success: function(data) {
			if(data.state.toLowerCase() == "success") {
				$('.addModel').css('display', 'none');
				layer.msg("添加成功！");
				table.bootstrapTable('refresh');
				Clean();
			}
		}

	});
}
//清除表格
function Clean() {
	$('.add_ygCode').val('');
	$('.add_ygName').val('');
	$('.add_pwd').val('');
	$('.add_pwd2').val('');
	$('.add_fenji').val('');
	$('.inps1').val('');
	$('.inps2').val('');
	$('.inps3').val('');
	$('.addhwb input[name="huwu"]').removeAttr('checked');
	$('.addzxqx input[name="zxqx"]').removeAttr('checked');
	$('.addSex input[name="sex"]').removeAttr('checked');
	$('.add_mobile').val('');
	$('.add_telphone').val('');
	$('.add_birth').val('');
	$('.add_zxlx input[name="zxqx"]').removeAttr('checked');
	$('.add_remark').val('');
}
//所属角色列表
var jsid; //角色id
$('.xlAdd_one ul').on('click', 'li', function() {
	$('.inps1').val($(this).html());
	jsid = $(this).attr('data-id');
	console.log(jsid);
	//		$(this).addClass('fouceli').siblings().removeClass('fouceli');
	$(this).parent().parent().css('display', 'none');
})

//获取角色列表 
function addjs(token) {
	$('.xlAdd_one ul').html('');

	$.ajax({
		type: "get",
		url: huayi.config.callcenter_url + "RoleInfo/GetRoleList",
		async: true,
		dataType: 'json',
		data: {
			token: token,
			code: '',
			name: ''
		},
		success: function(data) {
			var con = data.rows;
			//				console.log(con);
			for(var i = 0; i < con.length; i++) {
				$('<li data-id=' + con[i].F_RoleId + '>' + con[i].F_RoleName + '</li>').appendTo('.xlAdd_one ul');
			}
		}
	});
}
//获取所属部门
var setting2 = {
	data: {
		key: {
			name: "text"
		},
		simpleData: {
			enable: true,
			idKey: "id",
			rootPId: 0
		}
	},
	callback: {
		onClick: ztreeDep
	}
};
var did; //部门id
var dname; //部门name
function ztreeDep(event, treeId, treeNode) {
	did = treeNode.id;
	dname = treeNode.text;
	$('.inps2').val(dname);
};

function adddep() {
	$.get(huayi.config.callcenter_url + "Department/GetDeptList", {
		"token": $.cookie("token"),
		"pid": pid
	}, function(result) {
		result = $.parseJSON(result);
		$.fn.zTree.init($("#xlAdd_depTree"), setting2, result.data); //实例化树形图
	});
}
//获取坐席组列表
var setting3 = {
	data: {
		key: {
			name: "F_ZXZName"
		},
		simpleData: {
			enable: true,
			idKey: "F_ZXZID",
			rootPId: 0
		}
	},
	callback: {
		onClick: ztreeZxz
	}
};
var zxid; //坐席组id
var zxname; //坐席组name
function ztreeZxz(event, treeId, treeNode) {
	zxid = treeNode.F_ZXZID;
	zxname = treeNode.F_ZXZName;
	$('.inps3').val(zxname);
};

function addzxz() {
	$.get(huayi.config.callcenter_url + "SeatGroup/GetSeatList?", {
		"token": $.cookie("token")
	}, function(result) {
		result = $.parseJSON(result);
		$.fn.zTree.init($("#xlAdd_zxz"), setting3, result.data); //实例化树形图
	});
}

//***********************添加功能结束=============================

//=======================修改功能开始==============================
//用户生日
laydate.render({
	elem: '#chan_ygbirth',
	theme: '#1ab394',
	calendar: 'true'
});
//		var chan_uc;
$('.change').click(function() {
	chanjs(token); //角色列表
	chanGetDep(); //部门列表
	chanGetzx(); //获取坐席
	console.log("用户工号" + chan_uc + "用户编号" + ygbh)
	if(ygbh) {
		$('.changeModel').css('display', 'block');
		getYG(chan_uc, ygbh);

	} else {
		layer.confirm('请选择要修改的行！', {
			btn: ['确定']
		});
		return;
	}

})
//删除
$('.move').click(function() {
	if(ygbh) {
		move(chan_uc);

	} else {
		layer.confirm('请选择要删除的行！', {
			btn: ['确定']
		});
		return;
	}
})

function move(chan_uc) {
	$.ajax({
		type: "post",
		url: huayi.config.callcenter_url + "UserAccount/DeleteUsers",
		async: true,
		dataType: 'json',
		data: {
			token: token,
			ids: chan_uc,
		},
		success: function(data) {
			if(data.state.toLowerCase() == "success") {
				layer.msg("删除成功！");
				initTable(token, id, keyWord);
			}
		}
	});
}
//所属角色列表
var chan_jsid; //角色id
$('.xlChan_four ul').on('click', 'li', function() {
	$('.inps4').val($(this).html());
	chan_jsid = $(this).attr('data-id');
	console.log(chan_jsid);
	//		$(this).addClass('fouceli').siblings().removeClass('fouceli');
	$(this).parent().parent().css('display', 'none');
})
//获取角色列表 
function chanjs(token) {
	$('.xlChan_four ul').html('');
	$.ajax({
		type: "get",
		url: huayi.config.callcenter_url + "RoleInfo/GetRoleList",
		async: true,
		dataType: 'json',
		data: {
			token: token,
			code: '',
			name: ''
		},
		success: function(data) {
			var con = data.rows;
			//				console.log(con);
			for(var i = 0; i < con.length; i++) {
				$('<li data-id=' + con[i].F_RoleId + '>' + con[i].F_RoleName + '</li>').appendTo('.xlChan_four ul');
			}
		}
	});
}
//获取所属部门
var setting4 = {
	data: {
		key: {
			name: "text"
		},
		simpleData: {
			enable: true,
			idKey: "id",
			rootPId: 0
		}
	},
	callback: {
		onClick: chanaDep
	}
};
var chanDid; //部门id
var chanDname; //部门name
function chanaDep(event, treeId, treeNode) {
	chanDid = treeNode.id;
	chanDname = treeNode.text;
	$('.inps5').val(chanDname);
};

function chanGetDep() {
	$.get(huayi.config.callcenter_url + "Department/GetDeptList", {
		"token": $.cookie("token"),
		"pid": pid
	}, function(result) {
		result = $.parseJSON(result);
		$.fn.zTree.init($("#xlChan_depTree"), setting4, result.data); //实例化树形图
	});
}
//获取坐席组列表
var setting5 = {
	data: {
		key: {
			name: "F_ZXZName"
		},
		simpleData: {
			enable: true,
			idKey: "F_ZXZID",
			rootPId: 0
		}
	},
	callback: {
		onClick: chanZxz
	}
};
var chanZxid; //坐席组id
var chanZxname; //坐席组name
function chanZxz(event, treeId, treeNode) {
	chanZxid = treeNode.F_ZXZID;
	chanZxname = treeNode.F_ZXZName;
	$('.inps6').val(chanZxname);
};

function chanGetzx() {
	$.get(huayi.config.callcenter_url + "SeatGroup/GetSeatList?flag=ZXZ", {
		"token": $.cookie("token")
	}, function(result) {
		result = $.parseJSON(result);
		$.fn.zTree.init($("#xlchan_zxz"), setting5, result.data); //实例化树形图
	});
}
//获取用户信息
function getYG(chan_uc, ygbh) {
	$.ajax({
		type: "get",
		url: huayi.config.callcenter_url + "UserAccount/GetUser",
		async: true,
		dataType: 'json',
		data: {
			token: token,
			usercode: ygbh,
			userid: chan_uc
		},
		success: function(data) {
			if(data.state.toLowerCase() == "success") {
				var ygcon = data.data;
				console.log(ygcon.F_ExtensionNumber);
				$('.change_ygName').val(ygcon.F_UserName); //员工姓名
				$('.change_ygCode').val(ygcon.F_WorkNumber); //员工工号
				$('.xlChan_four ul li').each(function(i, n) {
					if($(n).attr("data-id") == ygcon.F_RoleId) {
						$('.inps4').val($(n).text()); //所属角色
						var idd = ygcon.F_RoleId;
						$('.inps4').attr('data_id', idd);
					}
				})
				$('.inps5').val(ygcon.depname); //所属部门
				$('.inps5').attr('data_id', ygcon.F_DeptId);
				$('.change_hwb input[name="huwu"][value="' + ygcon.F_SeatFlag + '"]').prop("checked", "checked"); //话务标志
				$('.change_zxqx input[name="zxqx"][value="' + ygcon.F_SeatRight + '"]').prop("checked", "checked"); //坐席权限
				$('.change_zxlx input[name="call"][value="' + ygcon.F_HJType + '"]').prop("checked", "checked"); //坐席类型
				$('.changeSex input[name="sex"][value="' + ygcon.F_SexFlag + '"]').prop("checked", "checked"); //性别
				$('.inps6').val(ygcon.F_SeatGroup); //坐席组
				$('.inps6').attr('data_id', ygcon.F_GroupId);
				$('.change_fenji').val(ygcon.F_ExtensionNumber); //分机号
				//$('.change_wxno').val(ygcon.F_WXNo);//外呼显示号码
				$('#chan_ygbirth').val(ygcon.F_Birthday); //生日
				$('.change_telphone').val(ygcon.F_Telephone); //电话
				$('.change_mobile').val(ygcon.F_Mobile); //手机
				$('.change_remark').val(ygcon.F_Remark); //备注
			}
		}

	});
}
//关闭按钮
$('.changeBtr').click(function() {
	$('.changeModel').css('display', 'none');
})
chan_jsid = $('.inps4').attr('data_id'); //角色ID
chanDid = $('.inps5').attr('data_id'); //部门id
chanZxid = $('.inps6').attr('data_id'); //坐席组id
//保存按钮
$('.changeCun').click(function() {
	chan_tj(token, chanDid, chan_jsid, chan_uc, pwd, ygbh, chanZxid);

})

function chan_tj(token, chanDid, chan_jsid, chan_uc, pwd, ygbh, chanZxid) {
	$.ajax({
		type: "post",
		url: huayi.config.callcenter_url + "UserAccount/EditUsers",
		async: true,
		dataType: 'json',
		data: {
			token: token,
			userid: chan_uc,
			usercode: $('.change_ygCode').val(),
			username: $('.change_ygName').val(),
			password: pwd,
			extno: $('.change_fenji').val(),
			//wxno:$('.change_wxno').val(),
			worknumber: ygbh,
			deptid: chanDid,
			roleid: chan_jsid,
			groupid: chanZxid,
			isseat: $('.change_hwb input[name="huwu"]:checked ').val(),
			searright: $('.change_zxqx input[name="zxqx"]:checked ').val(),
			sex: $('.changeSex input[name="sex"]:checked ').val(),
			mobile: $('.change_mobile').val(),
			telphone: $('.change_telphone').val(),
			birth: $('#chan_ygbirth').val(),
			hjtype: $('.change_zxlx input[name="call"]:checked ').val(),
			remark: $('.change_remark').val()
		},
		success: function(data) {
			if(data.state.toLowerCase() == "success") {
				$('.changeModel').css('display', 'none');
				layer.msg("修改成功！");
				initTable(token, id, keyWord);
			}
		}
	});
}

//***********************修改功能结束==============================

//=======================重设功能开始==============================
$('.again').click(function() {
	if(ygbh) {
		$('.againModel').css('display', 'block');
		$('.again_ygName').val(yhname)
		$('.again_ygCode').val(yhgh)
	} else {
		layer.confirm('请选择要重设密码的用户！', {
			btn: ['确定']
		});
		return;
	}

})
//关闭按钮
$('.agBtr').click(function() {
	$('.againModel').css('display', 'none');
})
//确定按钮
$('.again_Cun').click(function() {
	if($('.again_pwd').val() !== $('.again_pwd2').val()) {
		layer.confirm('密码不一致，请重新输入！', {
			btn: ['确定']
		});
		return;
		//			$('.again_pwd').val('');
		$('.again_pwd2').val('');
	} else {
		$('.againModel').css('display', 'none');
		cs(ygbh); //重设密码
	}

})

function cs(ygbh) {
	$.ajax({
		type: "post",
		url: huayi.config.callcenter_url + "UserAccount/ResetPwd",
		async: true,
		dataType: 'json',
		data: {
			token: token,
			usercode: ygbh,
			pwd: $('.again_pwd').val()
		},
		success: function(data) {
			if(data.state.toLowerCase() == "success") {
				layer.msg("重设密码成功！");
				initTable(token, id, keyWord);
			}
		}
	});
}
//***********************重设功能结束==============================
var state;
//=======================禁用功能开始==============================
$('.ban').click(function() {
	if(buMenId) {
		$('.banModel').css('display', 'block');
	} else {
		layer.confirm('请选择行！', {
			btn: ['确定']
		});
		return;
	}
})
//关闭按钮
$('.banBtr').click(function() {
	$('.banModel').css('display', 'none');
})
//取消按钮
$('.banReturn').click(function() {
	$('.banModel').css('display', 'none');
})

//确定按钮
$('.banSure').click(function() {
	$('.banModel').css('display', 'none');
	state = 1;
	console.log(state);
	bu(chan_uc, state);

})

function bu(chan_uc, state) {
	$.ajax({
		type: "post",
		url: huayi.config.callcenter_url + "UserAccount/DelUsers",
		async: true,
		dataType: 'json',
		data: {
			token: token,
			ids: chan_uc,
			state: state
		},
		success: function(data) {
			if(data.state.toLowerCase() == "success") {
				initTable(token, id, keyWord);
			}
		}
	});
}
//***********************禁用功能结束==============================

//=======================启用功能开始==============================
$('.using').click(function() {
	if(buMenId) {
		$('.useModel').css('display', 'block');
	} else {
		layer.confirm('请选择行！', {
			btn: ['确定']
		});
		return;

	}
})
//关闭按钮
$('.useBtr').click(function() {
	$('.useModel').css('display', 'none');
})
//取消按钮
$('.useReturn').click(function() {
	$('.useModel').css('display', 'none');
})
//确定按钮
$('.useSure').click(function() {
	state = 0;
	console.log(state);
	$('.useModel').css('display', 'none');
	bu(chan_uc, state);
})
//***********************启用功能结束==============================

//右边表格
initTable(token, id, keyWord);

function initTable(token, id, keyWord) {
	//先销毁表格
	table.bootstrapTable('destroy');
	//初始化表格,动态从服务器加载数据
	table.bootstrapTable({
		method: "get", //使用get请求到服务器获取数据
		url: huayi.config.callcenter_url + "UserAccount/GetList", //获取数据的Servlet地址
		contentType: 'application/x-www-form-urlencoded',
		striped: true, //表格显示条纹
		pagination: true, //启动分页
		pageSize: 10, //每页显示的记录数
		pageNumber: 1, //当前第几页
		pageList: [10, 15, 20, 30, 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 = {
				pageindex: params.pageNumber,
				pagesize: params.pageSize,
				token: token,
				dptid: id,
				key: keyWord
			};
			return param;
		},
		onLoadSuccess: function() { //加载成功时执行
			//layer.msg("加载成功");
		},
		onLoadError: function() { //加载失败时执行
			//layer.msg("加载数据失败", { time: 1500, icon: 2 });
		}
	});
}
/*选中行添加背景颜色*/
var ygbh, chan_uc, pwd, buMenId, yhname, yhgh;
table.on("click-row.bs.table", function(e, row, ele) {
	$('.success').removeClass('success'); //去除之前选中的行的，选中样式
	$(ele).addClass('success'); //添加当前选中的 success样式用于区别
	ygbh = row.F_UserCode; //用户编号
	chan_uc = row.F_UserId; //用户id
	pwd = row.F_Password; //密码
	buMenId = row.F_DeptId; //部门id
	yhname = row.F_UserName; //用户name
	yhgh = row.F_WorkNumber; //用户工号
	//				alert(chan_uc)

});

function setCode(val, row, index) {
	var page = table.bootstrapTable("getPageCode");
	return page.pageSize * (page.pageNumber - 1) + index + 1;
}

function setZuoType(val) {
	var str = '';
	switch(val + '') {
		case '0':
			str = "呼入组";
			break;
		case '1':
			str = "呼出组";
			break;
	}
	return str;
}

function setYongState(val) {
	var str = '';
	switch(val + '') {
		case '0':
			str = "正常";
			break;
		case '1':
			str = "禁用";
			break;
	}
	return str;
}