var divHeight = ""; // 查询面板高度
var dataGridHeight = "";
var ccWidth = "";
var bodyHeight = "";
var addWinWidth = 0;  //新增窗口宽度
var addWinHeight = 0;  //新增窗口高度
var operation = "";
var orgId;
var orgName;
var operate;
/**
 * 初始化
 */
$(function() {

	$("#parentName").attr("disabled", "disabled");
	$("#unitnum").attr("disabled", "disabled");
	$("#name").attr("disabled", "disabled");
	$("#unitType").attr("disabled", "disabled");
	$("#phone").attr("disabled", "disabled");
	$("#address").attr("disabled", "disabled");
	$("#description").attr("disabled", "disabled");
	$("#orderNum").attr("disabled", "disabled");
	
	bodyWidth = document.body.clientWidth;
	bodyHeight = document.documentElement.clientHeight;
	divHeight = $("#orgDivID").height();
	ccWidth = $("#cc").width();
	dataGridHeight = divHeight + 27; 
	addWinWidth = (bodyWidth/5)*3;   
	addWinHeight = (addWinWidth/2)*1;    
	$("#addOrgWinId").window('close');
	$("#addUserWinId").window('close');
	$("#allotRoleWin").window('close'); //分配角色窗口
	$("#userNameId").combobox({
		url : '/admin/user/getUsersList',
		valueField:'id',
	    textField:'text'
	})
	initData();
	leftOrRightChoose();
});
//新增用户输入框初始化
function initUserForm(){
	$("#userNameId01").attr("style","width:"+ (fixShortWidth()) +"px");
	$("#loginNameId").attr("style","width:"+ (fixShortWidth()) +"px");
	$("#usernameId").attr("style","width:"+ (fixShortWidth()) +"px");
	$("#emailId").attr("style","width:"+ (fixShortWidth()) +"px");
	$("#ageId").attr("style","width:"+ (fixShortWidth()) +"px");
	$("#companyId").attr("style","width:"+ (fixShortWidth()) +"px");
	$("#telphoneId").attr("style","width:"+ (fixShortWidth()) +"px");
	$("#sexId").combobox({
		width:fixShortWidth()+4  
	})
	$("#countStatusId").combobox({
		width:fixShortWidth()+4  
	})
	$("#userTypeId").combobox({
		width:fixShortWidth()+4  
	})
	$("#userTypeId01").combobox({
		width:fixShortWidth()  
	})
}

function initData() {
	// 初始化菜单树
	$('#tt').tree({
		url : '/admin/org/getLeftTree',
//		state : 'closed',
		onLoadSuccess : function(node, data) {
			// 加载成功后选中根节点
			$('#tt').tree('select', $('#tt').tree('getRoot').target);
			url = '/admin/org/queryOrgById?orgId=' + data[0].id;
			$.post(url, function(bo) {
				$('#right').form('load', bo);
			}, 'json');
//			if(true){ //默认关闭所有节点
//				var root = $("#tt").tree("getRoot");
//				$("#tt").tree("collapseAll",root.target);
//			}
			queryOrgUser(data[0].id);
		},
		onBeforeExpand : function(node, param) {
		},
		onClick : function(node) {
			url = '/admin/org/queryOrgById?orgId=' + node.id;
			$.post(url, function(bo) {
				$('#right').form('load', bo);
			}, 'json');
			initUserList(node.id); //加载机构下面所有用户信息
		}
	});
}

function queryOrgUser(id){
	url = '/admin/org/queryOrgById?orgId=' + id;
	$.post(url, function(bo) {
		$('#right').form('load', bo);
	}, 'json');
	initUserList(id); //加载机构下面所有用户信息
}


/**
 * 描述：增加机构信息
 */
function openAddWin() {
	operate = "add";
	var row = $('#tt').tree('getSelected');
	if (row != null) {
		$("#addOrgWinId").window({
			title : '新增机构信息',
			width : 900,
			height : 300,
			left : (ccWidth - 900) / 2,
			top : (bodyHeight - 300)/2,
			closable : true, // 否显示关闭按钮
			collapsible : false, // 是否显示折叠按钮
			minimizable : true, // 是否显示最小化按钮
			maximizable : true, // 是否显示最大化按钮
			close : true, // 初始是否关闭
			modal : true
		});
		$("#addOrgForm").form('clear');
		$("#addOrgWinId").window('open');
		$("#parentNameId02").val(row.text);
	} else {
		$.messager.alert('提示', "请选择上级菜单", 'error');
		return;
	}
}

// 保存
function saveData() {
	var row = $('#tt').tree('getSelected');
	$("#addOrgForm").form('submit', {
		url : '/admin/org/addOrUpdateOrgInfo?orgId=' + row.id + "&orgName=" + encodeURI(encodeURI(row.text))+"&operate="+operate,
		onSubmit: function(){
			return $(this).form('validate');
		},
		success: function(data){
			var data = eval("("+data+")");
			if (data.flag){
				$.messager.alert('提示', data.info, 'ok');
				initData();
				$("#addOrgWinId").window('close');
			} else {
				$.messager.alert("提示",data.info,'error');
			}
		}
	});
}

// 修改
function editOrg() {
	operate = "edit";
	var row = $('#tt').tree('getSelected');
	if (row != null) {
		$.getJSON(url = '/admin/org/queryOrgById?orgId=' + row.id+"&operate="+operate, function(data) {
			$("#addOrgForm").form('load', data);
		});
		$("#addOrgWinId").window({
			title : '修改机构信息',
			width : 900,
			height : 300,
			left : (ccWidth - 900) / 2,
			top : (bodyHeight - 300)/2,
			closable : true, // 否显示关闭按钮
			collapsible : false, // 是否显示折叠按钮
			minimizable : true, // 是否显示最小化按钮
			maximizable : true, // 是否显示最大化按钮
			close : true, // 初始是否关闭
			modal : true
		});
		$("#addOrgWinId").window('open');
	} else {
		$.messager.alert('提示', '请选中一条记录', 'info');
		// $.调用jquery自己的内置对象
	}
}
// 删除
function delOrg() {
	var row = $('#tt').tree('getSelected');
	if (row != null) {
		orgId = row.id;
		$.getJSON("/admin/org/isExistNext?orgId=" + orgId, function(obj) {
			if(obj.flag) {
				$.messager.confirm("删除", "确定删除？", function(r) {
					if (r) {
						var postUrl = '/admin/org/deleteOrg';
						$.post(postUrl, {
							"ids" : orgId
						}, function(result) {
							if (result.flag) {
								$.messager.alert('提示', '数据删除成功！', 'info');
								initData();
							} else {
								$.messager.alert('提示', '数据删除失败！', 'info');
								initData();
							}
						}, 'json');
					}
				});
			} else {
				$.messager.alert('提示', obj.info, 'info');
			}
		});
	} else {
		$.messager.alert('提示', '请选中一条记录', 'info');
		// $.调用jquery自己的内置对象
	}
}

/**
 * id数组转换为json字符串
 */
function arrayTojson(arr) {
	var jsonIds = "[";
	for (var i = 0; i < arr.length; i++) {
		if (i == arr.length - 1) {
			jsonIds += arr[i].id;
		} else {
			jsonIds += arr[i].id + ",";
		}
	}
	jsonIds += "]";

	return jsonIds;
}

/**
 * 描述：加载数据
 */
function loadData(infoId) {

	$.getJSON("queryById.do?id=" + infoId, {}, function(jso) {
		putValue(jso);
	});
}

/**
 * 描述：显示数据
 * 
 * @param obj
 *            数据
 */
function putValue(obj) {
	$("#newsTitleId2").text(obj.newsTitle);
	$("#newsAbstractId2").text(obj.newsAbstract);
	$("#standby1Id2").text(obj.standby1);
	$("#newsTypeId2").text(obj.newsType);
	$("#industryId2").text(obj.industry);
	$("#auditStatusId").text(obj.auditStatus);
	$("#releaseDateId2").text(obj.releaseDate);
	$("#promulgatorId2").text(obj.promulgator);
	$("#startDateId2").text(obj.startDate);
	$("#endDateId2").text(obj.endDate);
	$("#hostCityId2").text(obj.hostCity);

}


function initUserList(orgId){
	$("#userListTable").datagrid({
		height: (bodyHeight - divHeight)/3*2,
		nowrap : true,
		striped : true,
		pagination : true,
		singleSelect : true, 
		rownumbers : true,
		pageSize : 15,
		autoRowHeight: false, 
		fitColumns : true, // 允许表格自动缩放，以适应父容器
		url : '/admin/org/getOrgUserByOrdId?orgId='+orgId,
		columns:[[{ 
			field:'1ck',
			title:'id',
			width:15,
			checkbox:true
		},{
			field:'username',
			title:'用户名称',
			align:'center',
			formatter : dataStyle,
			width:50,
			sortable:true
		},{
			field:'loginName',
			title:'登录账号',
			width:70,
			align:'center'
		},{
			field:'email',
			title:'邮箱',
			width:70,
			align:'center'
		},{
			field:'userType',
			title:'用户类型',
			width:40,
			align:'center'
		},{
			field:'createTime',
			title:'创建时间',
			width:70,
			align:'center'
		},{
			field:'loginCount',
			title:'登录次数',
			width:30,
			align:'center'
		},{ 
			field:'countStatus',
			title:'账号状态',
			width:40, 
			align:'center'
		},{
			field:'roles',
			title:'分配角色',
			width:270,
			align:'left',
			headalign : 'center'
		}]] ,
		onLoadSuccess:function(data){
	    	$('#userListTable').datagrid('clearSelections'); 
	    }
	})
	initOrgRoleList(orgId);
}

//初始化角色列表
function initOrgRoleList(orgId){
	$("#orgRoleListTable").datagrid({
		title : '部门拥有角色列表',
		height: (bodyHeight - divHeight)/3,
		nowrap : true,
		striped : true,
		pagination : true,
		singleSelect : true, 
		rownumbers : true,
		pageSize : 15,
		autoRowHeight: false, 
		fitColumns : true, // 允许表格自动缩放，以适应父容器
		url : '/admin/org/getAllOrgRoles?orgId='+orgId,
		columns:[[{ 
			field:'ck',
			title:'id',
			width:15, 
			checkbox:true
		},{
			field:'roleName',
			title:'角色名称',
			align:'center',
			formatter : dataStyle1,
			width:100,
			sortable:true
		},{ 
			field:'description',
			title:'角色描述',
			width:140,
			align:'center'
		}]], 
		onLoadSuccess:function(data){
	    	$('#roleListTableID').datagrid('clearSelections'); 
	    } 
	})
}

function dataStyle(val,row){
	return '<a class="" href="#" onclick="viewUser(\''+row.id+'\')">'+row.username+'</a>';
}
function dataStyle1(val,row){
	return '<a class="" href="#" onclick="viewUser(\''+row.id+'\')">'+row.roleName+'</a>';
}
/**
 * 打开添加用户窗口
 */
//打开 新增 |修改 窗口
function openAddWin1(winType){
	initUserForm();
	operation = winType;
	var treeRode = $("#tt").tree('getSelected');
	if(treeRode.id != undefined){
		if('add' == winType){
//			$("#main_area").height(300); 
			$("#addUserWinId").window({
				title : "新增用户信息",
				width : 900,
				height : 300,
				left : (ccWidth - 900)/2,
				top : (bodyHeight - 300)/2,
				closable : true, 	 // 否显示关闭按钮
				collapsible : false, // 是否显示折叠按钮
				minimizable : false, // 是否显示最小化按钮
				maximizable : false, // 是否显示最大化按钮
				close : true,        // 初始是否关闭
				modal : true
			});
			$("#buttonId01").show();
			$("#buttonId02").show();
			$("#saveUserForm").form('clear');
			$("#addUserWinId").window('open');
		}
		if('edit' == winType){
			var rows = $('#userListTable').datagrid('getSelections');
			if(rows.length == 1){
				var row = $('#userListTable').datagrid('getSelected');
				$.getJSON("/admin/user/getUserById/" + row.id, function(data) {
					$("#saveUserForm").form('load', data);
				});
				$("#main_area").height(addWinHeight);
				$("#addUserWinId").window({
					title : "修改用户信息",
					width : 900,
					height : 300,
					left : (ccWidth - 900)/2,
					top : (bodyHeight - 300)/2,
					closable : true, 	 // 否显示关闭按钮
					collapsible : false, // 是否显示折叠按钮
					minimizable : false, // 是否显示最小化按钮
					maximizable : false, // 是否显示最大化按钮
					close : true,        // 初始是否关闭
					modal : true
				});
				$("#buttonId01").show();
				$("#buttonId02").show();
				$("#addUserWinId").window('open');
			}else {
				$.messager.alert('提示', '请选中一条记录', 'info');
			}
		}
	}else {
		
	}
}

function saveData1(){
	var treeNode = $('#tt').tree('getSelected');
	if('add' == operation){
		var loginName = $("#loginNameId").val();
		$.getJSON("/admin/user/isExistUser?loginName="+loginName,
		 	function(check) {
				if (check.flag){ 
					$.messager.alert('提示', '账号已存在，请重新输入！', 'error');
				}else{
					// 如果不重复则添加用户
					$('#saveUserForm').form('submit',{
						url: '/admin/user/addUser?orgId='+treeNode.id+"&operation="+operation,
						onSubmit: function(){
							return $(this).form('validate');
						},
						success: function(data){
							var data = eval("("+data+")")
							if (data.flag){
								$.messager.alert('提示', data.info, 'ok');
								closeWindow1();
								initUserList(treeNode.id);
							} else {
								$.messager.alert("提示","账号已存在，请重新输入！",'error');
							}
						}
					}); 
				}
		});
	}
	if('edit' == operation){
		var row = $('#userListTable').datagrid('getSelected');
		$('#saveUserForm').form('submit',{
			url: '/admin/user/addUser?userId='+row.id+"&operation="+operation+"&orgId="+treeNode.id,
			onSubmit: function(){
				return $(this).form('validate');
			},
			success: function(data){
				var data = eval("("+data+")"); 
				if (data.flag){
					$.messager.alert('提示',data.info, 'ok');
					closeWindow1();
					initUserList(treeNode.id);
				} else {
					$.messager.alert("提示",data.info,'error');
				} 
			}
		});
	}
}

function deleUser(){
	var row = $('#tt').tree('getSelected');
	var rows = $("#userListTable").datagrid('getSelected');
	/*$.getJSON(url = '/admin/org/delOrgUserByOrdId?orgId=' + row.id+"&userId="+rows.id, function(data) {
		if (data.flag){
			$.messager.alert('提示',data.info, 'ok');
			closeWindow1();
			initUserList(row.id);
		} else {
			$.messager.alert("提示",data.info,'error');
		} 
	});*/
	
	$.messager.confirm("删除","确定删除？",function(r){
		if (r){
			var postUrl = '/admin/user/deleteUser';
			$.post(postUrl,{
				"userId":rows.id,"orgId":row.id},function(result){
				if (result.flag){
					$.messager.alert('提示',result.info,'ok');
					closeWindow1();
					initUserList(row.id);
				} else {
					$.messager.alert('提示',result.info,'error');
					initData();
					return;
				}
			},'json');
		}
	});
}

//打开角色分配窗口
function openRoleWin(){
	var row = $('#tt').tree('getSelected');
	if(row.id != ''){
		$("#allotRoleWin").window({
			title : '部门角色分配',
			width : addWinWidth,
			height : addWinHeight, 
			left : (bodyWidth - addWinWidth)/2,
			top : (bodyHeight - addWinHeight)/2,
			closable : true, 	 // 否显示关闭按钮
			collapsible : false, // 是否显示折叠按钮
			minimizable : false, // 是否显示最小化按钮
			maximizable : false, // 是否显示最大化按钮 
			close : true,        // 初始是否关闭
			modal : true
		});
		$.post("/admin/role/getRolesList",function(data){ //获取所有角色
			var html="";
			$.each(data,function(n,v){
				html+="<div class='mult-selection' sid='"+ v.id+"'>"+ v.text+"</div>"
			});
			$("#role-select1").html(html);
			$("#role-select1 div.mult-selection").on("click",function(){
				$(this).toggleClass("active");
			});
		},'json');
		$.post("/admin/role/getOrgRoles/"+row.id,function(data){ //获取当前部门已经拥有所有角色
			var html="";
			$.each(data,function(n,v){
				html+="<div class='mult-selection' sid='"+ v.id+"'>"+ v.roleName+"</div>"
			});
			$("#role-select2").html(html);
			$("#role-select2 div.mult-selection").on("click",function(){
				$(this).toggleClass("active");
			});

		},'json'); 
		$("#buttonId").attr("style","margin:"+addWinHeight/3+"px 0px 0px 0px");
        $("#allotRoleWin").window('open');
	}else {
		$.messager.alert('提示', '请选中一个部门进行角色分配...', 'info');
	} 
}

//打开用户角色分配窗口
function openUserRoleWin(){
	var rows = $('#userListTable').datagrid('getSelections');
	if(rows.length == 1){
		var row = $("#userListTable").datagrid("getSelected");
		$("#allotRoleWin").window({
			title : '用户角色分配',
			width : addWinWidth,
			height : addWinHeight, 
			left : (bodyWidth - addWinWidth)/2,
			top : (bodyHeight - addWinHeight)/2,
			closable : true, 	 // 否显示关闭按钮
			collapsible : false, // 是否显示折叠按钮
			minimizable : false, // 是否显示最小化按钮
			maximizable : false, // 是否显示最大化按钮 
			close : true,        // 初始是否关闭
			modal : true
		});
		$.post("/admin/role/getRolesList",function(data){
			var html="";
			$.each(data,function(n,v){
				html+="<div class='mult-selection' sid='"+ v.id+"'>"+ v.text+"</div>"
			});
			$("#role-select1").html(html);
			$("#role-select1 div.mult-selection").on("click",function(){
				$(this).toggleClass("active");
			});
		},'json');
		$.post("/admin/role/userRoles/"+row.id,function(data){
			var html="";
			$.each(data,function(n,v){
				html+="<div class='mult-selection' sid='"+ v.id+"'>"+ v.roleName+"</div>"
			});
			$("#role-select2").html(html);
			$("#role-select2 div.mult-selection").on("click",function(){
				$(this).toggleClass("active");
			});

		},'json'); 
		$("#buttonId").attr("style","margin:"+addWinHeight/3+"px 0px 0px 0px");
        $("#allotRoleWin").window('open');
	}else {
		$.messager.alert('提示', '请选中一条数据进行角色分配...', 'info');
	} 
}

function allocationRole(){
	var row = $("#userListTable").datagrid("getSelected");
}

function leftOrRightChoose(){

	//移到右边
    $("#toRight").click(function() {
        $("#role-select1 .active").appendTo($("#role-select2"));
		$("#role-select2").children().removeClass("active");
    });
    //移到左边
    $("#toLeft").click(function() {
		$("#role-select2 .active").appendTo($("#role-select1"));
		$("#role-select1").children().removeClass("active");
    });
    //全部移到右边
    $("#allToRight").click(function() {
		$("#role-select1").children().appendTo($("#role-select2"));
		$("#role-select2").children().removeClass("active");
    });
    //全部移到左边
    $("#allToLeft").click(function() {
		$("#role-select2").children().appendTo($("#role-select1"));
		$("#role-select1").children().removeClass("active");
    });
    //给部门分配角色
   /*	$("#saveRoles").on("click",function(){
		var ids="";
		var row = $('#tt').tree('getSelected');
		$("#role-select2").find("div.mult-selection").each(function(n,v){
			if(n>0)
				ids+=",";
			ids+=$(v).attr("sid");
		});
		$.post("/admin/org/setOrgRoles/"+row.id,{"ids":ids},function(data){
			if(data.flag){
				$("#allotRoleWin").window('close');
				initData();
			}
			else{
				$.messager.alert('提示', data.info , 'info');
			}
		},'json');
	});*/
	$("#saveRoles").on("click",function(){
		var treeNode = $('#tt').tree('getSelected');
		var ids="";
		var row = $("#userListTable").datagrid("getSelected");
		$("#role-select2").find("div.mult-selection").each(function(n,v){
			if(n>0)
				ids+=",";
			ids+=$(v).attr("sid");
		});

		$.post("/admin/role/saveUserRoles/"+row.id,{"ids":ids},function(data){
			if(data.flag){
				$("#allotRoleWin").window('close');
				initUserList(treeNode.id);
			}
			else{
				$.messager.alert('提示', data.info , 'info');
			}
		},'json');
	});
}

function allocationRole(){
	var row = $("#userListTable").datagrid("getSelected");
}

function closeWindow() {
	$("#addOrgWinId").window('close');
	initData();
}

function closeWindow1() {
	$("#addUserWinId").window('close');
}
/**
 * 发送邮件
 */
function sendMail(){
	var rows = $('#userListTable').datagrid('getSelections');
	if(rows.length !=0 ){
		$.messager.confirm("发送","确定发送？",function(r){
			if (r){
				var jsonIds = arrayTojson(rows);
				var postUrl = '/admin/user/sendEmailToUser';
				$.post(postUrl,{
					"ids":jsonIds},function(result){
						if (result.flag){
							$.messager.alert('提示',result.info,'ok');
							initUserList();
							closeWindow1();
						} else {
							$.messager.alert('提示',result.info,'error');
							initUserList();
							return;
						}
					},'json');
			}
		});
	}else{ 
		$.messager.alert('提示', '请选中一条记录', 'info');
		// $.调用jquery自己的内置对象
	}
}

var clientWidth = document.documentElement.clientWidth;
var clientHeight = document.documentElement.clientHeight;
$(document).ready(function() {
	// 左侧div宽度
	var div_left_width = $(".panel-header").width() + 18;
	my_resize(div_left_width);
	$(window).resize(function() {
		clientHeight = document.documentElement.offsetHeight;
		clientWidth = document.documentElement.offsetWidth;
		div_left_width = $(".panel-header").width() + 18;
		my_resize(div_left_width);
	});
	// 自动适应页面大小
	function my_resize(panelWidth) {
		$("#cc").css("width", clientWidth);
		$("#cc").css("height", clientHeight);
		// $("#cc").layout('resize',{height:clientHeight,width:clientWidth});
		$('#left').panel('resize', {
			height : clientHeight,
			width : div_left_width
		});
		$('#right').panel('resize', {
			height : clientHeight,
			width : clientWidth - panelWidth
		});

	}

	$(".layout-button-left").hide();
	$(".layout-button-left").bind("click", function() {
		my_resize(div_left_width - 21);
		clientWidth = document.documentElement.clientWidth;
		$(".layout-button-right").bind("click", function() {
			var temp = 0 - div_left_width + 145;
			my_resize(temp);
			clientWidth = document.documentElement.clientWidth;
		});
	});
});


//设置 long 宽度自适应   相对窗口
function fixLongWidth(){ 
	return addWinWidth*0.755;        
} 
          
//设置 short 宽度自适应
function fixShortWidth(){   
	return addWinWidth*0.30;           
} 