$package("itsm.security");
/**  
 * @author Tan  
 * @constructor users
 * @description 用户管理主函数.
 * @date 2011-02-25
 * @since version 1.0 
 */
$import('itsm.security.organizationTreeUtil')
$import('itsm.security.editUserPassword')


itsm.security.user=function(){
	this.operator;
	this.userRoleIds = new Array();
	this.mydata = new Array();
	return{
		/**
		 * @description 状态格式化.
		 */
		userStateFormat:function(cellvalue, options){
			if(cellvalue==true){
				return i18n['common_enable'];
			}
			else{
				return i18n['common_disable'];
			}
		},
		/**
		 * @description 动作格式化.
		 */
		userGridFormatter:function(cell,opt,data){
			return $('#userToolbarAct').html()
		},
		/**
		 * @description 加载用户列表.
		 */
		showUserGrid:function(){
			var params = $.extend({},jqGridParams, {	
				url:'user!find.action',
				caption:i18n['caption_userGrid'],
				colNames:['ID',i18n['title_user_loginName'],i18n['title_user_lastName'],i18n['title_user_firstName'],i18n['title_user_org'],i18n['title_user_phone'],i18n['title_user_mobile'],'Email',i18n['common_state'],i18n['common_action'],'','','','','','','','','',''],
			 	colModel:[
			 	          {name:'userId',align:'center',width:30},
			 	          {name:'loginName',align:'center',width:80},
			 	          {name:'firstName',align:'center',width:50},
			 	          {name:'lastName',align:'center',width:30},
			 	          {name:'orgName',align:'center',sortable:false,width:80},
			 	          {name:'phone',align:'center',width:80},
			 	          {name:'moblie',align:'center',width:80},
			 	          {name:'email',align:'center',width:80},
			 	          {name:'userState',align:'center',width:40,formatter:itsm.security.user.userStateFormat},
			 	          {name:'act', width:80,align:'center',sortable:false,formatter:itsm.security.user.userGridFormatter},
			 	          {name:'userState',hidden:true},
			 	          {name:'remark',hidden:true},
			 	          {name:'job',hidden:true},
			 	          {name:'password',hidden:true},
			 	          {name:'officePhone',hidden:true},
			 	          {name:'orgNo',hidden:true},
			 	          {name:'description',hidden:true},
			 	          {name:'fax',hidden:true},
			 	          {name:'msn',hidden:true},
			 	          {name:'officeAddress',hidden:true}
			 	          
			 	],
				jsonReader: $.extend(jqGridJsonReader, {id: "userId"}),
				sortname:'userId',
				pager:'#userPager'
				});
				$("#userGrid").jqGrid(params);
				$("#userGrid").navGrid('#userPager',navGridParams);
				//列表操作项
				$("#t_userGrid").css(jqGridTopStyles);
				$("#t_userGrid").append($('#userTopMenu').html());
				
				//自适应宽度
				setGridWidth("#userGrid","regCenter",10);
		},
		
		/** 
		 * @description 保存新用户
		 * */
		addUser:function() {
			if($('#userForm').form('validate')){
				if(operator=='save'){
					$.post('user!userExist.action','userDto.userId='+$("#userId").val()+'&userDto.loginName='+$("#loginName").val(),function(data){
						if(data){
							itsm.security.user.addUserOpt();
						}else{
							$.messager.alert(i18n['msg_msg'],'<br/>'+i18n['error_userExist'],'error');
						}
					})
				}else{
					itsm.security.user.addUserOpt();
				}
			}	
		},
		
		/** 
		 * @description 编辑保存用户
		 * */
		addUserOpt:function() {
			if($('#userForm').form('validate')){
				var user_form = $('#userForm form,#roleSet-win form').serialize();
				var url = 'user!'+operator+'.action';
				$.post(url, user_form, function(){
					msgShow(i18n['msg_add_successful'],'show');
					$('#addUser').window('close');
					$('#userGrid').trigger('reloadGrid');
				});
			}
		},
		
		/**
		 * @description 用户添加窗口
		 */
		user_add:function(){
			$.post('currency!findDefaultCurrency.action',function(data){
				if(data!=null && data!='')
					$('#userCost_currency').text(data);
				else
					$('#userCost_currency').text('￥')
			});
			$('#resetPassword_tr').hide();
			$('#password_tr,#rpassword_tr').show();
			$('#loginName').removeAttr("readonly");
			resetForm('#addUserForm');
			itsm.security.user.add_loadRole(0,"roleSet");
			$('#addUser').window('open');
			operator = 'save';
			$('#userOtherInfo').tabs();
		},

		/**
		 * @description 编辑用户
		 */
		editUser_aff:function(){
			checkBeforeEditGrid('#userGrid',itsm.security.user.editUser);
		},
		
		/**
		 * @description 编辑用户窗口
		 */
		editUser:function(data) {
			operator = 'merge';
			$.post('currency!findDefaultCurrency.action',function(data){
				if(data!=null && data!='')
					$('#userCost_currency').text(data);
				else
					$('#userCost_currency').text('￥')
			});
			
			$('#userId').val(data.userId);
			$('#loginName').val(data.loginName);
			$('#firstName').val(data.firstName);
			$('#lastName').val(data.lastName);
			$('#email').val(data.email);
			$('#password,#rpassword').val(data.password);
			$('#resetPassword_tr').show();
			$('#password_tr,#rpassword_tr').hide();

			$('#moblie').val(data.moblie);
			$('#phone').val(data.phone);
			$('#fax').val(data.fax);
			$('#msn').val(data.msn);
			$('#officeAddress').val(data.officeAddress);
			$('#officePhone').val(data.officePhone);
			$('#description').val(data.description);
			$('#remark').val(data.remark);
			$('#userCost').val(data.userCost);
			$('#job').val(data.job);
			$('#user_orgName').val(data.orgName);
			$('#user_orgNo').val(data.orgNo);
			/**
			 * 单选按钮选择项
			 */
			if(data.userState=='false'){
				$('#userState1').attr("checked",'false')
			}else
			{
				$('#userState').attr("checked",'ture');
			}
			$("#userId").attr('name','userDto.userId')
			$('#loginName').attr("readonly",'readonly');
			itsm.security.user.add_loadRole(data.userId,"roleSet");
			$('#addUser').window('open');
			$('#userOtherInfo').tabs();
		},
		
		
		/**
		 * @description 删除.
		 */
		opt_delete:function(){
			checkBeforeDeleteGridInLine('#userGrid',itsm.security.user.opt_deleteInLineMethod);
		},
		/**
		 * @description 删除Method.
		 */
		opt_deleteInLineMethod:function(rowId){
			var param = $.param({'ids':rowId},true);
			$.post("user!delUser.action", param, function(data){
					$('#userGrid').trigger('reloadGrid');
					msgShow(i18n['msg_user_deleteSuccessful'],'show');
			}, "json");
		},
		
		/**
		 * @description 搜索用户
		 */
		searchUser:function(){
			var sdata=$('#searchUser form').getForm();
			var postData = $("#userGrid").jqGrid("getGridParam", "postData");
			$.extend(postData,sdata);  
			var _url = 'user!find.action';		
			$('#userGrid').jqGrid('setGridParam',{url:_url})
				.trigger('reloadGrid',[{"page":"1"}]).jqGrid('setGridParam',{url:_url});
		},
		
		
		opt_setRole_aff:function(){
			checkBeforeEditGrid('#userGrid',itsm.security.user.opt_setRole);
		},
		/**
		 * @description 操作项-用户角色设置
		 */
		opt_setRole:function(rowData){
			$('#roleIds').val(rowData.userId);
			itsm.security.user.add_loadRole(rowData.userId,"roleSetInfo");
			$('#roleSet-win').window('open');
		},
		/**
		 * @description 操作项-保存(根据用户ID修改角色)
		 */
		updateRoleByUserId:function(){
			var rowIds = $('#userGrid').getGridParam('selarrrow');
			if(rowIds=='')
			{
				$.messager.alert(i18n['msg_msg'],'<br/>'+i18n['msg_atLeastChooseOneData'],'info');
			}
			else
			{
				var param = $.param({'ids':rowIds},true);
				var user_form = $('#roleSet-win form').serialize();
				$.post("user!updateRoleByUserId.action",user_form+'&'+param, function(){
					
					$('#roleSet-win').window('close');
					$('#userGrid').trigger('reloadGrid');
					
					msgShow(i18n['msg_user_roleSetSuccessful'],'show');

					$('#roleIds').val('')
					
				}, "json");
			}
		},

		/**
		 * @description 加载角色
		 */
		add_loadRole:function(id,tab){
			$("#"+tab+" table").html("");
			$("#"+tab+" table").empty();
			if(id!=null){
				itsm.security.user.getUserRole(id);
			}
			setTimeout(function(){
				itsm.security.user.getUserRoleAll(tab);
			},500);
		},
		/**
		 * @description 新增页面加载角色复选框
		 */
		
		getUserRole:function(id){
				if(id!=0){
					$.post("user!getUserRole.action","id="+id,function(data){
						userRoleIds=data;
					},"json")
				}
		},
		getUserRoleAll:function(tab){
			$.post("role!findByState.action",function(data){
				mydata=data;
				this.roleHtml;
				roleHtml="";
				for(var i=0;i<mydata.length;i++)
				{								
					if(i % 2==0){
						roleHtml=roleHtml+"<tr>"
					}
					roleHtml=roleHtml+"<td><input type='checkbox' name='userDto.roleIds' class='userRoleId'"+
					" value='"+mydata[i].roleId+"'";
					if(userRoleIds!=null){
						for(var j=0; j<userRoleIds.length;j++)
						{	
							if(userRoleIds[j].roleId==mydata[i].roleId)
							{
								roleHtml=roleHtml+" checked ";
							}
						}
					}
					roleHtml=roleHtml+" />"+mydata[i].roleName+"</td>"
					
				}
				if(mydata.length % 2==1){
					roleHtml+="<td></td>"
				}
				$("#"+tab+" table").html(roleHtml);
				userRoleIds=null;
			},"json")
		},
		

		orgSet_save:function(){
			if($('#orgNo1').val()==null || $('#orgNo1').val()==""){

				msgAlert(i18n['title_user_selectOrg'],'error');
				
			}else{	
				var data='id='+$('#orgNo1').val()+'&str='+$('#userId1').val();
				$.post("user!mergeByOrg.action", data, function(){
					
					
					$('#orgSet-win').window('close');
					$('#userGrid').trigger('reloadGrid');
					
					$('#orgName1').val('');
					$('#orgNo1').val('');
					$('#userId1').val('');
					
					
					
					msgShow(i18n['msg_operationSuccessful'],'info');
					
				}, "json");
			}
		},
		

		/**用户角色批量设置窗口*/
		userReleSet_win:function(){
			var rowIds = $("#userGrid").getGridParam("selarrrow");
			if(rowIds==""){
				
				msgAlert(i18n['msg_atLeastChooseOneData'],'info');
				
			}else{	
				
				$('#roleIds').val(rowIds);
				$('#orgName1').val('');
				$('#orgNo1').val('');
				itsm.security.user.add_loadRole(null,"roleSetInfo");
				$('#roleSet-win').window('open');
			}
			
		},
		/**用户所属机构批量设置*/
		userOrgSet_win:function(){
			var rowIds = $("#userGrid").getGridParam("selarrrow");
			if(rowIds==""){
				
				msgAlert(i18n['msg_atLeastChooseOneData'],'info');
				
			}else{	
				$('#userId1').val(rowIds);
				$('#orgSet-win').window('open');
			}
		},


		
		/**
		 * @description 导出导入
		 */
		importExportUserData:function(type){
			if(type=='view'){
				itsm.security.user.exportUserView();
			}
			if(type=='excel'){
				itsm.security.user.importUserData();
			}
		},
		/**
		 * 导出数据到Excel
		 */
		exportUserData:function(){
			var extype=$('#exportUserDataDc').val();
			if(extype=="view"){
				itsm.security.user.exportUserView();
			}
			if(extype=="all"){
				
				msgAlert(i18n["msg_dc_comfirmExport"],"question");
			}
		},
		
		//导出
		exportUserView:function(){
			var sdata = $('#searchUser form').getForm();
			var usData = $("#userGrid").jqGrid("getGridParam", "postData");   
			for(i in sdata)
			{    	   	
				if(sdata[i]!=""&&sdata[i]!=null){
					if(i=='userQueryDto.loginName')$('#exportUser_loginName').val(sdata[i]); 
					if(i=='userQueryDto.firstName')$('#exportUser_firstName').val(sdata[i]);
					if(i=='userQueryDto.lastName')$('#exportUser_lastName').val(sdata[i]);
					if(i=='userQueryDto.email')$('#exportUser_email').val(sdata[i]);
					}
			}
			$('#exportUser_sidx').val(usData.sidx);
			$('#exportUser_sord').val(usData.sord);
			$('#exportUser_page').val(usData.page);
			$('#exportUser_rows').val(usData.rows);
			$("#exportUserWindow form").submit();
		},
		
		/**
		 * 导入数据.
		 */
		importUserData:function(){
			$('#importUserDataWindow').window('open');
		},
		
		/**
		 * @descriptionadd 客户端导入数据
		 * */
		importUserExcel:function()
		{
				$.ajaxFileUpload({
		            url:'user!importUserData.action',
		            secureuri:false,
		            fileElementId:'importUserFile', 
		            dataType:'json',
		            success: function(data,status){
		             	$('#importUserDataWindow').window('close');
		            	if(data=="-2"){
		            		msgShow(i18n['duplicated_Login_names'],'show');
						}else if(data=="-1"){
							msgAlert(i18n['msg_dc_fileNotExists'],'error');
						}else if(data=="0"){
							msgShow(i18n['msg_dc_noEffect'],'show');
						}else{
							msgShow(i18n['msg_dc_importSuccess'].replace('N',data),'show');
							$('#userGrid').trigger('reloadGrid');
						}
		            }
		        });
		},
	
	
		init:function(){
			$("#userMain_loading").hide();
			$("#userMain_content").show();
			itsm.security.user.showUserGrid();
			$('#link_user_add').click(itsm.security.user.user_add);
			$('#link_user_edit').click(itsm.security.user.editUser_aff);
			$('#link_user_delete').click(itsm.security.user.opt_delete);
			$('#link_user_search').click(function(){$('#searchUser').window('open')});
			$('#user_link_search').click(itsm.security.user.searchUser);
			$('#link_user_role').click(itsm.security.user.userReleSet_win);
			$('#link_roleSet_save').click(itsm.security.user.updateRoleByUserId);
			$('#link_user_org').click(itsm.security.user.userOrgSet_win);
			$('#link_orgSet_save').click(itsm.security.user.orgSet_save);
			$('#user_orgName').click(function(){
				itsm.security.organizationTreeUtil.showAll_2('#userGroup_win','#userGroupTree','#user_orgName','#user_orgNo');
			});
			$('#orgName1').click(function(){
				itsm.security.organizationTreeUtil.showAll_2('#userGroup_win','#userGroupTree','#orgName1','#orgNo1');
			});
			$('#user_search_orgName').click(function(){
				itsm.security.organizationTreeUtil.showAll_2('#userGroup_win','#userGroupTree','#user_search_orgName','#user_search_orgNo');
			});
			$('#link_user_password_reset').click(function(){itsm.security.editUserPassword.userPasswordReset($('#loginName').val())});
			
		}
	}
}();

/**载入**/
$(document).ready(itsm.security.user.init);