define(function(require){
	var $ = require('jquery');
	require('grid')($);
    require('uriTemplate')($);
    require('dialog')($);
    require('datepicker')($);
    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('../../../styles/cim/autoComplete.css');
	require('../../../js/seaJsExtends/autoComplete.js')($);
	$(function(){
		hotKeyCompany();
		search();
		$("#searchBtn").bind("click",function(){
			if($('#searchForm').valid()){
				if($('#companyCdp').val()==""){
					$('#companyId').attr('value',"");
				}
				search();
			}else{
				$.msg.alert(i18n["Page.Dialog.content.inputError"]);
			}
		});
		$("#newBtn").bind("click",function(){
			location.href=$("#newUrl").val().trim();
		});
		//$("#delete").click(function(){batchDelete();});
		$("#searchForm :input").bind("keydown",function(e){
			var e = e ? e : window.event;
			if(e.keyCode==13){
				if($('#searchForm').valid()){
					search();
				}else{
					$.msg.alert(i18n["Page.Dialog.content.inputError"]);
				}
			}
		});
		$('#searchForm').validate({
			rules:{
				startBillingAmount:{
					regex:/^[+|-]?\d*\.?\d*$/
				},
				endBillingAmount:{
					regex:/^[+|-]?\d*\.?\d*$/
				}
			},
			messages:{
				startBillingAmount:{
					regex:i18n["Validation.billing.billingAmount"]
				},
				endBillingAmount:{
					regex:i18n["Validation.billing.billingAmount"]
				}
			}
		});
	});

	function search(){
		var contact = $("#contact").val();
		var url=$("#searchUrl").val().trim();
		$("#billList").grid({
			url:url,
			root:"billingList",
			pageTheme:'Theme1',
			isREST :false,
			method:"POST",
			defaultParams:{billingTitle:$('#billingTitle').val(),billingStatus:$('#billingStatus').val(),startDate:$('#startDate').val(),
				endDate:$('#endDate').val(),startBillingAmount:$('#startBillingAmount').val(),endBillingAmount:$('#endBillingAmount').val(),modifierName:$('#modifierName').val(),companyId:$('#companyId').val(),contact:contact},
			fields:[
			        //{id:"billingId",type:"checkbox",style:{width:"5%"}},
			        {name:i18n["Entity.billing.title"],style:{width:"10%"},id:"billingTitle",render:function(data){
					    var billName='';
		                var dataName=data.billingTitle;
		                if(dataName.length>10){
		                	billName=dataName.substring(0,10)+"...";
		                }else{
		                	billName=dataName;
		                    }
		 			    //return billName;
		 			    return $('<a href="#" title='+data.billingTitle+' class="bb"/>').html(billName).click(function(){
		  				    showDetail(data);
		     			    });
			        }},
			        {name:i18ns("Entity.billing.raCount"),style:{width:"8%"},id:"raCount"},
			        {name:i18n["Entity.billing.arAmount"],style:{width:"8%"},id:"arAmount"},
			        {name:i18ns("Entity.billing.partAmount"),style:{width:"8%"},id:"partAmount"},
			        {name:i18n["Entity.billing.billingAmount"],style:{width:"8%"},id:"billingAmount"},
			        {name:i18ns("Entity.billing.beenPaidAmount"),style:{width:"10%"},style:{width:"8%"},id:"paymentAmount"},
			        {name:i18n["Entity.billing.status"],style:{width:"8%"},id:"billingStatus",options:{'0':i18n["Entity.billing.status.unbilling"],'1':i18n["Entity.billing.status.unpaid"],'2':i18n["Entity.billing.status.paid"]}},
			        {name:i18n["Entity.billing.creatorName"],style:{width:"10%"},id:"creatorName"},
			        {name:i18n["Entity.billing.creatorDate"],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:i18n["Entity.Operation"],style:{width:"20%"},operation:[
			                                                  {text:i18n["Entity.Operation.edit"],display:function(data){
			                                                	  return data.billingStatus!=2?true:false;
			                                                  },action:function(data){
			                                                	  editBill(data.billingId);
			                                                  }},
			                                                  {text:i18n["Entity.Operation.billing"],display:function(data){
			                                                	  return (data.billingStatus==0&&data.raCount>0)?true:false;
			                                                  },action:function(data){
			                                                	  toBilling(data);
			                                                  }},
			                                                  {text:i18ns("Entity.billing.invoiceAgain"),display:function(data){
			                                                	  return (data.billingStatus==1)?true:false;
			                                                  },action:function(data){
			                                                	  toEditBilling(data);
			                                                  }},
			                                                  {text:i18n["Entity.Operation.payment"],display:function(data){
			                                                	  return (data.billingStatus==1)?true:false;
			                                                  },action:function(data){
			                                                	  payment(data);
			                                                  }},
			                                                  {text:i18n["Entity.Operation.export"],display:true,action:function(data){
			                                                	  exportBill(data.billingId);
			                                                  }},
			                                                  {text:i18n["Entity.Operation.audits"],display:true,action:function(data){
			                                                	  audits(data.billingId);
			                                                  }},
			                                                  {text:i18ns("Entity.customer.close"),display:function(data){
			                                                	  return (data.billingStatus==1&&data.paymentAmount!=0)?true:false;
			                                                  },action:function(data){
			                                                	  closedBilling(data);
			                                                  }},
			                                                  {text:i18n["Entity.Operation.delete"],display:function(data){
			                                                	  return (data.billingStatus!=2&&data.paymentAmount==0)?true:false;
			                                                  },confirm: i18n["Entity.billing.confirmdelete"],action:function(data){
			                                                		var obj = this;
			                                    					var id = data.billingId;
			                                    					var urlVal = $('#deleteUrl').val();
			                                    					var urlParam = {"id":id,'_method':'DELETE'};
			                                    					$.ajax({
			                                    						type:"POST",
			                                    						url: urlVal,
			                                    					    data:urlParam,
			                                    						dataType:"json",
			                                    						timeout:5000,
			                                    						success:function(response){
			                                                             if(response.flag)
			                                                             {
			                                                                $.msg.alert(i18n["Page.billing.dialogshow.title"],i18n["Entity.billing.deletesuccessfully"],function(){obj.refresh();});}
			                                    					    },
			                                    						error:function(response){
			                                    							return response;}
			                                    				    });	
			                                                  }}
			                                                  ]}
			        ]
			});
	}
	
	//注销批量删除功能
//	  function batchDelete(){
//		  	var ids = getCheckedVals();
//		  	if(ids.length==0){
//		  		$.msg.alert(i18n["Page.billing.dialogshow.title"],i18n["Page.warnning.tips"],{
//		  			    buttons:
//		  			    	IFA.generateJson(i18n["Entity.Operation.ok"],function(){
//		                           $(this).dialog("close");
//		                      }
//		  		        ),
//		  		        width:350,height:150
//		  			});
//		  	}else{
//		  		$.msg.alert(i18n["Page.billing.dialogshow.title"],i18n["Page.warnning.tips"],{
//		  			buttons:IFA.generateJson(i18n["Entity.page.YES"],function(){
//		             	var urlVal = $('#deleteUrl').val();
//	   					var urlParam = {"id":ids,'_method':'DELETE'};
//	   					$.ajax({
//	   						type:"POST",
//	   						url: urlVal,
//	   					    data:urlParam,
//	   						dataType:"json",
//	   						timeout:5000,
//	   						success:function(response){
//	                            if(response.flag)
//	                            {
//	                               $.msg.alert(i18n["Page.billing.dialogshow.title"],i18n["Entity.billing.deletesuccessfully"],function(){search();});}
//	   					    },
//	   						error:function(response){
//	   							return response;}
//	   				    });	
//	   					$(this).dialog("close");
//				       },
//				       i18n["Entity.page.No"],function() {
//				         	$(this).dialog("close");
//					       }
//		  		)});
//		  	}
//		  }
	  
	    
	  
		function getCheckedVals(){
			var checkVal = "";
			$(":checkbox[name='billingId'][checked]").each(		
					function(i) {
						checkVal += $(this).val();
						checkVal +=",";
					}
				);
			return checkVal.substring(0,checkVal.length-1);
		}
		
		function editBill(id){
		      var urlVal = $('#editUrl').val();
		      var urlStr = new $.Template(urlVal);
			  var urlParam = {"id":id};
			  var url = urlStr.expand(urlParam);	
		      location.replace(url);	
		}
		function toBilling(data){
			var billingId = data.billingId;
//			var billAmount = prompt(i18n["Entity.billing.inputBillingArmount"],data.arAmount);
//			if(billAmount!=null&&billAmount!=""){
//				var url = $('#billingUrl').val().trim();
//			    $.ajax({
//			    	type:"POST",
//			    	url:url,
//					async:false,
//			    	data:{"billingId":billingId,"billingAmount":billAmount},
//				    success: function(response,ioArgs){
//				    	if(response.successful){				    		
//				    		search();
//				    	}
//				   	},error:function(response,ioArgs){
//				   		alert(ioArgs);
//				   	}
//			   	});
//			}
			$.msg.confirm(i18ns("Page.billing.dialogshow.title"),$('#template'),function(result){
				if(result){
					var invoiceNo = $('#invoiceNo').val().trim();
					var billingAmount = $('#billingAmount').val().trim();
					var arAmount = data.arAmount;
					var arAmountString = "<font color='red'>"+i18ns("Entity.billing.invoiceAmountdefault")+":"+"&nbsp;&nbsp;"+arAmount+"&nbsp;&nbsp;"+"RMB?";
					if(invoiceNo==null||invoiceNo==""){
						$.msg.alert(i18ns("Entity.billing.enterInvoiceNumber"));
					}else{						
						if(billingAmount==null||billingAmount==""){
							$.msg.confirm(i18ns("Page.billing.dialogshow.title"),arAmountString,function(result){
								if(result){									
									billingAmount=arAmount;
									billing(billingId,invoiceNo,billingAmount);
								}else{
									billingAmount = prompt(i18n["Entity.billing.inputBillingArmount"],data.arAmount);
									if(billingAmount!=null&&billingAmount!=""){
										billing(billingId,invoiceNo,billingAmount);
									}
								}
							});
						}else{
							billing(billingId,invoiceNo,billingAmount);
						}
					}
				}
			});
		}
		function payment(data){
			$('#bAmount').text(data.billingAmount+" RMB");
			$('#pAmount').text(data.paymentAmount+" RMB");
			//var string = i18n["Entity.billing.bill"]+data.billingTitle+"(Id:"+data.billingId+")"+i18n["Entity.billing.isbillingamount"] +data.billingAmount+i18n["Entity.billing.yuan"]+i18n["Entity.billing.surepaid"];
			$.msg.alert(i18n["Entity.billing.confirminfo"],$('#paymentTemplate'),{
				buttons:IFA.generateJson(i18n["Entity.page.YES"],function(){
						    var id = data.billingId;
						    var paymentNo = $('#paymentNo').val().trim();
						    var paymentAmount = $('#paymentAmount').val().trim();
							var url = $('#payUrl').val().trim();
							$.ajax({
								type:"POST",
								url:url,
								async:false,
								data:{"billingId":id,"paymentNo":paymentNo,"paymentAmount":paymentAmount},
								success:function(response,ioArgs){
									if(response.paid){
										search();
									}
								},error:function(response,ioArgs){
							   		alert(ioArgs);
							   	}
							});
		   					$(this).dialog("close");
					       },
					       i18n["Entity.page.No"],function() {
					         	$(this).dialog("close");
						       }
				)
			});
		}
		
		function audits(id){
		      var urlVal = $('#auditUrl').val().trim();
		      var urlStr = new $.Template(urlVal);
			  var urlParam = {"id":id};
			  var url = urlStr.expand(urlParam);	
		      location.replace(url);
		}
		function exportBill(id){
			var urlVal = $('#exportUrl').val().trim();
			var urlStr = new $.Template(urlVal);
			var urlPar = {"id":id};
			var url = urlStr.expand(urlPar);
			location.href = url;
		}
		function toEditBilling(data){
			var billingId = data.billingId;
			$('#invoiceNo').val(data.invoiceNo);
			$('#billingAmount').val(data.billingAmount);
			$.msg.confirm(i18ns("Page.billing.dialogshow.title"),$('#template'),function(result){
				if(result){
					var invoiceNo = $('#invoiceNo').val().trim();
					var billingAmount = $('#billingAmount').val().trim();
					var arAmount = data.arAmount;
					var arAmountString = "<font color='red'>"+i18ns("Entity.billing.invoiceAmountdefault")+":"+"&nbsp;&nbsp;"+arAmount+"&nbsp;&nbsp;"+"RMB?";
					if(invoiceNo==null||invoiceNo==""){
						$.msg.alert(i18ns("Entity.billing.enterInvoiceNumber"));
					}else{						
						if(billingAmount==null||billingAmount==""){
							$.msg.confirm(i18ns("Page.billing.dialogshow.title"),arAmountString,function(result){
								if(result){									
									billingAmount=arAmount;
									if(invoiceNo!=data.invoiceNo){											
										editBilling(billingId,invoiceNo,billingAmount);
									}else{
										$.msg.alert(i18ns("Entity.billing.changeinvoiceNum"));
									}
								}else{
									billingAmount = prompt(i18n["Entity.billing.inputBillingArmount"],data.arAmount);
									if(billingAmount!=null&&billingAmount!=""){
										if(invoiceNo!=data.invoiceNo){											
											editBilling(billingId,invoiceNo,billingAmount);
										}else{
											$.msg.alert(i18ns("Entity.billing.changeinvoiceNum"));
										}
									}
								}
							});
						}else{
							if(invoiceNo!=data.invoiceNo){											
								editBilling(billingId,invoiceNo,billingAmount);
							}else{
								$.msg.alert(i18ns("Entity.billing.changeinvoiceNum"));
							}
						}
					}
				}
			});
		}
		
		//开票
		function billing(billingId,invoiceNo,billingAmount){
			var url = $('#billingUrl').val().trim();
		    $.ajax({
		    	type:"POST",
		    	url:url,
				async:false,
		    	data:{"billingId":billingId,"invoiceNo":invoiceNo,"billingAmount":billingAmount},
			    success: function(response,ioArgs){
			    	if(response.successful){				    		
			    		search();
			    	}
			   	},error:function(response,ioArgs){
			   		alert(ioArgs);
			   	}
		   	});
		}
		
		//再次开票
		function editBilling(billingId,invoiceNo,billingAmount){
			//var url = $('#editBillingUrl').val().trim();
			var url = $('#billingUrl').val().trim();
		    $.ajax({
		    	type:"POST",
		    	url:url,
				async:false,
		    	data:{"billingId":billingId,"invoiceNo":invoiceNo,"billingAmount":billingAmount},
			    success: function(response,ioArgs){
			    	if(response.successful){				    		
			    		search();
			    	}
			   	},error:function(response,ioArgs){
			   		alert(ioArgs);
			   	}
		   	});
		}
	    $("#startDate").datepicker({
		});
	    $("#endDate").datepicker({
		});
	    
	    //公司热键
		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);
							showContact(data.companyId);
						});
			}
			});
		}
		
		$("#addContact").bind("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);
		});
		
		function showContact(personId){
			var url = $('#showContactUrl').val();
			$.get(url,{"personId":personId},function(data){
				var personProfile = data.personProfile;
				$("#personId").attr("value",personId);
				if(personProfile.cnName!=null&&personProfile.cnName!=""){				
					$("#personName").val(personProfile.en1stName+personProfile.enLstName+personProfile.cnName);
				}else{
					$("#personName").val(personProfile.en1stName+personProfile.enLstName);
				}
			});
		}
		
		function showDetail(data){
			var id = data.billingId;
		    var hiddenUrl = $('#detailUrl').val();
			var urlStr = new $.Template(hiddenUrl);
			var urlParam = {"id":id};
			var url = urlStr.expand(urlParam);	
		    location.replace(url);	
		}
		//关闭账单
		function closedBilling(data){
			var url = $("#closedBillingUrl").val();
			$.msg.confirm(i18ns("Page.billing.dialogshow.title"),"<font color='red'>"+i18ns("Entity.billing.closebill")+"</BR></BR>"+i18ns("Entity.billing.closedPaid"),function(result){
				if(result){
					var StringTips =i18ns("Entity.billing.arAmount")+":"+data.arAmount+"&nbsp;&nbsp;"+i18ns("Entity.billing.billingAmount")+":"+data.billingAmount+"&nbsp;&nbsp;"+i18ns("Entity.billing.paymentAmount")+":"+data.paymentAmount+"&nbsp;&nbsp;</BR></BR>"+i18ns("Entity.billing.closebill");
					if(data.billingAmount<data.arAmount){
						StringTips = "<font color='red'>"+i18ns("Entity.billing.billingAmount")+"("+data.billingAmount+")&nbsp;&nbsp;"+i18ns("Entity.billing.lessthan")+"&nbsp;&nbsp;"+i18ns("Entity.billing.raActualCost")+"("+"&nbsp;&nbsp;"+data.arAmount+")&nbsp;&nbsp;</BR></BR>"+i18ns("Entity.billing.closebill");
					}
					if(data.paymentAmount<data.billingAmount){
						StringTips = "<font color='red'>"+i18ns("Entity.billing.paymentAmount")+"("+data.paymentAmount+")&nbsp;&nbsp;"+i18ns("Entity.billing.lessthan")+"&nbsp;&nbsp;"+i18ns("Entity.billing.billingAmount")+"("+data.billingAmount+")&nbsp;&nbsp;</BR></BR>"+i18ns("Entity.billing.closebill");
					}
					$.msg.confirm(i18ns("Page.billing.dialogshow.title"),StringTips,function(result){
						if(result){
							$.post(url,{"billingId":data.billingId},function(response){
								if(response.closed){
									search();
								}
							});
						}
					});
				}
			});
		}
});