$package("itsm.security"); 
 /**  
 * @author Van&&Tan  
 * @constructor role
 * @description 角色管理主函数.
 * @date 2011-02-25
 * @since version 1.0 
 */
$import('itsm.security.functionTree');
itsm.security.role=function(){

	this.operator='';
	this.result=null;
	this.roleIds='';
	this.noSelect='';
	this.functionNo='';
	this.editRoleIds='';
	this.optItem='';
	this.str='';
	return{
		/**
		 * @description 状态格式化.
		 */
		roleStateFormat:function(cellvalue, options){
			if(cellvalue)
				return i18n['common_enable'];
			else
				return i18n['common_disable'];
		},
		
		/**
		 * @description 格式化动作.
		 */
		roleGridFormatter:function(cell,opt,data){
			var actionHTML=$('#roleGridAct').html();
			actionHTML=actionHTML.replace(/\{id}/g,data.roleId);
			return actionHTML;
		},
		
		/**
		 * @description 加载角色列表.
		 */
		showRoleGrid:function(){
			var params = $.extend({},jqGridParams, {	
				url:'role!find.action',
				caption:i18n['caption_roleGrid'],
				colNames:['ID',i18n['title_role_roleName'],i18n['title_role_roleCode'],i18n['common_desc'],i18n['common_remark'],i18n['common_state'],i18n['common_action'],''],
			 	colModel:[
			 	          {name:'roleId',align:'left',width:30},
			 	          {name:'roleName',align:'left',width:80},
			 	          {name:'roleCode',align:'left',width:80},
			 	          {name:'description',align:'left',width:120},
			 	          {name:'remark',align:'left',width:80},
			 	          {name:'roleState',align:'center',width:30,formatter:itsm.security.role.roleStateFormat},
			 	          {name:'act',align:'center',sortable:false,width:80,formatter:itsm.security.role.roleGridFormatter},
			 	          {name:'roleState',hidden:true}
			 	],
				jsonReader: $.extend(jqGridJsonReader, {id: "roleId"}),
				sortname:'roleId',
				pager:'#rolePager'
			});
			$("#roleGrid").jqGrid(params);
			$("#roleGrid").navGrid('#rolePager',navGridParams);
			//列表操作项
			$("#t_roleGrid").css(jqGridTopStyles);
			$("#t_roleGrid").append($('#roleTopMenu').html());
			
			//自适应宽度
			setGridWidth("#roleGrid","regCenter",10);
			
		},
		
		
		/**
		 * @description 新增窗口.
		 */
		addWin:function(){
			$('#roleId').val();
			$("#addRole form")[0].reset();
			$('#addRole').window('open');
			operator = 'save';
		},
		/** 
		 * @description 新增角色.
		 */
		addRole:function() {
				if($('#addOrEditRoleForm').form('validate')){
					var ROLE=$('#roleCode').val();
					if(ROLE.indexOf("ROLE_")==-1){
						
						ROLE="ROLE_"+ROLE;
						$('#roleCode').val(ROLE);
					}
					$.post('role!existByRoleCode.action','roleDto.roleCode='+ROLE,function(data){
						if(data || $('#roleCode').val()==$('#back_roleCode').val()){
							$.post('role!existByRoleName.action','roleDto.roleName='+$('#roleName').val(),function(result){
								if(result || $('#roleName').val()==$('#back_roleName').val()){
								
										var role_form = $('#addRole form').serialize();
										var url = 'role!'+operator+'.action';
										$.post(url, role_form, function(){
											$('#addRole').window('close');
											$('#roleGrid').trigger('reloadGrid');
											msgShow(i18n['msg_add_successful'],'show');
										});
								}else{
									msgAlert(i18n['msg_role_roleNameExist'],'info');	
								}
							});
						}else{
							msgAlert(i18n['msg_role_roleCodeExist'],'info');	
						}
					});
			}
			
		},
		
		/** 
		 * @description 删除角色.
		 */
		delRole:function(rowIds) {
			if(rowIds==""){	
				msgAlert(i18n['msg_atLeastChooseOneData'],'info');
			}else{
				$.messager.confirm(i18n['msg_msg'], i18n['msg_confirmDelete'], function(r){
					if (r){
						var pp = $.param({'ids':rowIds},true);
						$.post("role!deleteRole.action", pp, function(data){
							if(data){
								$('#roleGrid').trigger('reloadGrid');
								msgShow(i18n['msg_deleteSuccessful'],'show');
							}	
							else{
								msgAlert(i18n['msg_canNotDeleteSystemData'],'info');					
							}
								
						}, "json");
					}
				});
			}
		},

	

		/** 
		 * @description 编辑角色.
		 */
		editRole:function(rowId) {
			operator = 'editRole';
			if(rowId==null){
				msgAlert(i18n['msg_atLeastChooseOneData'],'info');
			}else{
				var data = $("#roleGrid").getRowData(rowId);
				$('#roleId').val(data.roleId);
				$('#roleName').val(data.roleName);
				$('#roleCode').val(data.roleCode);
				$('#back_roleCode').val(data.roleCode);
				$('#back_roleName').val(data.roleName);
				$('#remark').val(data.remark);
				$('#description').val(data.description);
				if(data.roleState=='false'){
					$('#roleState1').attr("checked",'false')
				}else
				{
					$('#roleState').attr("checked",'ture')
				}
				
				$('#addRole').window('open');
			}
		},
		/**
		 * @description 搜索角色.
		 */
		search:function(){
			var sdata=$('#searchRole form').getForm();
			var postData = $("#roleGrid").jqGrid("getGridParam", "postData");       
			$.extend(postData, sdata);
			var _url = 'role!find.action';		
			$('#roleGrid').jqGrid('setGridParam',{url:_url})
				.trigger('reloadGrid',[{"page":"1"}]).jqGrid('setGridParam',{url:_url});
			
		},
		
		//--------------------------角色权限分配 start-------------------------
		
		/**
		 * @description 打开权限分配窗口
		 */
		open_func:function(rowId,isRoles){
			result=null;
			roleIds=''
			noSelect=''
			optItem='';
			if(rowId==""){
				msgAlert(i18n['msg_atLeastChooseOneData'],'info');
			}else{	
				
				if(isRoles){
					$.post('role!getResourceByRoleId.action',"roleId="+rowId,function(data){
						
						if(data!=null){
							result=data.split(',');
							roleIds=data;
						}else
							result=null;
					})
				}	
				editRoleIds=rowId;
				$('#operationOptions').html(i18n['label_role_chooseFunction']);
				itsm.security.role.functionTree();
				$('#assignFunc').window('open');
			}
			
		},
		
		/**
		 * @description 保存权限分配
		 */
		save_func:function(){
			if(result!=null && result!=''){
				str="str="+result+"-"+editRoleIds
				
			}else{
				str="str=-"+editRoleIds
			}
			
			$.post('role!setResourceByRoleIds.action',str,function(){
				$('#assignFunc').window('close');
				msgShow(i18n['msg_role_roleSetSuccess'],'show');
				
			})
		},
		

		loadOpertion:function(event, data)
		{
			var resName=data.rslt.obj.attr("resName");
			var resNo=data.rslt.obj.attr("resNo");
			if(resName!=null){
				
				functionNo=resNo;
				itsm.security.role.optionsByFunId();
			}
		},
		/**
		 * @description 功能TREE
		 * */
		functionTree:function (){
			
			itsm.security.functionTree.functionTreeCallback('#functionTree',itsm.security.role.loadOpertion);

		},

		/**
		 * @description 全选
		 * */
	    checkAll:function () {
	    	if($('#checkAll_but').attr('checked'))
	    		$('input[name="optItem"]').attr("checked",true);
	    	else
	    		$('input[name="optItem"]').attr("checked",false);
	    	itsm.security.role.getOptSelect();
	    	
	    },
	    /**
		 * @description 反选
		 * */
	    checkOther:function(){
		    $("input[name='optItem']").each(function() {
		    	if(this.checked == false)
		    		this.checked = true;
		    	else
		    		this.checked = false;
		    })
		    itsm.security.role.getOptSelect();
	    },
		
	    /**
		 * @description 获取操作项选中的值
		 */
		getOptSelect:function(){
			
			noSelect='';
			$(".optItemId").each(function(){ //由于复选框一般选中的是多个,所以可以循环输出
				if($(this).attr('checked')){
					if(roleIds=="")
						roleIds=$(this).val();
					else
						roleIds=roleIds+","+$(this).val();
				}else{
					roleIds+=''
					if(noSelect=="")
						noSelect=$(this).val();
					else
					    noSelect=noSelect+","+$(this).val();

				}
			});
			
			
			
			
			/*把数组唯一化*/
			Array.prototype.in_array = function($){
		        for (var i=0;i<this.length;i++ )
		                if(this[i]===$)return true;
		        return false;
			};
			
			Array.prototype.array_unique=function(){
                for (var i = 0, l = this.length,$ = []; i < l; i++)
                        if (!$.in_array(this[i])) $.push(this[i]);
                return $;
			
			};
	
			
			/*把数组指定值删除*/
			Array.prototype.indexOf = function(val) {  
			   for (var i = 0; i < this.length; i++) { 
					   if (this[i] ==val) return i; 
			   }	   
			   return -1;  
			};  
			Array.prototype.remove = function(val) {
				for(var j=0;j<val.length;j++){ 
					var index = this.indexOf(val[j]);  
					if (index > -1) {  
						this.splice(index, 1);
					}    
			    }  
			};
			
			/*清除没选中的值*/
			var noSelectToIds=noSelect.split(',');
			var roleIdsToIds=roleIds.split(',');
			roleIdsToIds=roleIdsToIds.array_unique();
			roleIdsToIds.remove(noSelectToIds);
		
			result=roleIdsToIds.array_unique();
			
			setTimeout(function(){
				roleIds=result
			},0)
			
		},
		
		 /**
		 * @description 根据功能ID加载相应操作
		 */
		optionsByFunId:function(){
			$('#operationOptions').html('')
			$.post("operation!find.action","functionNo="+functionNo+"&rows=10000",function(data){
				var opt=data.data
				optItem='<table width=100%><tr><td colspan=2>'+
				'<input type=checkbox id=checkAll_but onclick=itsm.security.role.checkAll() />'+i18n['common_selectAll']+
				'<input type=checkbox id=checkOther_but onclick=itsm.security.role.checkOther() />'+i18n['common_deSelect']+'</td></tr>';
				if(opt!=null)
				{
					for(var i=0; i<opt.length;i++){
						if(i % 2==0){
							optItem=optItem+"<tr>"
						}
						optItem=optItem+"<td><input type='checkbox' name='optItem' onclick='itsm.security.role.getOptSelect()' class='optItemId' "+
						"value='"+opt[i].resNo+"'"
						if(result!=null){
							for(var j=0; j<result.length;j++)
							{	
								if(result[j]==opt[i].resNo)
								{
									optItem=optItem+" checked ";
								}
							}
						}
						optItem=optItem+" />"+opt[i].resName+"</td>"
					}
	
					$('#operationOptions').html(optItem)
				}
			},"json")
		},
		
		
		
		
		/**
		 * @description 导出导入
		 */
		importExportRoleData:function(type){
			if(type=='view'){
				itsm.security.role.exportRoleView();
			}
			if(type=='excel'){
				itsm.security.role.importRoleData();
			}
		},
		
		/**
		 * 导出数据到Excel
		 */
		exportRoleData:function(){
			var extype=$('#exportRoleDataDc').val();
			if(extype=="view"){
				itsm.security.role.exportRoleView();
			}
			if(extype=="all"){
				msgAlert(i18n["msg_dc_comfirmExport"],"question");
			}	
		},
		exportRoleView:function(){		
			var sdata = $('#searchRole form').getForm();
			var rqData = $("#roleGrid").jqGrid("getGridParam", "postData");   
			for(i in sdata)
			{    	   		
				if(sdata[i]!=""&&sdata[i]!=null){
					if(i=='roleQueryDto.roleName')$('#exportRole_roleName').val(sdata[i]); 
					if(i=='roleQueryDto.roleCode')$('#exportRole_roleCode').val(sdata[i]);
					if(i=='roleQueryDto.description')$('#exportRole_description').val(sdata[i]);
					if(i=='roleQueryDto.remark')$('#exportRole_remark').val(sdata[i]);
					}
			}
			$('#exportRole_sidx').val(rqData.sidx);
			$('#exportRole_sord').val(rqData.sord);
			$('#exportRole_page').val(rqData.page);
			$('#exportRole_rows').val(rqData.rows);
	//        alert(rqData.page);
			$("#exportRoleWindow form").submit();
		},
		
		
		/**
		 * 导入数据.
		 */
		importRoleData:function(){
			$('#importRoleDataWindow').window('open');
		},
		
		/**
		 * @descriptionadd 客户端导入数据
		 * */
		importRoleExcel:function()
		{
			$.ajaxFileUpload({
	            url:'role!importRoleData.action',
	            secureuri:false,
	            fileElementId:'importRoleFile', 
	            dataType:'json',
	            success: function(data,status){
	             	$('#importRoleDataWindow').window('close');
	            	
	            	if(data=="-2"){
	            		msgShow(i18n['duplicated_role_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');
						$('#roleGrid').trigger('reloadGrid');
					}
	            	 
	            }
	        });
			
		},
		/**
		 * @description 页面事件
		 */
		webEvent:function(){
			$('#link_role_edit').click(function(){itsm.security.role.editRole($("#roleGrid").getGridParam("selrow"))})
			$('#link_role_delete').click(function(){itsm.security.role.delRole($("#roleGrid").getGridParam("selarrrow"))})
			$('#link_role_search').click(function(){$('#searchRole').window('open');})
			$('#link_role_assign').click(function(){itsm.security.role.open_func($("#roleGrid").getGridParam("selarrrow"),false)});
		},
		init:function(){
			 $("#roleMain_loading").hide();
			 $("#roleMain_content").show();
			 itsm.security.role.showRoleGrid();
			 itsm.security.role.webEvent();
		}
	}
}();

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