var m_DeptId = "";//记录当前操作的部门ID
var m_PersonId = "";//记录当前操作的人员ID
var m_AuthCache = [];//授权组数据缓存
var m_ResultJson = {};//部门人员缓存
var m_selectlisti = "";//选中人员下标
var m_BoolShowAddQRCodeForm;    //  是否需要显示添加二维码的winform窗体
var m_BoolDeletePerson = false;       //  是否触发删除人员操作
var m_BoolUnbind = false;
var m_MyAuth;//本人权限，-1是管理员权限
var m_SelectedAuth;//选中人的权限
var m_frist = 1;//初次加载为1
var m_isGroupSubmit = true;//判断部门顺序是否提交过,提交过true，没提交过false
$(function () {
	//页面输入格式
	$("#myPageAlert").hide();
	$("#txtPersonMobile").keyup(function () {
		this.value = this.value.replace(/[^\d]/g, '');
	});
	m_MyAuth = manageObj.getauthid();//本人权限
	manageObj.getdepartmenttreelist();//获取部门树形列表
	manageObj.getauthlist();//权限组获取
});

//绑定授权列表回调方法
function AsyncGetAuthListResult(jsonResult) {
	var objselectAuth = $("#selectAuth");
	objselectAuth.empty();//清空
	var LoginPersonAutnList = m_ResultJson.result.list;//当前登录人员拥有权限的部门
	if (jsonResult.success) {
		m_AuthCache = jsonResult.result.list;
		if (m_MyAuth != -1) {
			for (var i = 0; i < m_AuthCache.length; i++) {
				if (ShowDeptAuth(m_AuthCache[i], LoginPersonAutnList)) {
					objselectAuth.append("<option value='" + m_AuthCache[i].agid + "'>" + m_AuthCache[i].agname + "</option>");
				}
			}
		} else {
			for (var k = 0; k < m_AuthCache.length; k++) {
				objselectAuth.append("<option value='" + m_AuthCache[k].agid + "'>" + m_AuthCache[k].agname + "</option>");
			}
		}
	} else {
		ShowError("myPageAlert", "获取权限列表异常：" + jsonResult.error);
	}
}
//筛选部门权限显示 返回bool(本人非管理员权限执行的方法)
function ShowDeptAuth(jsonAuths, LoginPersonAutnList) {
    var BisShow = true;
    if (jsonAuths.agname == "管理员") {
        return false;
    }
	var JsonOneAuthDept = JSON.parse(jsonAuths.grantval);//当前权限所包含的部门ID
    if (LoginPersonAutnList.length >= JsonOneAuthDept.length) {
        var strThisAuth = "";
        for (var j = 0; j < LoginPersonAutnList.length; j++) {
        	strThisAuth += LoginPersonAutnList[j].dgid;
        }
        for (var i = 0; i < JsonOneAuthDept.length; i++) {
        	if (strThisAuth.indexOf(JsonOneAuthDept[i]) == -1) {
            	BisShow = false;
            }
        }
    }
    else {
    	BisShow = false;
    }
    return BisShow;
}

//获取部门列表回调方法
function AsyncGetDepartmentTreeListResult(jsonResult) {
	$("#selectPersonDept").empty();//清空
	if (jsonResult.success) {
		m_ResultJson = jsonResult;
		CommonErgodic();
	} else {
		ShowError("myPageAlert", "操作失败：" + jsonResult.error);
	}
	$(".loadingcover").hide();
	$(".loading").hide();
	PageLoadTrees();
}

//选中部门时
function SetEditDeptBind(value, name, listi) {
	m_selectlisti = listi;
	m_DeptId = value;//部门ID
	if (m_DeptId.length > 0) {
		$("#BtnDeptDelete").show();
	} else {
		$("#BtnDeptDelete").hide();
	}
	$("#txtDeptName").val(name);
	$("#txtDeptName").focus();
	$("#spDeleteDeptName").html(name);
	$("#divEditDept").removeClass("tab-pane fade").addClass("tab-pane fade active in");//显示
	$("#divEditPerson").removeClass("tab-pane fade active in").addClass("tab-pane fade");//隐藏
	$("#liCreateDept").removeClass("active");
	$("#liCreatePerson").removeClass("active");
}

//添加、修改部门
function EditDept() {
	var objtxtDeptName = $("#txtDeptName");
	objtxtDeptName.val($.trim(Canceller(objtxtDeptName.val())));
	if (objtxtDeptName.val().length == 0) {
		ShowError("myPageAlert", "部门名称不能为空！");
		objtxtDeptName.focus();
		return;
	}
	for (var i = 0; i < m_ResultJson.result.list.length; i++) {
		if (m_ResultJson.result.list[i].dgname == objtxtDeptName.val()) {
			ShowMsg("myPageAlert", "该部门已存在！");
			return;
		}
	}
	
	$(".loading").show();
	$(".loadingcover").show();
	if (m_DeptId.length == 0) {
	    var number = 10001;
	    if (m_ResultJson.result.list.length > 0) {
	        //添加
	        var number = m_isGroupSubmit ? Number(m_ResultJson.result.list[m_ResultJson.result.list.length - 1].sort) + 1 : "";
	    }
		var strParaJson = $.toJSON({
			deptname: objtxtDeptName.val(),
			sort: number
		});
		manageObj.creatdepartment(strParaJson);
	}
	else {
		//修改
		var strParaJson = $.toJSON({
			deptid: m_DeptId, deptname: objtxtDeptName.val()
		});
		manageObj.updatedepartment(strParaJson);
	}
}

//调整部门信息回调方法
function AsyncUpdateDepartmentResult(jsonResult) {
	if (jsonResult.success) {
		$("#DeleteDeptModal").modal("hide");
		$("#divEditDept").removeClass("tab-pane fade active in").addClass("tab-pane fade");//隐藏
		ShowMsg("myPageAlert", "操作成功！");
		manageObj.getdepartmenttreelist();//获取部门树形列表
	}
	else {
		//错误信息
		ShowError("myPageAlert", "操作失败：" + jsonResult.error);
	}
}

//添加部门信息回调方法
function AsyncCreatDepartmentResult(jsonResult) {
	if (jsonResult.success) {
		$("#DeleteDeptModal").modal("hide");
		$("#divEditDept").removeClass("tab-pane fade active in").addClass("tab-pane fade");//隐藏
		ShowMsg("myPageAlert", "操作成功！");
		manageObj.getdepartmenttreelist();//获取部门树形列表
	}
	else {
		//错误信息
		ShowError("myPageAlert", "操作失败：" + jsonResult.error);
	}
}
//显示删除部门对话框
function ShowDeleteDept() {
	if (m_DeptId.length == 0) {
		return;
	}
	if (m_ResultJson.result.list[m_selectlisti].users.length > 0) {
		ShowError("myPageAlert", "此部门下有人员，不能进行删除操作！");
		return;
	} else {
		$("#DeleteDeptModal").modal("show");
	}
}

//提交删除部门
function CommitDeptDelete() {
	$(".loading").show();
	$(".loadingcover").show();
	var strParaJson = $.toJSON({
		deptid: m_DeptId,
	});
	manageObj.deletedepartment(strParaJson);
}


//调整部门信息回调方法
function updatedepartment(jsonResult) {
	if (jsonResult.success) {
		$("#DeleteDeptModal").modal("hide");
		$("#divEditDept").removeClass("tab-pane fade active in").addClass("tab-pane fade");//隐藏
		ShowMsg("myPageAlert", "操作成功！");
		manageObj.getdepartmenttreelist();//获取部门树形列表
	}
	else {
		//错误信息
		ShowError("myPageAlert", "操作失败：" + jsonResult.error);
	}
}

function AsyncDeleteDepartmentResult(jsonResult) {
	if (jsonResult.success) {
		$("#DeleteDeptModal").modal("hide");
		$("#divEditDept").removeClass("tab-pane fade active in").addClass("tab-pane fade");//隐藏
		ShowMsg("myPageAlert", "操作成功！");
		manageObj.getdepartmenttreelist();//获取部门树形列表
	}
	else {
		//错误信息
		ShowError("myPageAlert", "操作失败：" + jsonResult.error);
	}
}

//选中人员时
function SetEditPersonBind(value) {
	m_PersonId = value;//人员ID
	$("#txtPersonMobile").attr("readonly", $.trim(value) != "");
	if (value.length > 0) {
		for (var i = 0; i < m_ResultJson.result.list.length; i++) {
			for (var j = 0; j < m_ResultJson.result.list[i].users.length; j++) {
				var item = m_ResultJson.result.list[i].users[j];
				if (item.uid == value) {
					$("#txtHeadUrl").val(item.headimgurl);
					if (item.headimgurl.length > 0) {
						$("#imgHead").attr("src", item.headimgurl);
					} else {
						$("#imgHead").attr("src", "../img/kefutouxiang.png");
					}
					$("#spDeletePersonName").html(item.name);
					$("#txtPersonName").val(item.name);
					$("#txtPersonMobile").val(item.mobile);

					$("#selectPersonDept").val(item.deptid);
					$("#btnupdate").show();
					$("#btndelete").show();
					$("#divEditDept").removeClass("tab-pane fade active in").addClass("tab-pane fade");//隐藏
					$("#divEditPerson").removeClass("tab-pane fade").addClass("tab-pane fade active in");//显示
					//$("#CreatTime").val(item.createtime);
					if (item.authid == "0") {
						$("#selectAuth").empty();//清空
						$("#selectAuth").append("<option value='0'>超级管理员</option>");
					} else if (item.authid == "-1") {
						$("#selectAuth").empty();//清空
						$("#selectAuth").append("<option value='-1'>超级管理员</option>");
					} else {
						$("#selectAuth").empty();//清空
						var LoginPersonAutnList = m_ResultJson.result.list;//当前登录人员拥有权限的部门

						if (m_MyAuth != -1) {
							for (var k = 0; k < m_AuthCache.length; k++) {
								if (ShowDeptAuth(m_AuthCache[k], LoginPersonAutnList)) {
									$("#selectAuth").append("<option value='" + m_AuthCache[k].agid + "'>" + m_AuthCache[k].agname + "</option>");
								}
								else if (item.authid == m_AuthCache[k].agid) {
									$("#selectAuth").append("<option value='" + m_AuthCache[k].agid + "'>" + m_AuthCache[k].agname + "</option>");
								}
							}
						} else {
							for (var l = 0; l < m_AuthCache.length; l++) {
								$("#selectAuth").append("<option value='" + m_AuthCache[l].agid + "'>" + m_AuthCache[l].agname + "</option>");
							}
						}
					}
					$("#selectAuth").val(item.authid);
				}
			}
		}
	} else {
		$("#selectAuth").empty();
		$("#txtPersonName").val("");
		$('#selectPersonDept option:eq(0)').attr('selected', 'selected');
		$("#txtPersonMobile").val("");

		$("#imgHead").attr("src", "../../img/home/header.png");
		$("#txtHeadUrl").val("");
		$("#btnupdate").hide();
		$("#btndelete").hide();
		$("#divEditDept").removeClass("tab-pane fade active in").addClass("tab-pane fade");//隐藏
		$("#divEditPerson").removeClass("tab-pane fade").addClass("tab-pane fade active in");//显示
		$("#selectAuth").empty();
		var LoginPersonAutnList = m_ResultJson.result.list;//当前登录人员拥有权限的部门
		
		if (m_MyAuth != -1) {
			for (var j = 0; j < m_AuthCache.length; j++) {
				if (ShowDeptAuth(m_AuthCache[j], LoginPersonAutnList)) {
					$("#selectAuth").append("<option value='" + m_AuthCache[j].agid + "'>" + m_AuthCache[j].agname + "</option>");
				}
			}
		} else {
			for (var m = 0; m < m_AuthCache.length; m++) {
				$("#selectAuth").append("<option value='" + m_AuthCache[m].agid + "'>" + m_AuthCache[m].agname + "</option>");
			}
		}
		
	}
	//得到选中人员的权限
	m_SelectedAuth = $("#selectAuth").find("option:selected").text();
}

//提交人员添加、修改操作
function EditPerson() {
	//var objtxtHeadImg = $("#txtHeadUrl");
	var objtxtPersonName = $("#txtPersonName");
	var objselectPersonDept = $("#selectPersonDept");
	var objtxtPersonMobile = $("#txtPersonMobile");
	var objselectAuth = $("#selectAuth");
	objtxtPersonName.val($.trim(Canceller(objtxtPersonName.val())));
	objselectPersonDept.val($.trim(Canceller(objselectPersonDept.val())));
	objtxtPersonMobile.val($.trim(Canceller(objtxtPersonMobile.val())));
	objselectAuth.val($.trim(Canceller(objselectAuth.val())));
	//objtxtHeadImg.val($.trim(Canceller(objtxtHeadImg.val())));

	//本人不是管理员但要将权限提升到管理员权限（提升权限时）
	if (m_MyAuth != "-1" && objselectAuth.find("option:selected").text() == "管理员") {
		ShowError("myPageAlert", "权限不足!您不是管理员权限，不能进行此操作。");
		return;
	}

	if (objtxtPersonName.val().length == 0) {
		ShowError("myPageAlert", "姓名不能为空！");
		objtxtPersonName.focus();
		return;
	}
	//if (objtxtPersonName.val() == "网站商务通") {
	//    ShowError("myPageAlert", "姓名不能为网站商务通！");
	//    objtxtPersonName.focus();
	//    return;
	//}
	if (objselectPersonDept.val().length < 1) {
		ShowError("myPageAlert", "请选择部门，若没有部门请先创建部门！");
		return;
	}

	if (objtxtPersonMobile.val().length == 0) {
		ShowError("myPageAlert", "手机号码不能为空！");
		objtxtPersonMobile.focus();
		return;
	}


	if (!(/^1(3|4|5|6|7|8|9)\d{9}$/.test(objtxtPersonMobile.val()))) {
		ShowError("myPageAlert", "手机号码格式不正确！");
		objtxtPersonMobile.val("");
		objtxtPersonMobile.focus();
		return;
	}
	if (objselectAuth.val() == "" || objselectAuth.val() == null) {
		ShowError("myPageAlert", "请选择权限！若没有权限组，请先创建权限组！");
		objselectAuth.focus();
		return;
	}

	var jsonResult;
	var number = "";//当前组内标签的sort值
	for (var i = 0; i < m_ResultJson.result.list.length; i++) {
		if (m_ResultJson.result.list[i].dgid == objselectPersonDept) {
			for (var j = 0; j < m_ResultJson.result.list[i].users.length; j++) {
			    if (m_JsonResult.result.list[i].users[j].sort != "" && m_ResultJson.result.list[i].users[j].sort != undefined && m_ResultJson.result.list[i].users[j].sort != null) {
					number = Number(m_ResultJson.result.list[i].users[m_ResultJson.result.list[i].users.length - 1].sort) + 1;
					break;
				}
			}
			break;
		}

	}
	if (m_PersonId.length == 0) {
		// 检查客服名称是否已经存在
		var userlist = m_ResultJson.result.list;
		if (userlist) {
			for (var index in userlist) {
				var inusers = userlist[index].users;
				for (var i in inusers) {
					var name = inusers[i].name;
					if (name == objtxtPersonName.val()) {
						ShowError("myPageAlert", "该姓名已存在！");
						objtxtPersonName.focus();
						return;
					}
				}
			}
		}

		//添加
		var strParaJson = $.toJSON({
			headimgurl: "",
			name: objtxtPersonName.val(),
			mobile: objtxtPersonMobile.val(),
			authid: objselectAuth.val(),
			deptid: objselectPersonDept.val(),
			sort: number
		});
		manageObj.adduser(strParaJson);
	}
	else {
		var struserid = "";
		var strauth = "";
		var num = 0;
		for (var i = 0; i < m_AuthCache.length; i++) {
			if (m_AuthCache[i].val == -1) {
				strauth = m_AuthCache[i].agid;
			}
		}
		if (strauth != objselectAuth.val()) {// 修改成非管理员权限的情况
			var isContain = false;
			for (var j = 0; j < m_ResultJson.result.list.length; j++) {
				var deptlist = m_ResultJson.result.list[j]
				for (var k = 0; k < deptlist.users.length; k++) {
					if (deptlist.users[k].authid == strauth) {
						struserid = deptlist.users[k].uid;
						if (struserid == m_PersonId) {
							isContain = true;
						}
						num++;
						if (num >= 2) {
							break;
						}
					}
				}
				if (num >= 2) {
					break;
				}
			}
			if (num < 2 && isContain) {
				ShowError("myPageAlert", "此为最后一个拥有管理员权限的人员，不允许修改为非管理员权限！");
				return;
			}
		}

		//本人不是管理员要操作管理员人员的情况下(降低权限和增删改时)(创建成员时不进行判断)
		if (m_MyAuth != "-1" && m_SelectedAuth == "管理员") {
			ShowError("myPageAlert", "权限不足!您不是管理员权限，不能进行此操作。!");
			return;
		}
		//修改
		var strParaJson = $.toJSON({
			uid: m_PersonId,
			headimgurl: "",
			name: objtxtPersonName.val(),
			mobile: objtxtPersonMobile.val(),
			authid: objselectAuth.val(),
			deptid: objselectPersonDept.val(),
			sort: number
		});
		manageObj.updateusermessage(strParaJson);
	}
}

//添加人员
function AsyncAddUserResult(jsonResult) {
	if (jsonResult.success) {
		$("#PersonPwdModal").modal("hide");
		$("#DeletePersonModal").modal("hide");
		$("#divEditPerson").removeClass("tab-pane fade active in").addClass("tab-pane fade");//隐藏面板
		//显示新创建人员密码
		$("#PAddUserReltPWD").html(jsonResult.pwd);
		$("#DIVAddUserReltPWDModel").modal("show");

		ShowMsg("myPageAlert", "操作成功！");
		manageObj.getdepartmenttreelist();//获取部门树形列表
	}
	else {
		if (jsonResult.error == "mobile error!") {
			ShowError("myPageAlert", "操作失败：该手机号码已被注册！");
		} else {
			ShowError("myPageAlert", "操作失败：" + jsonResult.error);
		}


	}
}
//
//调整人员信息回调方法
function AsyncUpdateUserMessageResult(jsonResult) {
	if (jsonResult.success) {
		$("#PersonPwdModal").modal("hide");
		$("#DeletePersonModal").modal("hide");
		$("#divEditPerson").removeClass("tab-pane fade active in").addClass("tab-pane fade");//隐藏面板
		ShowMsg("myPageAlert", "操作成功！");
		manageObj.getdepartmenttreelist();//获取部门树形列表
	}
	else {
		ShowError("myPageAlert", "操作失败：" + jsonResult.error);
	}
}

//显示删除人员
function ShowDeletePerson() {
	//本人不是管理员要操作管理员人员的情况下（不拦截将权限改成管理员）
	if (m_MyAuth != "-1" && m_SelectedAuth == "管理员") {
		ShowError("myPageAlert", "权限不足!您不是管理员权限，不能进行此操作。!");
		return;
	}
	var struserid = "";
	var strauth = "";
	var num = 0;
	for (var i = 0; i < m_AuthCache.length; i++) {
		if (m_AuthCache[i].val == -1) {
			strauth = m_AuthCache[i].agid;
		}
	}
	for (var j = 0; j < m_ResultJson.result.list.length; j++) {
		var deptlist = m_ResultJson.result.list[j]
		for (var k = 0; k < deptlist.users.length; k++) {
			if (deptlist.users[k].authid == strauth) {
				struserid = deptlist.users[k].uid;
				num++;
			}
		}

	}
	if (num < 2 && struserid == m_PersonId) {
		ShowError("myPageAlert", "此为最后一个拥有管理员权限的人员，不允许删除！");
		return;
	}
	if (m_PersonId.length == 0) {
		return;
	}
	var strLoginUid = manageObj.getloginmobile();
	if (strLoginUid == m_PersonId) {
		ShowError("myPageAlert", "不允许删除您所登录的帐号！");
		return;
	}
	$("#DeletePersonModal").modal("show");
}

//提交删除人员
function CommitPersonDelete() {
	
	m_BoolDeletePerson = true;
	var mobile = $("#txtPersonMobile").val();
	var strParaJson = $.toJSON({
		uid: m_PersonId,
		mobile: mobile

	});
	manageObj.deleteuser(strParaJson);
}
//删除人员回调
function AsyncDeleteUserResult(jsonResult) {
	if (jsonResult.success) {
		$("#PersonPwdModal").modal("hide");
		$("#DeletePersonModal").modal("hide");
		$("#divEditPerson").removeClass("tab-pane fade active in").addClass("tab-pane fade");//隐藏面板
		ShowMsg("myPageAlert", "操作成功！");
		manageObj.getdepartmenttreelist();//获取部门树形列表
	}
	else {
		ShowError("myPageAlert", "操作失败：" + jsonResult.error);
	}
}


//选择头像
function SelectHeadImg() {
	var strResult = manageObj.uploadheadimg();
	if (strResult.length > 0) {

		$("#txtHeadUrl").val(strResult);
		$("#imgHead").attr("src", strResult);
	}
}
//修改密码
function ShowUpdatePersonPwd() {
	//本人不是管理员要操作管理员人员的情况下（不拦截将权限改成管理员）
	if (m_MyAuth != "-1" && m_SelectedAuth == "管理员") {
		ShowError("myPageAlert", "权限不足!您不是管理员权限，不能进行此操作。");
		return;
	}
	if (m_PersonId.length == 0) {
		return;
	}
	$("#txtPersonPwd1").focus();
	$("#txtPersonPwd1").val("");
	$("#txtPersonPwd2").val("");
	$("#PersonPwdModal").modal("show");
}

//判断是否为一个url
function CheckUrl(str) {
	var RegUrl = new RegExp();
	RegUrl.compile("^[A-Za-z]+://[A-Za-z0-9-_]+\.[A-Za-z0-9-_%&?/.=]+$");
	if (!RegUrl.test(str)) {
		return false;
	}
	return true;
}
//提交人员密码修改
function CommitPersonPwd() {
	var objtxtPersonPwd1 = $("#txtPersonPwd1");
	var objtxtPersonPwd2 = $("#txtPersonPwd2");
	objtxtPersonPwd1.val($.trim(objtxtPersonPwd1.val()));
	objtxtPersonPwd2.val($.trim(objtxtPersonPwd2.val()));
	if (objtxtPersonPwd1.val().length < 6) {
		ShowError("myPageAlert", "新密码必须是6-30位长度的字符！");
		objtxtPersonPwd1.focus();
		return;
	}
	if (objtxtPersonPwd1.val().length == 0) {
		ShowError("myPageAlert", "新密码不能为空！");
		objtxtPersonPwd1.focus();
		return;
	}
	if (objtxtPersonPwd2.val().length == 0) {
		ShowError("myPageAlert", "新密码不能为空！");
		objtxtPersonPwd2.focus();
		return;
	}
	if (objtxtPersonPwd1.val() != objtxtPersonPwd2.val()) {
		ShowError("myPageAlert", "两次输入密码不一致！");
		objtxtPersonPwd1.val("");
		objtxtPersonPwd2.val("");
		objtxtPersonPwd1.focus();
		return;
	}

	var strParaJson = $.toJSON({
		userid: m_PersonId,
		newpwd: objtxtPersonPwd1.val()
	});
	manageObj.updateuserpwdbyid(strParaJson);
}

function AsyncUpdateUserPWDByIdResult(JsonResult) {
	if (JsonResult.success) {
		$("#PersonPwdModal").modal("hide");
		$("#DeletePersonModal").modal("hide");
		$("#divEditPerson").removeClass("tab-pane fade active in").addClass("tab-pane fade");//隐藏面板
		ShowMsg("myPageAlert", "操作成功！");
		$("#PersonPwdModal").modal("hide");
	} else {
		ShowError("myPageAlert", "操作失败：" + jsonResult.error);
	}
}
//人员头像自填 显示
function txtShowHeader() {
	var herderImg = $("#txtHeadUrl");
	$("#imgHead").attr("src", herderImg.val());
}

//树形菜单高度设置
function PageLoadTrees() {
	$(".left-list-l").css({
		height: $(window).height() - 40
	});
	$(".talklist-m").css({
		height: $(window).height() - 100
	});
	$("#right").css({
		height: $(window).height() - 40
	});
	$("#left").css({
		height: $(window).height() - 40
	});

	initTree();
}
$(window).resize(function () {
	PageLoadTrees();
});

//搜索框清空按钮
function resetTag() {
    $(".loadingcover").show();
    $(".loading").show();
	$("#txttag").val("");
	manageObj.getdepartmenttreelist();//获取部门树形列表
}
//公共遍历方法
function CommonErgodic() {
	var strTreeContent = "";//树型菜单内容
	var strDeptCss = "";
	strTreeContent += "<div class=\"input-group\"><input style=\"min-height: 34px;\" id=\"txttag\"  name=\"txttag\" type=\"text\" class=\"form-control input-txt-l\" placeholder=\"人员名称\"><span class=\"input-group-btn\"><button onclick=\"PersonnelQuery()\" class=\"btn btn-default\" type=\"button\" style=\"border-radius:0\"><i class=\"glyphicon glyphicon-search\"></i></button></span><span class=\"input-group-btn\"><button class=\"btn btn-default\"  onclick=\"resetTag()\" type=\"button\"><i class=\"glyphicon glyphicon-trash\"></i></button></span></div>";
	for (var i = 0; i < m_ResultJson.result.list.length; i++) {

		//当前没有字段sort的时候，给默认值，解决老版本兼容问题
	    if (m_ResultJson.result.list[i].sort == undefined || m_ResultJson.result.list[i].sort == "" || m_ResultJson.result.list[i].sort == null) {
			m_isGroupSubmit = false;
		} else {
			m_isGroupSubmit = true;
		}

		if (m_frist == 1) {
			strDeptCss = i == 0 ? "inactive-m inactives-m" : "inactive-m";
		} else {
			strDeptCss = "inactive-m";
		}
		strTreeContent += "<ul class=\"yiji-m\">";
		strTreeContent += "<li>";
		strTreeContent += "<a id=\"group" + i + "\" href=\"#divEditDept\" class=\"" + strDeptCss + "\" data-toggle=\"tab\" onclick=\"SetEditDeptBind('" + m_ResultJson.result.list[i].dgid + "','" + m_ResultJson.result.list[i].dgname + "','" + i + "');\"><span class=\"pull-left\" style=\"width:104px;\">" + m_ResultJson.result.list[i].dgname + "</span>";

		//判断组内标签能否向上向下移动
		if (i != 0 && i != m_ResultJson.result.list.length - 1) {
			//所选分组内既不是第一个，也不是最后一个（分组数大于1个）
		    strTreeContent += "<div class=\"pull-right\"><i class=\"fa fa-angle-up\" style=\"margin-right:5px;\" onclick=\"UserGroupTop(" + i + ")\"></i>";
		    strTreeContent += "<i class=\"fa fa-angle-down\" onclick=\"UserGroupBottom(" + i + ")\"></i></div>";
		} else if (i == 0 && i != m_ResultJson.result.list.length - 1) {
			//所选分组内标签是当前分组的第一个标签是第一个（分组数大于1个）
		    strTreeContent += "<div class=\"pull-right\"><i class=\"fa fa-angle-down\" style=\"margin-top: 10px;\" onclick=\"UserGroupBottom(" + i + ")\"></i></div>";
		} else if (i != 0 && i == m_ResultJson.result.list.length - 1) {
			//所选分组内标签是当前分组内的最后一个标签（分组数大于1个）
		    strTreeContent += "<div class=\"pull-right\"><i class=\"fa fa-angle-up\" style=\"margin-top: 10px;\" onclick=\"UserGroupTop(" + i + ")\"></i></div>";
		} else if (i == 0 && i == m_ResultJson.result.list.length - 1) {
			//所选分组内仅有一个标签
		}

		strTreeContent += "<span class=\"label pull-left badge-color\">" + m_ResultJson.result.list[i].users.length + "</span></a>"

		if (m_frist == 1) {
			if (i == 0) {
				strTreeContent += "<ul id=\"users" + i + "\" style=\"display: block;\">";
			} else {
				strTreeContent += "<ul id=\"users" + i + "\" style=\"display: none;\">";
			}
			m_frist = 2;
		} else {
			strTreeContent += "<ul id=\"users" + i + "\" style=\"display: none;\">";
		}
		for (var j = 0; j < m_ResultJson.result.list[i].users.length; j++) {

			var personItem = m_ResultJson.result.list[i].users[j];
			var imgurl = "";
			if (m_ResultJson.result.list[i].users[j].headimgurl.length > 0) {
				imgurl = m_ResultJson.result.list[i].users[j].headimgurl;
			} else {
				imgurl = "../img/kefutouxiang.png";
			}
			strTreeContent += "<li><a href=\"#divEditPerson\" data-toggle=\"tab\" onclick=\"SetEditPersonBind('" + personItem.uid + "');\"><img src=\'" + imgurl + "\' width=\'25\' height=\"25\"/> " + m_ResultJson.result.list[i].users[j].name;

			////判断组内标签能否向上向下移动
			//if (j != 0 && j != m_ResultJson.result.list[i].users.length - 1) {
			//    //所选分组内既不是第一个，也不是最后一个（分组数大于1个）
			//    strTreeContent += "<span class=\"glyphicon glyphicon-chevron-up pull-right\" style=\"margin-right:5px;\" onclick=\"UserTop(" + i + "," + j + ")\"></span>";
			//    strTreeContent += "<span class=\"glyphicon glyphicon-chevron-down pull-right\" onclick=\"UserBottom(" + i + "," + j + ")\"></span>";
			//} else if (j == 0 && j != m_ResultJson.result.list[i].users.length - 1) {
			//    //所选分组内标签是当前分组的第一个标签是第一个（分组数大于1个）
			//    strTreeContent += "<span class=\"glyphicon glyphicon-chevron-down pull-right\" onclick=\"UserBottom(" + i + "," + j + ")\"></span>";
			//} else if (j != 0 && j == m_ResultJson.result.list[i].users.length - 1) {
			//    //所选分组内标签是当前分组内的最后一个标签（分组数大于1个）
			//    strTreeContent += "<span class=\"glyphicon glyphicon-chevron-up pull-right\" style=\"margin-right:5px;\" onclick=\"UserTop(" + i + "," + j + ")\"></span>";
			//} else if (j == 0 && j == m_ResultJson.result.list[i].users.length - 1) {
			//    //所选分组内仅有一个标签
			//}

			strTreeContent += "</a></li>";
		}
		strTreeContent += "</ul>";
		strTreeContent += "</li>";
		strTreeContent += "</ul>";
		$("#selectPersonDept").append("<option value='" + m_ResultJson.result.list[i].dgid + "'>" + m_ResultJson.result.list[i].dgname + "</option>");
	}
	$("#divTree").html(strTreeContent);
}
//查询人员
function PersonnelQuery() {
	$("#selectPersonDept").empty();//清空
	var replaycondition = $.trim($("#txttag").val().replace(/["]/g, '').replace(/[']/g, ''));
	var strTreeContent = "";//树型菜单内容
	strTreeContent += "<div class=\"input-group\"><input style=\"min-height:34px;\" id=\"txttag\"  name=\"txttag\" type=\"text\"  value=\"" + replaycondition + "\" class=\"form-control input-txt-l\" placeholder=\"人员名称\"><span class=\"input-group-btn\"><button onclick=\"PersonnelQuery()\" class=\"btn btn-default\" type=\"button\" style=\"border-radius:0\"><i class=\"glyphicon glyphicon-search\"></i></button></span><span class=\"input-group-btn\"><button class=\"btn btn-default\"  onclick=\"resetTag()\" type=\"button\"><i class=\"glyphicon glyphicon-trash\"></i></button></span></div>";
	var strDeptCss = "";
	if (replaycondition.length < 1) {
		manageObj.getdepartmenttreelist();
	} else {
		for (var i = 0; i < m_ResultJson.result.list.length; i++) {

			var jsonItem = m_ResultJson.result.list[i];
			var groupname = "";
			if (jsonItem != null) {
				for (var j = 0; j < jsonItem.users.length; j++) {
					if (jsonItem.users[j].name.indexOf(replaycondition) != -1) {
						if (groupname != jsonItem.dename) {
							strTreeContent += "<ul class=\"yiji-m\">";
							strTreeContent += "<li>";
							strTreeContent += "<a href=\"#divEditDept\" class=\"inactive-m\" data-toggle=\"tab\" onclick=\"SetEditDeptBind('" + m_ResultJson.result.list[i].dgid + "','" + m_ResultJson.result.list[i].dgname + "','" + i + "');\">" + m_ResultJson.result.list[i].dgname + "</a>";
							strTreeContent += "<ul style=\"display: none;\">";
							groupname = jsonItem.dename;
						}
						var personItem = jsonItem.users[j];
						var imgurl = "";
						if (jsonItem.users[j].headimgurl.length > 0) {
							imgurl = jsonItem.users[j].headimgurl;
						} else {
							imgurl = "../img/kefutouxiang.png";
						}
						strTreeContent += "<li><a href=\"#divEditPerson\" data-toggle=\"tab\" onclick=\"SetEditPersonBind('" + personItem.uid + "');\"><img src=\'" + imgurl + "\' width=\'25\' height=\"25\"/> " + m_ResultJson.result.list[i].users[j].name + "</a></li>";
					}
				}
			}
			strTreeContent += "</ul>";
			strTreeContent += "</li>";
			strTreeContent += "</ul>";
			$("#selectPersonDept").append("<option value='" + m_ResultJson.result.list[i].dgid + "'>" + m_ResultJson.result.list[i].dgname + "</option>");

		}
	}
	$("#divTree").html(strTreeContent);
	PageLoadTrees();

}
///----------------------分组向上向下移动-------------------start
//向上移动
function UserGroupTop(index) {
    event.cancelBubble = true;//禁止触发父级事件
	$(".loading").show();
	$(".loadingcover").show();
	if (!m_isGroupSubmit) {
		for (var i = 0; i < m_ResultJson.result.list.length; i++) {
			m_ResultJson.result.list[i].sort = 10000 + Number(i) + 1;
		}
	}
	m_ResultJson.result.list[index].sort = Number(m_ResultJson.result.list[index].sort) - 1;
	m_ResultJson.result.list[index - 1].sort = Number(m_ResultJson.result.list[index - 1].sort) + 1;
	var top = m_ResultJson.result.list[index - 1];
	m_ResultJson.result.list[index - 1] = m_ResultJson.result.list[index];
	m_ResultJson.result.list[index] = top;

	var deptlist = [];
	var jObject = {};
	if (m_isGroupSubmit) {
		jObject.id = m_ResultJson.result.list[index - 1].dgid;
		jObject.sort = m_ResultJson.result.list[index - 1].sort;
		deptlist.push(jObject);
		jObject = {};
		jObject.id = m_ResultJson.result.list[index].dgid;
		jObject.sort = m_ResultJson.result.list[index].sort;
		deptlist.push(jObject);
	} else {
		for (var i = 0; i < m_ResultJson.result.list.length; i++) {
			jObject = {};
			jObject.id = m_ResultJson.result.list[i].dgid;
			jObject.sort = m_ResultJson.result.list[i].sort;
			deptlist.push(jObject);
		}
	}
	var json = $.toJSON({
		deptlist: deptlist
	});
	manageObj.changedeptposition(json);
}
//向下移动
function UserGroupBottom(index) {
    event.cancelBubble = true;//禁止触发父级事件
    $(".loading").show();
    $(".loadingcover").show();
	if (!m_isGroupSubmit) {
		for (var i = 0; i < m_ResultJson.result.list.length; i++) {
			m_ResultJson.result.list[i].sort = 10000 + Number(i) + 1;
		}
	}
	m_ResultJson.result.list[index + 1].sort = Number(m_ResultJson.result.list[index + 1].sort) - 1;
	m_ResultJson.result.list[index].sort = Number(m_ResultJson.result.list[index].sort) + 1;
	var bottom = m_ResultJson.result.list[index + 1];
	m_ResultJson.result.list[index + 1] = m_ResultJson.result.list[index];
	m_ResultJson.result.list[index] = bottom;
	var deptlist = [];
	var jObject = {};
	if (m_isGroupSubmit) {
		jObject.id = m_ResultJson.result.list[index].dgid;
		jObject.sort = m_ResultJson.result.list[index].sort;
		deptlist.push(jObject);
		jObject = {};
		jObject.id = m_ResultJson.result.list[index + 1].dgid;
		jObject.sort = m_ResultJson.result.list[index + 1].sort;
		deptlist.push(jObject);
	} else {
		for (var i = 0; i < m_ResultJson.result.list.length; i++) {
			jObject = {};
			jObject.id = m_ResultJson.result.list[i].dgid;
			jObject.sort = m_ResultJson.result.list[i].sort;
			deptlist.push(jObject);
		}
	}
	var json = $.toJSON({
		deptlist: deptlist
	});
	manageObj.changedeptposition(json);
}
//部门上下移动回调
function AsynChangeDeptPositionResult(jsonResult) {
	if (jsonResult.success) {
		ShowMsg("myPageAlert", "操作成功！");
	} else {
	    ShowError("myPageAlert", "操作失败：" + jsonResult.error);
	    $(".loadingcover").hide();
	    $(".loading").hide();
	}
	manageObj.getdepartmenttreelist();//获取部门树形列表
}
///----------------------分组向上向下移动-------------------end

///---------------------分组内标签向上向下移动--------------start
//分组内标签向上移动单击
function UserTop(GroupIndex, TagIndex) {
	//参数：GroupIndex是所选标签组的下标，TagIndex是所选标签的下标
	event.cancelBubble = true;//禁止触发父级事件
	var isUser = true;//判断人员顺序是否提交过,提交过true，没提交过false
	if (m_ResultJson.result.list[GroupIndex].users[TagIndex].sort == "" || m_ResultJson.result.list[GroupIndex].users[TagIndex].sort == undefined || m_ResultJson.result.list[GroupIndex].users[TagIndex].sort==null) {
		for (var i = 0; i < m_ResultJson.result.list[GroupIndex].users.length; i++) {
			m_ResultJson.result.list[GroupIndex].users[i].sort = 10000 + i + 1;
		}
		isUser = false;
	}
	m_ResultJson.result.list[GroupIndex].users[TagIndex].sort = Number(m_ResultJson.result.list[GroupIndex].users[TagIndex].sort)-1;
	m_ResultJson.result.list[GroupIndex].users[TagIndex - 1].sort = Number(m_ResultJson.result.list[GroupIndex].users[TagIndex - 1].sort)+1;
	var top = m_ResultJson.result.list[GroupIndex].users[TagIndex - 1];
	m_ResultJson.result.list[GroupIndex].users[TagIndex - 1] = m_ResultJson.result.list[GroupIndex].users[TagIndex];
	m_ResultJson.result.list[GroupIndex].users[TagIndex] = top;

	var userlist = [];
	var jObject = {};
	if (!isUser) {
		for (var j = 0; j < m_ResultJson.result.list[GroupIndex].users.length; j++) {
			jObject = {};
			jObject.id = m_ResultJson.result.list[GroupIndex].users[j].deptid;
			jObject.sort = m_ResultJson.result.list[GroupIndex].users[j].sort;
			userlist.push(jObject);
		}
	} else {
		jObject.id = m_ResultJson.result.list[GroupIndex].users[TagIndex - 1].deptid;
		jObject.sort = m_ResultJson.result.list[GroupIndex].users[TagIndex - 1].sort;
		userlist.push(jObject);
		jObject = {};
		jObject.id = m_ResultJson.result.list[GroupIndex].users[TagIndex].deptid;
		jObject.sort = m_ResultJson.result.list[GroupIndex].users[TagIndex].sort;
		userlist.push(jObject);
	}
	var json = $.toJSON({
		ulist: userlist
	})
	$(".loading").show();
	$(".loadingcover").show();
	manageObj.changeuserposition(json);
	//CommonErgodic();//公共遍历方法
	PageLoadTrees();
	//当前标签组设置为选中状态，显示所有标签
	$("#users" + GroupIndex).attr("style", "display:block");
	$("#group" + GroupIndex).removeClass().addClass("inactive-m inactives-m");
}

//分组内标签向下移动单击事件
function UserBottom(GroupIndex, TagIndex) {
	//参数：GroupIndex是所选标签组的下标，TagIndex是所选标签的下标
	event.cancelBubble = true;//禁止触发父级事件
	var isUser = true;//判断人员顺序是否提交过,提交过true，没提交过false
	if (m_ResultJson.result.list[GroupIndex].users[TagIndex].sort == "" || m_ResultJson.result.list[GroupIndex].users[TagIndex].sort == undefined || m_ResultJson.result.list[GroupIndex].users[TagIndex].sort == null) {
		for (var i = 0; i < m_ResultJson.result.list[GroupIndex].users.length; i++) {
			m_ResultJson.result.list[GroupIndex].users[i].sort = 10000 + i + 1;
		}
		isUser = false;
	}
	m_ResultJson.result.list[GroupIndex].users[TagIndex].sort = Number(m_ResultJson.result.list[GroupIndex].users[TagIndex].sort)++;
	m_ResultJson.result.list[GroupIndex].users[TagIndex + 1].sort = Number(m_ResultJson.result.list[GroupIndex].users[TagIndex + 1].sort)--;
	var top = m_ResultJson.result.list[GroupIndex].users[TagIndex + 1];
	m_ResultJson.result.list[GroupIndex].users[TagIndex + 1] = m_ResultJson.result.list[GroupIndex].users[TagIndex];
	m_ResultJson.result.list[GroupIndex].users[TagIndex] = top;

	var userlist = [];//储存换位置之后缓存
	var jObject = {};
	if (!isUser) {
		for (var j = 0; j < m_ResultJson.result.list[GroupIndex].users.length; j++) {
			jObject = {};
			jObject.id = m_ResultJson.result.list[GroupIndex].users[j].deptid;
			jObject.sort = m_ResultJson.result.list[GroupIndex].users[j].sort;
			userlist.push(jObject);
		}
	} else {
		jObject.id = m_ResultJson.result.list[GroupIndex].users[TagIndex + 1].deptid;
		jObject.sort = m_ResultJson.result.list[GroupIndex].users[TagIndex + 1].sort;
		userlist.push(jObject);
		jObject = {};
		jObject.id = m_ResultJson.result.list[GroupIndex].users[TagIndex].deptid;
		jObject.sort = m_ResultJson.result.list[GroupIndex].users[TagIndex].sort;
		userlist.push(jObject);

	}
	var json = $.toJSON({
		ulist: userlist
	});
	$(".loading").show();
	$(".loadingcover").show();
	manageObj.changeuserposition(json);
	//CommonErgodic();//公共遍历方法
	PageLoadTrees();
	//当前标签组设置为选中状态，显示所有标签
	$("#users" + GroupIndex).attr("style", "display:block");
	$("#group" + GroupIndex).removeClass().addClass("inactive-m inactives-m");
}
function AsyncChangeUserPositionResult(jsonResult) {
	if (jsonResult.success) {
		ShowMsg("myPageAlert", "操作成功！");
	} else {
	    ShowError("myPageAlert", "操作失败：" + jsonResult.error);
	    $(".loading").hide();
	    $(".loadingcover").hide();
	}
	manageObj.getdepartmenttreelist();//获取部门树形列表
}
///---------------------分组内标签向上向下移动--------------end
