define(function(require){
	var $ = require('jquery');
	require('grid')($);
	require('validation')($);
    require('uriTemplate')($);
    require('dialog')($);
    require('datepicker')($);
	var IFA = require('util');
	require("../../../styles/cim/jquery-ui-1.8.14.custom.css");
	require('../../../styles/cim/cim-grid.css');
	require('../../../styles/cim/validation.css');
	require('../../../js/seaJsExtends/autoComplete.js')($);
	require('../../../styles/cim/autoComplete.css');
	$(function(){		
	    hotKeyCompany();
		$('#billForm').validate({
			rules:{
				billingTitle:{
					required:true,
					maxlength:20
					//VerificationBillName:true
				},
				companyCdp:{
					required:true
				},
				billingDescription:{
					maxlength:50
				}
			}
		});
		
//      //账单标题唯一性验证
//		$.validator.addMethod("VerificationBillName:true",function(value,element,param){
//			var billingTitleVal = $('input[name=billingTitle]').val();
//			var flag = "";
//				var urlStr = $("#uniqueUrl").val();
//			    $.ajax({
//			    	type:"POST",
//			    	url:urlStr+".json",
//					async:false,
//			    	data:{"billingTitle":billingTitleVal},
//				    success: function(response,ioArgs){
//			   		    flag = response.status;
//				   	},error:function(response,ioArgs){
//				   		alert(ioArgs);
//				   	}
//			   	});
//			return flag;
//		},"账单标题不能重复");		

	var urlVal=$("#searchUrl").val().trim();
    var urlStr = new $.Template(urlVal);
	var id = $('#billingId').val();
	var ids = $('#ids').val()=="" ? $("#empty_path_variable").val() : $('#ids').val();
	//var urlParam = {"id":id,"ids":ids};
	var companyId = $("#companyId").val();
	var urlParam = {"id":id,"ids":ids,"companyId":companyId};
	var url = urlStr.expand(urlParam);
	var ralist = $("#addedRaDataList").grid({
		url:url,
		root:"addedRaList",
		pageTheme:'Theme1',
		isREST :false,
		//method:"POST",
		//defaultParams:IFA.convertQueryStringToJson($("#searchForm").serialize()),
		fields:[{id:"id",type:"checkbox",style:{width:"5%"}},
		        {name:i18ns("Entity.report.rentalno"),style:{width:"10%"},id:"rentalNo"},
		        {name:i18ns("Entity.report.clientfullname"),style:{width:"10%"},id:"personName",render:function(data){
		        	var cnName = "";
		        	var enfstName ="" ;
		        	var enlstName = "";
		        	var customerName = "";
		        	if(data.customerName!=null){
		        		cnName = data.customerName;
		        	}
		        	if(data.customerUS1stName!=null){
		        		enfstName = data.customerUS1stName;
		        	}
		        	if(data.customerUSLstName){
		        		enlstName = data.customerUSLstName;
		        	}
		        	customerName=enfstName+enlstName+cnName;
		        	return customerName;
		        }},
		        {name:i18n["Entity.billing.companyName"],style:{width:"10%"},id:"companyName",render:function(data){
				    var comName='';
	                var dataName=data.companyName;
	                if(dataName.length>10){
	                	comName=dataName.substring(0,10)+"...";
	                }else{
	                	comName=dataName;
	                    }
	 			    return comName;
		        }},
		        {name:"CDP#",style:{width:"10%"},id:"cdpNo"},
		        {name:i18ns("Page.workOrder.bankTransfer"),style:{width:"10%"},id:"charge",type:'currency'},
		        {name:i18n["Entity.billing.raActualCost"],style:{width:"10%"},id:"revenue",type:'currency'},
		        {name:i18n["Entity.billing.raCreationDate"],style:{width:"15%"},id:"creationDate",render:function(data){
  				  	var timeCheck = /^\d{4}-\d{2}-\d{2}\s+\d{2}:\d{2}$/;
  				  	if(!timeCheck.exec(data.creationDate)){
  				  		 data.creationDate = new Date(data.creationDate).format("yyyy-MM-dd hh:mm");
  				  	}
  				  	return data.creationDate;
		        }},
		        {name:i18ns("JS.workOrder.pickupTime"),style:{width:"10%"},id:"pickupDate",render:function(data){
		        	var timeCheck = /^\d{4}-\d{2}-\d{2}\s+\d{2}:\d{2}$/;
  				  	if(!timeCheck.exec(data.pickupDate)){
  				  		 data.pickupDate = new Date(data.pickupDate).format("yyyy-MM-dd hh:mm");
  				  	}
  				  	return data.pickupDate;
		        }},
		        {name:i18ns("JS.workOrder.pickOffTime"),style:{width:"10%"},id:"returnDate",render:function(data){
		        	var timeCheck = /^\d{4}-\d{2}-\d{2}\s+\d{2}:\d{2}$/;
  				  	if(!timeCheck.exec(data.returnDate)){
  				  		 data.returnDate = new Date(data.returnDate).format("yyyy-MM-dd hh:mm");
  				  	}
  				  	return data.returnDate;
		        }}
		        ],
		callback:function(response){
			var arAmount = response.billarAmount;
			$('input[name=arAmount]').attr('value',arAmount);
			$('input[name=partAmount]').attr('value',response.partAmount);
		}}
		);
	});	
	
	$("#saveBt").click(function(){
		var tempVal= getCheckeboxVals();
		$('#ids').attr("value",tempVal);
		if($('#billForm').valid()){	
			$("#billForm").submit();
		}else{
			$.msg.alert(i18n["Page.Dialog.content.inputError"]);
		}
		 return false;
	});
	
	$('#addRaBt').click(function(){
		 var id = $('#billingId').val();
		 var urlVal = $('#addRalUrl').val().trim();
	     var urlStr = new $.Template(urlVal);
		 var urlParam = {"id":id};
		 var url = urlStr.expand(urlParam);	
	     location.replace(url);
		return false;
	});
	
	//更改账单联系人
	$("#editContact").click(function(){
		if($("#companyCdp").val()==""){
			$("#companyName").val("");
		}
		var companyName = $("#companyName").val();
	    var url = $('#addContactUrl').val();
	    var data = {"companyName":companyName};
		var personId = window.showModalDialog(url,data,"dialogWidth=1000px;dialogHeight=600px");
		showContact(personId);
	});
	$('#cancelBt').click(function(){
		var url = $('#cancelUrl').val().trim();
		location.replace(url);
		return false;
	});
	$('#deleteBt').click(function(){
		 deleteRa();
	});
	function deleteRa(){
		var ids = getCheckedVals();
		if(ids.length==0){
			$.msg.alert(i18n["Page.title.dialogshow.title"],i18n["Entity.billing.tip.plzchodeletera"],{
  			    buttons:
  			    	IFA.generateJson(i18n["Entity.Operation.ok"],function(){
                           $(this).dialog("close");
                      }
  		        ),
  		        width:350,height:150
  			});
		}else{		
			$.msg.alert(i18n["Page.title.dialogshow.title"],i18n["Entity.billing.tip.deleteaddedra"],{
				buttons:IFA.generateJson(i18n["Entity.page.YES"],function(){
						$(":checkbox[name='id'][checked]").parent().parent().remove();
						$(this).dialog("close");
						var urlVal=$("#searchUrl").val().trim();
					    var urlStr = new $.Template(urlVal);
						var id = $('#empty_path_variable').val();
						var companyId = $("#companyId").val();
						var ids = getCheckeboxVals();
						var urlParam = {"id":id,"ids":ids,"companyId":companyId};
						var url = urlStr.expand(urlParam);
						ralist.setUrl(url);
						ralist.render();
						var valLength = $(":checkbox[name='id']").length;
						if(valLength==0){
							$('#ids').attr("value","");
							$('input[name=arAmount]').attr("value","0.0");
						}else{	
							var tempIds = getCheckeboxVals();
							$('#ids').attr("value",tempIds);
						}
					},
					i18n["Entity.page.No"],function(){
						$(this).dialog("close");
					}
				)
			});
		}
	}
	//显示账单联系人
	function showContact(personId){
		var url = $('#showContactUrl').val();
		$.get(url,{"personId":personId},function(data){
			var personProfile = data.personProfile;
			$("#contactTips").remove();
			$("#personId").attr("value",personId);
			if(personProfile.cnName!=null&&personProfile.cnName!=""){				
				$("#contact1Info").text(i18ns("Entity.billing.contact")+":"+personProfile.en1stName+personProfile.enLstName+"("+personProfile.cnName+")");
			}else{
				$("#contact1Info").text(i18ns("Entity.billing.contact")+":"+personProfile.en1stName+personProfile.enLstName);
			}
			
			$("#contact1PhoneInfo").text(i18ns("Entity.dealer.tel")+":"+personProfile.mobileTelephone);
			$("#contact1EmailInfo").text("Email："+personProfile.email);
		});
	}
	function getCheckedVals(){
		var checkVal = "";
		$(":checkbox[name='id'][checked]").each(		
				function(i) {
					checkVal += $(this).val();
					checkVal +=",";
				}
			);
		return checkVal.substring(0,checkVal.length-1);
	}
	function getCheckeboxVals(){
		var checkVal = "";
		$(":checkbox[name='id']").each(		
				function(i) {
					checkVal += $(this).val();
					checkVal +=",";
				}
			);
		return checkVal.substring(0,checkVal.length-1);
	}
	
	//公司热键
	function hotKeyCompany(){
	  	$.ajax({
			type:"get",
			url:$("#companyUrl").val(),
			success:function(response){
			$("#companyCdp").autocomplete(response.company,
				      {caption: "&nbsp;&nbsp;"+i18n["JS.districtHotKey.caption"],
						findCaption: "&nbsp;,"+i18n["JS.districtHotKey.findCaption"],
						noFindCaption: "&nbsp;&nbsp;"+i18n["JS.companyHotKey.noFindCaption"]+":&nbsp; ",
						max: 5,
						width: 200,
						formatItem: function(row, i, max) {
				             var cpdNo="cdpNo:"+row.cdpNo+"&#13;";
				             var companyName=i18n["JS.companyHotKey.coName"]+":"+row.companyName+"&#13;";
				             var companyHotkey=i18n["JS.companyHotKey"]+":"+row.companyHotkey+"&#13;";
				             var companyAddress=i18n["JS.companyHotKey.coAddr"]+":"+row.companyAddress+"&#13;";
				             var companyContact1st=i18n["JS.companyHotKey.coContact"]+":"+row.companyContact1st+"&#13;";
				             var title=cpdNo+companyName+companyHotkey+companyAddress+companyContact1st;
				             var companyName=row.companyName+"("+row.companyHotkey+")";
							return '<span title="{2}"><span class="ac_code" >{0}</span><span class="ac_Name">{1}</span></span>'.patchContent(row.cdpNo,companyName,title);
						},
						formatMatch: function(row, i, max) {
							return "{0} {1} {2}".patchContent(row.cdpNo,row.companyHotkey,row.companyName);
						},
						formatResult: function(row) {
							return "{0}".patchContent(row.cdpNo);
						}
					}).result(function(event, data, formatted) {
						$("#companyId").val(data.companyId);
						$("#companyName").val(data.companyName);
					});
		}
		});
	}
});