/**  
 * @author Van  
 * @constructor Van
 * @description 规则列表主函数.rules/ruleMain.jsp
 * @date 2011-02-26
 * @since version 1.0 
 */
$package('itsm.rules');
$import('itsm.config.dataDictionary.dataDictionaryUtil');
$import("itsm.security.userUtil");
$import("itsm.config.categoryManage.eventCategoryTree");



itsm.rules.ruleCM = function(){
	 

	 
		return {
			
				/**
				 * 取得option HTML
				 */
				getOptionsHTML_i18n:function(options) {
					
				    var optionHTML = '';
				    
				    $.each(options, function(k,v) {
				    	optionHTML += '<option value="'+k+'">'+i18n[v]+'</option>';
				    });
				    
				    return optionHTML;
				},
			
			
				loadConditionHTML:function(){
					
						var options = {
								'etitle' : 'label_sla_title',
								'edesc' : 'label_sla_desc',
								'createdByNo' : 'label_sla_createBy',
								'priorityNo' : 'label_sla_priority',
								'seriousnessNo' : 'label_sla_seriousness',
								'effectRangeNo' : 'label_sla_effectRange',
								'requestCategoryNo' : 'label_sla_ecategory',
								'levelNo' : 'label_sla_level',
								'imodeNo' : 'label_sla_imode'
							};
						return itsm.rules.ruleCM.getOptionsHTML_i18n(options);
						
				},
				
				
				loadConditionMathematicalOperationHTML:function(){
					
					var options = {
							'matches' : 'label_sla_matches',
							'not matches' : 'label_sla_notMatches',
							'==' : 'label_sla_eq',
							'!=' : 'label_sla_notEq',
							'matches start' : 'label_sla_matchesStart',
							'matches end' : 'label_sla_matchesEnd'
						};
					
					return itsm.rules.ruleCM.getOptionsHTML_i18n(options);
					
				},
				
				loadActionHTML:function(){
					
					var options = {
						'servicesNo':'label_sla_setServiceOrg',
						'approvalNo':'label_sla_setApproval',
						'updateLevelNo':'label_sla_updateTo',
						'assigneeGroupNo':'label_sla_assignGroup',
						'assigneeNo':'label_sla_assign',
						'statusNo':'label_sla_struts',
						'priorityNo':'label_sla_priority',
						'seriousnessNo':'label_sla_seriousness'
					};
						
						
					return itsm.rules.ruleCM.getOptionsHTML_i18n(options);
						
				},
				
				
				switchRuleName:function(str){
					
					var strs = {'etitle':'common_title',
						'edesc':'common_desc',
						'createdByNo':'label_sla_createBy',
						'priorityNo':'label_sla_priority',
						'seriousnessNo':'label_sla_seriousness',
						'effectRangeNo':'label_sla_effectRange',
						'requestCategoryNo':'label_sla_ecategory',
						'levelNo':'label_sla_level',
						'imodeNo':'label_sla_imode',
						'==':'label_sla_eq',
						'!=':'label_sla_notEq',
						'matches start':'label_sla_matchesStart',
						'matches end':'label_sla_matchesEnd',
						'not matches':'label_sla_notMatches',
						'matches':'label_sla_matches',
						
						'servicesNo':'label_sla_setServiceOrg',
						'approvalNo':'label_sla_setApproval',
						'ownerNo':'label_sla_updateTo',
						'assigneeNo':'label_sla_assign',
						'assigneeGroupNo':'label_sla_assignGroup',
						'statusNo':'label_sla_struts',
						'priorityNo':'label_sla_priority',
						'seriousnessNo':'label_sla_seriousness',
						'updateLevelNo':'escalateLevel'
					};
							 
				    $.each(strs, function(k,v) {
				    	str=str.replace(k,i18n[v]);
				    });
				    
				  
				    return str;

				},
				
				
				loadActionHTML_Simple:function(){
					
					
					var options = {
							'==':'label_sla_eq',
							'!=':'label_sla_notEq'
						};
					return itsm.rules.ruleCM.getOptionsHTML_i18n(options);

				},
				loadActionHTML_Simple2:function(){
					
					return itsm.rules.ruleCM.loadConditionMathematicalOperationHTML();
				},
				
				setMathematicalOperation:function(valueID,appendID){
					
					var tp=$(valueID).val();
					$(appendID).empty();
					
					if(tp=="priorityNo"||tp=="seriousnessNo"||tp=="effectRangeNo"||tp=="requestCategoryNo"||tp=="levelNo"||tp=="imodeNo"||tp=="createdByNo"){
						
						$(itsm.rules.ruleCM.loadActionHTML_Simple()).appendTo(appendID);
						
					}else{
						$(itsm.rules.ruleCM.loadActionHTML_Simple2()).appendTo(appendID); 	

					}
				},
				
			
				switchDataType:function(valueID){
					
					var sel=$(valueID).val();
					
					if("etitle"==sel||"edesc"==sel){
						
						return "String";

					}else{
						return "Long";
					}
					
				},
				
				/**
				 * 选择请求分类.
				 */
				selectRequestCategory:function(putID,putName){

					itsm.config.categoryManage.eventCategoryTree.requestCategory(putName,putID);
				},
	
				/**
				 * @description 加载升级级别.
				 */
				loadUpdateLevel:function(select){
					
					$(select).html('');
					var url = 'updatelevel!findAllLevels.action';
					$.post(url,function(res)
					{
						if(res.data!=null){
							if(res.data.length>0){
								for(var i=0;i<res.data.length;i++){
									$('<option value="'+res.data[i].ulId+'">'+res.data[i].ulName+'</option>').appendTo(select);
								}
							}
						}
					});
					
				},

				/**
				 * @description 选择服务机构.
				 */
				selectServiceOrg:function(treeDIV,windowDIV,orgNo_put,orgName_put){
					
					   $(windowDIV).window('open');
					   
						$(treeDIV).jstree({
							"json_data":{
							    ajax: {url : "organization!findServicesTree.action"}
							},
							"plugins" : ["themes", "json_data", "ui", "crrm", "cookies", "types", "hotkeys"]
							})
							
							.bind('loaded.jstree', function(e,data){data.inst.open_all(-1);})
							.bind('select_node.jstree',function(event,data){
								
								$(orgNo_put).val(data.rslt.obj.attr("orgNo"));
								$(orgName_put).val(data.rslt.obj.attr("orgName"));

								$(windowDIV).window('close');
							});
				},
				
				/**
				 * 返回规则列表.
				 * 
				 */
				showRuleList:function(rulePackageNo){
					
					
					openTab(i18n['title_rule_ruleList'],'../pages/rules/ruleMain.jsp?rulePackageNo='+rulePackageNo);
			
					setTimeout(function(){
						
						$("#rulesGrid").trigger('reloadGrid');
						
					},10);
				},
				
				/**
				 * 添加规则集列表.
				 */
				replaceRuleStr:function(){
						var str= '<tr id="constraint{0}">'+
						    '<td style="background-color:#FFF;height:28px;text-align:center">{1}'+
						    '<input type="hidden" name="rule_condition_constraints_conNo" value="{2}"/>'+
						    '<input type="hidden" name="rule_condition_constraints_dataType" value="{3}" >'+
						    '<input type="hidden" style="border:none" name="rule_condition_constraints_propertyName" value="{4}" readonly>'+
						    '</td>'+
						    '<td style="background-color:#FFF;text-align:center">{5}'+
						    '<input type="hidden" name="rule_condition_constraints_propertyValueName" value="{6}">'+
						    '<input type="hidden" name="rule_condition_constraints_propertyValue" value="{7}">'+
						    '</td>'+
						    '<td style="background-color:#FFF;text-align:center">'+
						    '<img src="../images/icons/delete.gif" style="cursor:pointer" onclick="itsm.rules.ruleCM.removeRow(\'{8}\')"/>'+
						    '</td>'+
						  '</tr>';
						  
						  for (var i=0; i<arguments.length; i++) {
						    str = str.replace('{'+i+'}', arguments[i]);
						  }
						  return str;
				},
				/**
				 * 移除表格行.
				 */
				removeRow:function(rowId){
				
					$(rowId).remove();
				},
				
				/**
				 * 添加动作集.
				 */
				replaceActionStr:function(){
					
					
					  var str='<tr id="action{0}">'+
					    '<td style="background-color:#FFF;height:28px;text-align:center">{1}'+
					    '<input type="hidden" name="rule_actions_dataType" value="Long">'+
					    '<input type="hidden" style="border:none" name="rule_actions_propertyName" value="{2}" readonly>'+
					    '</td>'+
					    '<td style="background-color:#FFF;text-align:center">{3}'+		   
					    '<input type="hidden" name="rule_actions_givenName" value="{4}" >'+
					    '<input type="hidden" name="rule_actions_givenValue" value="{5}" >'+
					    '</td>'+
					    '<td style="background-color:#FFF;text-align:center">'+
					    '<img src="../images/icons/delete.gif" style="cursor:pointer" onclick="itsm.rules.ruleCM.removeRow(\'{6}\')"/>'+
					    '</td>'+
					  '</tr>';
					  
					  for (var i=0; i<arguments.length; i++) {
						    str = str.replace('{'+i+'}', arguments[i]);
					  }
					  return str;
					  
				},
				
				/**
				 * 创建规则集事件.
				 */
				createRuleEvent:function(flag,htmlPut,nameId,valueId,method){
					
					var HTML="";
					var _valueId='#'+valueId;

					if(flag=="requestCategoryNo"){
						
						
						HTML="<input id="+nameId+" style='width:100px;cursor:pointer;color:#555555' onclick=itsm.rules.ruleCM.selectRequestCategory('#"+valueId+"','#"+nameId+"') readonly/><input type='hidden' id='"+valueId+"' />";
						
					}else if(flag=="priorityNo"||flag=="seriousnessNo"||flag=="effectRangeNo"||flag=="levelNo"||flag=="imodeNo"||flag=="statusNo"){
						
						HTML="<select id='"+valueId+"' style='width:100px'></select>";
						flag=flag.replace(/No/g,''); 
						if(flag=='status'){
							flag='requestStatus';
						}
						itsm.config.dataDictionary.dataDictionaryUtil.loadOptionsByCode(flag,_valueId);
						
	
					}else if(flag=="createdByNo" || flag=="assigneeNo" ||  flag=="approvalNo" ){
						HTML="<input id='"+nameId+"' style='width:100px;cursor:pointer;color:#555555' value='"+i18n['msg_chooseUser']+"' onclick=itsm.security.userUtil.selectUser('#"+nameId+"','#"+valueId+"','','loginName') readonly/><input type='hidden' id='"+valueId+"' />";
					}
					else if(flag=="servicesNo" ||flag=="assigneeGroupNo"){		
						
						HTML="<input id='"+nameId+"' style='width:100%;cursor:pointer;color:#555555' onclick='"+method+"' readonly/><input type='hidden' id='"+valueId+"' />";
					}
					else if(flag=="updateLevelNo"){
						
						HTML="<select id='"+valueId+"' style='width:100px'></select>";
						itsm.rules.ruleCM.loadUpdateLevel('#'+valueId);
					}
					
					else{
						HTML="<input style='width:100px' id='"+valueId+"' />";
					}
					
					$(htmlPut).html(HTML);
				},
				
				/**
				 * 获取显示值.
				 */
				getRuleTitle:function(flagId,valueId,nameId){
					
					var flag=$(flagId).val();

					if(flag=="priorityNo"||flag=="seriousnessNo"||flag=="effectRangeNo"||flag=="levelNo"||flag=="imodeNo"||flag=="statusNo" || flag=="updateLevelNo"){
						
						return $(valueId).find("option:selected").text()
					}		
					if(flag=="etitle"||flag=="edesc"){
						return $(valueId).val()
					}

					if(flag=="createdByNo" || flag=="requestCategoryNo" || flag=="assigneeNo"||flag=="approvalNo"||flag=="servicesNo"||flag=="assigneeGroupNo"){					
						return $(nameId).val();
					}
				},
				
				/**
				 * 保存规则公共方法（请求规则）.
				 */
				saveRuleCommon:function(panelDIV,flag,andId){
					
					var rule = itsm.rules.ruleCM.getRuleInfo(panelDIV,andId,'requestRule');	
					var url= "callBusinessRuleSet!"+flag+".action";
					
					startProcess();//开始进程
					$.post(url,rule,function(){
						endProcess();//结束进程
						
						itsm.rules.ruleCM.showRuleList('1');//返回请求列表
						
						//显示消息
						if(flag=="merge"){		
							msgShow(i18n['label_rule_editSuccessful'],'show');
						}else{
							msgShow(i18n['msg_add_successful'],'show');
						}
					});				
				},
				
				
				/**
				 * 获取规则相关属性.
				 */
				getRuleInfo:function(panelDIV,andId,flag){
									
					var rule = $(panelDIV+' form').getForm();
					var andOr="or";
					
					if($(andId).attr("checked")==true){
						andOr="and";
					}
					
					var constraintsProps = {};
					var constraintsNames = $(panelDIV+' form input[name="rule_condition_constraints_propertyName"]');
					var constraintsNos = $(panelDIV+' form input[name="rule_condition_constraints_conNo"]');
					var constraintsValues = $(panelDIV+' form input[name="rule_condition_constraints_propertyValue"]');
					var constraintsValueNames = $(panelDIV+' form input[name="rule_condition_constraints_propertyValueName"]');
					var constraintsDataTypes = $(panelDIV+' form input[name="rule_condition_constraints_dataType"]');
	
					for (i =0; i<constraintsNames.length; i++) {
						
						constraintsProps['rule.condition.constraints['+i+'].conNo'] = constraintsNos[i].value;
						constraintsProps['rule.condition.constraints['+i+'].propertyName'] = constraintsNames[i].value;
						constraintsProps['rule.condition.constraints['+i+'].propertyValue'] = constraintsValues[i].value;
						constraintsProps['rule.condition.constraints['+i+'].propertyValueName'] = constraintsValueNames[i].value;			
						constraintsProps['rule.condition.constraints['+i+'].dataType'] =constraintsDataTypes[i].value;
						constraintsProps['rule.condition.constraints['+i+'].andOr'] =andOr;
						constraintsProps['rule.condition.constraints['+i+'].sequence'] = (i+1);
					}
					$.extend(rule, constraintsProps);
					
					var actionsProps = {};
					
					if(flag=="sla"){
						actionsProps['rule.actions[0].propertyName']="matchRuleName";
						actionsProps['rule.actions[0].givenValue']=$('#rule_ruleName').val();
						actionsProps['rule.actions[0].dataType']="String";
						actionsProps['rule.actions[0].sequence']= 1;
						
					}else{
						var actionsNames = $(panelDIV+' form input[name="rule_actions_propertyName"]');
						var actionsValues = $(panelDIV+' form input[name="rule_actions_givenValue"]');
						var actionsNos = $(panelDIV+' form input[name="rule_actions_actionNo"]');
						var actionsDataTypes = $(panelDIV+' form input[name="rule_actions_dataType"]');
						var actionsGivenNames = $(panelDIV+' form input[name="rule_actions_givenName"]');

						for(j=0;j<actionsNames.length;j++){
							
							actionsProps['rule.actions['+j+'].propertyName']=actionsNames[j].value;
							actionsProps['rule.actions['+j+'].givenValue']=actionsValues[j].value;
							actionsProps['rule.actions['+j+'].givenName']=actionsGivenNames[j].value;
							actionsProps['rule.actions['+j+'].dataType']=actionsDataTypes[j].value;
							actionsProps['rule.actions['+j+'].sequence']= (j+1);
						}
					}
				
					$.extend(rule,actionsProps);
					
					
					return rule;
				}
				
				
				

			
		};
	 

}();
