var divHeight = "";  // 查询面板高度
var dataGridWidth = ""; // 查询面板宽度
var dataGridHeight = "";
var h = "";   // 内容显示窗口高度
var operation = "";
var addWinWidth = 0;  //新增窗口宽度
var addWinHeight = 0;  //新增窗口高度
$(function(){
	$("#addUserWinID").window('close');
	$("#allotRoleWin").window('close');
	$("#sendMailWinId").window('close');
	divHeight = $("#queryDiv").height();
	dataGridWidth = $("#queryDiv").width();
	dataGridHeight = divHeight + 28; 
	var opra;
	initData();
	
	bodyWidth = document.body.clientWidth;
	bodyHeight = document.documentElement.clientHeight;
	addWinWidth = (bodyWidth/5)*3;   
	addWinHeight = (addWinWidth/2)*1;    
	  
	$("#sexId").combobox({
		width:fixShortWidth()  
	})
	$("#countStatusId").combobox({
		width:fixShortWidth()  
	})
	$("#userTypeId").combobox({
		width:fixShortWidth()  
	})
	$("#userTypeId01").combobox({
		width:fixShortWidth()  
	})
	
	$("#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");
	
//	$('#searchable').multiselect2side({
//		search: "待选区　　搜索：" ,
//		selectedPosition: 'right',   
//		moveOptions: false,   
//		labelsx: '待选区',   
//		labeldx: '已选区'         
//	});
	

	leftOrRightChoose();
});


function initData(){
	h = document.body.clientHeight;
	$("#userListTable").datagrid({
		height: h - dataGridHeight,
		nowrap : true,
		striped : true,
		pagination : true,
		singleSelect : false, 
		rownumbers : true, 
		pageList : [15,20,30,40,50],
		autoRowHeight: false, 
		fitColumns : true, // 允许表格自动缩放，以适应父容器
		url : '/admin/user/getAllUsers',
		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:'userType',
			title:'用户类型',
			width:40,
			align:'center'
		},{
			field:'createTime',
			title:'创建时间',
			width:70,
			align:'center'
		},{
			field:'loginCount',
			title:'登录次数',
			width:70,
			align:'center'
		},{ 
			field:'countStatus',
			title:'账号状态',
			width:70, 
			align:'center'
		},{
			field:'roles',
			title:'分配角色',
			width:270,
			align:'left',
			headalign : 'center'
		}]] ,
		onLoadSuccess:function(data){
	    	$('#userListTable').datagrid('clearSelections'); 
	    }
	})
}


function dataStyle(val,row){
	return '<a class="" href="#" onclick="viewUser(\''+row.id+'\')">'+row.username+'</a>';
}

//查询
function queryData() {
	var userName = $("#userNameId01").val()
	var userType = $("#userTypeId01").combobox('getValue');
	var queryParams = null;
	$("#userListTable").datagrid({
		queryParams : {
			userName : userName,
			userType : userType
		}
	});
}
//清空查询条件
function clearQueryForm(){
	$("#queryFromId").form('clear');
}

// 打开 新增 |修改 窗口
function openAddWin(winType){
	operation = winType;
	var title = "";
	if('add' == winType){
		title = "新增用户信息";
		$("#main_area").height(addWinHeight);
		$("#addUserWinID").window({
			title : title,
			width : addWinWidth,
			height : addWinHeight, 
			left : (dataGridWidth - addWinWidth)/2,
			top : (bodyHeight - addWinHeight)/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){
		title = "修改用户信息";
		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 : title,
				width : addWinWidth,
				height : addWinHeight, 
				left : (dataGridWidth - addWinWidth)/2,
				top : (bodyHeight - addWinHeight)/2,
				closable : true, 	 // 否显示关闭按钮
				collapsible : false, // 是否显示折叠按钮
				minimizable : false, // 是否显示最小化按钮
				maximizable : false, // 是否显示最大化按钮
				close : true,        // 初始是否关闭
				modal : true
			});
			$("#buttonId01").show();
			$("#buttonId02").show();
			$("#addUserWinID").window('open');
		}else {
			$.messager.alert('提示', '请选中一条记录', 'info');
		}
	}
}


// 查看
function viewUser(id){
	$.getJSON("/admin/user/getUserById/" + id, function(data) {
		$("#saveUserForm").form('load', data);
	});
	$("#main_area").height(addWinHeight);
	$("#addUserWinID").window({
		title : '查看用户详细信息',
		width : addWinWidth,
		height : addWinHeight, 
		left : (dataGridWidth - addWinWidth)/2,
		top : (bodyHeight - addWinHeight)/2,
		closable : true, 	 // 否显示关闭按钮
		collapsible : false, // 是否显示折叠按钮
		minimizable : false, // 是否显示最小化按钮
		maximizable : false, // 是否显示最大化按钮
		close : true,        // 初始是否关闭
		modal : true
	});
	$("#buttonId01").hide();
	$("#buttonId02").hide();
	$("#addUserWinID").window('open');
} 
// 保存数据
function saveData(){
	var url = "";
	if('add' == operation){
		url = "/admin/user/addUser";
		var loginName = $("#loginNameId").val();
		$.getJSON("/admin/user/isExistUser?loginName="+loginName,
		 	function(check) {
				if (check.flag){ 
					$.messager.alert('提示', '账号已存在，请重新输入！', 'error');
				}else{
					// 如果不重复则添加用户
					$('#saveUserForm').form('submit',{
						url: url,
						onSubmit: function(){
							return $(this).form('validate');
						},
						success: function(data){
							var data = eval("("+data+")")
							if (data.flag){
								$.messager.alert('提示', data.info, 'ok');
								closeUserWin();
								initData();
							} else {
								$.messager.alert("提示","账号已存在，请重新输入！",'error');
							}
						}
					}); 
				}
		});
	}
	if('edit' == operation){
		var row = $('#userListTable').datagrid('getSelected');
		url = "/admin/user/edit/"+row.id;
		$('#saveUserForm').form('submit',{
			url: url,
			onSubmit: function(){
				return $(this).form('validate');
			},
			success: function(data){
				var data = eval("("+data+")"); 
				if (data.success){
					$.messager.alert('提示',data.info, 'ok');
					closeUserWin();
					initData();
				} else {
					$.messager.alert("提示",data.info,'error');
				} 
			}
		});
	}
}

// 删除
function deleUser(){
	var rows = $('#userListTable').datagrid('getSelections');
	if (rows.length !=0 ){
		var jsonIds = arrayTojson(rows);
		$.messager.confirm("删除","确定删除？",function(r){
			if (r){
				var postUrl = '/admin/user/deleteUser';
				$.post(postUrl,{
					"ids":jsonIds},function(result){
					if (result.flag){
						$.messager.alert('提示',result.info,'ok');
						initData();
					} else {
						$.messager.alert('提示',result.info,'error');
						initData();
						return;
					}
				},'json');
			}
		});
	}else{ 
		$.messager.alert('提示', '请选中一条记录', 'info');
		// $.调用jquery自己的内置对象
	}
}

//发送邮件
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');
							initData();
							closeWindow1();
						} else {
							$.messager.alert('提示',result.info,'error');
							initData();
							return;
						}
					},'json');
			}
		});
	}else{ 
		$.messager.alert('提示', '请选中一条记录', 'info');
		// $.调用jquery自己的内置对象
	}
}
//打开角色分配窗口
function openRoleWin(){
	var rows = $('#userListTable').datagrid('getSelections');
	if(rows.length == 1){
		var row = $("#userListTable").datagrid("getSelected");
		$("#allotRoleWin").window({
			title : '用户角色分配',
			width : addWinWidth,
			height : addWinHeight, 
			left : (dataGridWidth - 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 closeUserWin(){
	$("#addUserWinID").window('close');
}
function closeWindow1(){
	$("#sendMailWinId").window('close');
}
/**
 * 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 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 = $("#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');
				initData();
			}
			else{
				$.messager.alert('提示', data.info , 'info');
			}
		},'json');
	});
}

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