define(function(require){
	var $ = require('jquery');
	require('grid')($);
	var IFA = require('util');
	require('uriTemplate')($);
	require('validation')($);
	require('dialog')($);
	require("../../../styles/cim/jquery-ui-1.8.14.custom.css");
	require('../../../styles/cim/cim-grid.css');  
	require('../../../styles/cim/validation.css');  
	$(function(){
		searchResult();
		$("#search").bind("click",searchResult);
		$("#reset").bind("click",reset);
		$("#newUser").bind("click",function(){
			location.href=$("#userNewUrl").val().trim();
		});
		$("#userSearchForm :input").bind("keydown",function(e){
			var e = e ? e : window.event;
			if(e.keyCode==13){
			   searchResult();
			}
		});
		//验证信息
		var message="";
		//密码强度验证
		$.validator.addMethod("passwordCheck",function(value,element,params){
			var status=false;
			value=value.trim();
			$.ajax({
				type:"POST",
				url:$("#checkPswUrl").val(),
				async:false,
				data:{"psw":value},
				timeout:3000,
				success:function(response,ioArgs){
					  if(!response.lengthLess){
						  message=i18n['System.Password.LengthIncorrect1'];
					  }else if(!response.lengthMore){
						  message=i18n['System.Password.LengthIncorrect2'];
					  }else if(!response.lowCase){
						  message=i18n['System.Password.LengthIncorrect3'];
					  }else if(!response.upperCase){
						  message=i18n['System.Password.LengthIncorrect4'];
					  }else if(!response.speChar){
						  message=i18n['System.Password.LengthIncorrect5'];
					  }else if(!response.numberic){
						  message=i18n['System.Password.LengthIncorrect6'];
					  }
					 status=(response.lengthMore)&&(response.lengthLess)&&(response.lowCase)&&(response.upperCase)&&(response.speChar)&&(response.numberic);
					}
			});
			return status;
			},function(){return message;});
		$("#updatePasswordUserForm").validate({
			 rules:{
			psdIndex:{
			required:true,
		    passwordCheck:true
		},
			rePasswordUserIndex:{
			required:true,
			equalTo:"#psdIndex",
			passwordCheck:true
		}		
		},
			 messages:{
         psdIndex:{
			required:i18n['System.Password.required']
		},
         rePasswordUserIndex:{
			required:i18n['System.Password.required'],
			equalTo:i18n['System.Password.notEqual']
		}
		}
		});
	});
	//根据条件查询
	function searchResult(){
		var url=$("#queryUrl").val().trim();
		$("#searchResult").grid({
			url:url,
			root:"userList",
			isREST :false,
			pageTheme:'Theme1',
			method:"POST",
			defaultParams:IFA.convertQueryStringToJson($("#userSearchForm").serialize()),
			fields:[{name:i18n['User.Login.Name'],id:"loginName",style:{width:"10%"},render:function(data){
					    var name='';
		                var dataName=data.loginName;
		                if(dataName.length>10){
		             	    name=dataName.substring(0,10)+"...";
		                }else{
		                    name=dataName;
		                    }
		 			    return $('<a  href="#" title="'+data.name+'" class="bb"/>').html(name).click(function(){
		  				        showDetail(data.id);
		     			    });
				       }},
			        {name:i18n['User.Name'],style:{width:"10%"},id:"name"},
			        {name:i18n['Entity.Role.roleName'],render:function(data){
				        var roleList=data.roles;
				        var html="";
				        for(var i=0;i<roleList.length;i++){
				        	if(i==roleList.length-1){
				        		html+=roleList[i].name;
				        	}else{
		                        html+=roleList[i].name+"、";
		                    }
					        }
				        var roleName=html;
				        if(html.length>50){
				        	roleName="";
				        	var times=parseInt(html.length/50);
				        	for(var i=0;i<times;i++){
					        	roleName+=html.substring(i*50, (i+1)*50)+"<BR>";
				        	}
				        	roleName+=html.substring(times*50, html.length);
				        }
				        return roleName;
				        }},
			        {name:i18n['User.MobilePhone'],style:{width:"10%"},id:"mobile"},
			        {name:i18n['Entity.SystemUser.email'],style:{width:"10%"},id:"email"},
			        {name:i18n['User.Sex'],style:{width:"7%"},id:"sex",options:{0:i18n['Entity.SystemUser.sex.mail'],1:i18n['Entity.SystemUser.sex.femail']}},
			        {name:i18n['User.Status'],style:{width:"7%"},id:"available",options:{0:i18n['User.Status.Off'],1:i18n['User.Status.On']}},
			        {name:i18n['Entity.Operation'],style:{width:"16%"},operation:[
			                                                  {text:i18n['Entity.Operation.detail'],display:true,action:function(data){showDetail(data.id);}},
			                                                  {text:i18n['Entity.page.edit'],display:true,action:function(data){editUser(data.id);}},
			                                                  {text:i18n['Entity.Operation.resetPassword'],display:true,action:function(data){
			                                                removePswClass();
			                                                $.msg.confirm(i18n['System.ModifyPassword'],$('#updatePasswordUserForm'),function(){},{width:'370px',buttons: 
			                                                	IFA.generateJson(
			                                        			i18n['Entity.Operation.ok'],function() {
			                                          		if($("#updatePasswordUserForm").valid()){
			                                                	var hiddenUrl =  $('#updatePWUrl').val();
			                                                	var urlStr =  new $.Template(hiddenUrl); 
			                        						    var password = $('#psdIndex').val();
			                        						 	var urlParam = {"userId":data.id,"password":password};
			                        							var url = urlStr.expand(urlParam);
			                        							  $.ajax({
			                        									type:"get",
			                        									url : url+".json",
			                        									timeout : 5000,
			                        									success:function(response) {
			                        								    $("#updatePasswordUserForm").dialog("close");
			                        								    $.msg.alert(i18n['Page.Dialog.title'],i18n['page.tip.editSuccessfully']);
			                        							  }
			                        							  });
			                        							  
			                                                  }
			                                  				},
                                        			i18n['Entity.Operation.cancel'], function() {
		                                  				 $(this).dialog("close");
                                        	  		  })});
			                                                  }},
			                                                  {text:i18n['User.Status.On'],display:function(data){
			                                                	  return data.available==1?false:true;
			                                                  },action:function(data){enableUser(data);}},
			                                                  {text:i18n['User.Status.Off'],display:function(data){
			                                                	  return data.available==1?true:false;
			                                                  },action:function(data){enableUser(data);}}]}
			        ] 
			});
	}
	//重置查询条件
	function reset(){
		$("#loginName").val("");
		$("#userName").val("");
		$("#sex0").get(0).setAttribute("defaultChecked",true);
		$("#sex0").attr("checked",true);
		$("#mobilePhone").val("");
		$("#email").val("");
		$("#available").val("");
		//$("#userSearchForm :input").val("");
	}
	
	//显示详情
	function showDetail(userId){
		var urlTemplate=$("#detailUrl").val().trim();
		var urlString=new $.Template(urlTemplate);
		var urlParam = {"id":userId};
		var url=urlString.expand(urlParam);
		location.href=url;
	}
	
	//启用/停用 用户
	function enableUser(data){
		var message= (data.available==1?i18n['User.Available.Tips1'].patchContent(data.name):i18n['User.Available.Tips2'].patchContent(data.name));
		var status= (data.available==1?0:1);
		$.msg.confirm(message,function(result){
			if(result){
				$.ajax({
					type:"post",
					url:$("#enableUrl").val().trim(),
					async:false,
					data:{id:data.id,available:status},
					timeout:3000,
					success:function(response,ioArgs){
						$.msg.alert(i18n['Page.title.operation.successfully']);
						searchResult();
					}
				});
			}
		});
	}
	function editUser(id){
		var urlTemplate=$("#editUrl").val().trim();
		var urlString=new $.Template(urlTemplate);
		var urlParam = {"id":id};
		var url=urlString.expand(urlParam);
		location.href=url;
	}
	//去除密码样式
	function removePswClass(){
		$("#psdIndex").val("");
		$("#rePasswordUserIndex").val("");
		$("#psdIndex").parent().find("em").remove();
		$("#rePasswordUserIndex").parent().find("em").remove();
		$("#psdIndex").removeClass("ui-state-highlight");
		$("#rePasswordUserIndex").removeClass("ui-state-highlight");
	}
});

