define(function(require,exports) {
	//加载JS库
	var $ = require('jquery');
	var IFA = require('util');
	require('uriTemplate')($);
	require('globalization');
	require('../../../js/seaJsExtends/autoComplete.js')($);
	require('../../../styles/cim/autoComplete.css');
	var reservationId;
	if($("#oldId").length>0){
		reservationId=$("#oldId").val().trim();
	}
	else{
		reservationId=$("#id").val().trim();
	}
	var compayCdpId = $("#compayCdpId").length>0?$("#compayCdpId").val():undefined;
	var resStatus = $("#resStatus").length>0?$("#resStatus").val():undefined;
	var params = {};
	exports.checkIsSameAmount = checkIsSameAmount;
	$(function(){
		showPaymentDetails();
		$("#addPayment").bind('click',function(){
			var tb = $("table[id='paymentManageTable']");
			var pms = $("table[id='paymentManageTable'] >tbody");
			addPayment(tb,pms.length);
		});
		$("a[name^='deletePayment']").live('click',function(){
			removePayment(this);
		});
		$("select[id^='paymentType']").live('change',function(){
			changePaymentType($(this));
		});
		$("input[data='paymentAmount']").live('keyup',function(){
//			如果输入非法，还会以上次合法的数据计算造成计算的数据和保存到数据库的数据不一致
//			if(!isNaN(Globalize.parseFloat($(this).val()))){
				calTotalAmount();
//			}
		});
		hotKeyCompany();
	});
	

	function calTotalAmount(){
		var total = 0;
		$("input[data='paymentAmount']").each(function(){
			total += Globalize.parseFloat($(this).val());
		});
		$("#payAmountEdit").text(Globalize.format(total,'n2'));
	}
	
	var paymentsObjs = {};
	var payments_len = 0;
	var payments_his = {};
	
	/*
	 * 支付信息
	 */
	function showPaymentDetails(){
		var url1 = $("#paymentTypesUrl").val();
		var urlStr2 =new $.Template($("#paymentDetailUrl").val());
		var param = {id:reservationId};
		var url2 = urlStr2.expand(param);
		$.get(url1,function(data1){
			var sel = $("#payTypeTemplate");
			var payments = data1.payments;
			for(var index in payments){
				var payment = payments[index];
				//payments[index].value==1和银行转账强关联
				paymentsObjs[payment.value] =payment;
				var opt;
				if(payment.available==0||(payment.value =="1"&&compayCdpId&&(compayCdpId=="-1"||compayCdpId==""))){
					opt= $("<option value="+payment.value+" disabled='disabled'>"+payment.name+"</option>");
				}else{
				opt= $("<option value="+payment.value+" >"+payment.name+"</option>");
				}
				sel.append(opt);
				payments_len++;
			}
			$.get(url2,function(data2){
				var paymentDetails = data2.paymentDetails;
				var len = paymentDetails.length;
				var payAmount = 0.00;
				for(var index in paymentDetails){
					var paymentDetail = paymentDetails[index];
					var type = paymentDetail.payMethod;
					var payment = paymentsObjs[type];
					var attributes = paymentDetail.attributes;
					var manage0 = null;
					var n0 = Number(index)+1;
					var s0 = 0;
					if( $("#paymentManageShow").length>0){
					if(index==0){
						 $("#paymentManageShow").append("<tbody id='paymentManageDetail"+n0+"'></tbody>");
					}else{
						$("#paymentManageDetail"+index).after("<tbody id='paymentManageDetail"+n0+"'></tbody>");
					}
					manage0 = $("#paymentManageDetail"+n0);
					manage0.append("<tr style='border-top:2px solid black'><th style='width:25%'>"+i18n["Page.workOrder.payment"]+n0+"</th><td  colspan='3' >"+payment.name+"</td></tr>");
					var newRow0 = null;
					for(var name in attributes){
						if(s0%2==0){
						newRow0 = $("<tr></tr>");
						manage0.append(newRow0);
						}
						var valueInput = attributes[name].valueInput==null?"":attributes[name].valueInput;
						if(attributes[name].id==1){
							var NumbervalueInput = Number(valueInput);
							if(NumbervalueInput!=NaN&&NumbervalueInput){
								valueInput=Globalize.format(NumbervalueInput,'n2');
							}
						}
						newRow0.append("<th style='width:25%'>"+i18ns(attributes[name].showName)+"</th><td style='width:25%'>"+valueInput+"</td>");
						s0++;
						if(attributes[name].id==1){//与paymentAttributeType 关联
							payAmount +=Number(Globalize.parseFloat(valueInput));
						}
					}
					if(s0%2!=0){
						newRow0.append("<th style='width:25%'></th><td style='width:25%'></td>");
					}
					}
					addPaymentDetailForEditting(index,paymentDetail,len,attributes);
				}
				if($("#payAmountShow").length>0){
					$("#payAmountShow").text(Globalize.format(Number(payAmount),'n2'));
				}
				if($("#payAmountEdit").length>0){
					$("#payAmountEdit").text(Globalize.format(Number(payAmount)),'n2');
				}
				
				calTotalAmount();
			});
		});
	}
	
	/*
	 * 显示编辑信息
	 */
	function addPaymentDetailForEditting(index,paymentDetail,len,attributes){
		var n = Number(index);
		var row =n+1;
		var manage=$("#paymentManageTable");
		var tb = null;
		var s=0;
		if(manage.length>0){
		tb = $('<tbody id="paymentManageEdit'+row+'" ></tbody>');
		manage.append(tb);
		tb.append($('<tr style="border-top:2px solid black"><th><a href="#;" name="deletePayment" data="old" style="display:'+(len==1?"none":"")+'">'+i18n['Entity.page.Delete']+'</a>&nbsp;'+i18n["Page.workOrder.payment"]+'<span name="showIndex">'+row+'</span></th><td  colspan="3" id="paymentSelect'+row+'"></td></tr>'));
		$("#paymentSelect"+row).append($("#payTypeTemplate").clone());
		var sel = $("#paymentSelect"+row).find("select");
		sel.attr("id","paymentType"+row).attr("name","payments["+n+"].paymentType");
		sel.find("option[value="+paymentDetail.payMethod+"]").attr("selected","selected");
		sel.data("prevPayMethod",paymentDetail.payMethod);
		//sel.rules("add",{required:true});
		var newRow = null;
		for(var name in attributes){
			var attribute = attributes[name];
			if(s%2==0){
			newRow = $("<tr></tr>");
			tb.append(newRow);
			}
			var isneed = attribute.isNeed;
			var classz ='{required:'+(isneed==1?'true':'false'); 
			if(attribute.regexs){
				var regex = attribute.regexs ;
				regex = isneed==1?regex:regex.replace(/\/\^/,"/^$|^");
				classz+=',regex:'+regex+'}';
			}else{
				classz+='}';
			}
			var style = attribute.domStyle?attribute.domStyle:"";
			var dom ;
			var valueInput;
			if(attribute.id==1){
				 valueInput = attribute.valueInput==null?"":attribute.valueInput;
					var NumbervalueInput = Number(valueInput);
					if(NumbervalueInput!=NaN&&NumbervalueInput){
						valueInput=Globalize.format(NumbervalueInput,'n2');
					}
			}else{
				 valueInput = attribute.valueInput==null?"":attribute.valueInput;
			}
			if(attribute.domType==0){
				dom = "<input type='text' class='inputbox "+classz+"' data='"+attribute.modelName+"' name='payments["+n+"].attributes["+s+"].value' style='"+style+"' value='"+valueInput+"' />";
			}else{
				dom = "<textarea class='inputbox "+classz+"' data='"+attribute.modelName+"' name='payments["+n+"].attributes["+s+"].value' style='"+style+"'  >"+valueInput+"</textarea>";
			}
			newRow.append("<th style='width:25%'>"+(attribute.isNeed==1?"<font color='red'>*</font>":"")+i18ns(attribute.showName)+"</th><td style='width:25%'><input type='hidden' class='inputbox' name='payments["+n+"].attributes["+s+"].id' value="+attribute.id+" />"+dom+"</td>"
					+"<td ><input type='hidden' class='inputbox '  name='payments["+n+"].attributes["+s+"].encrypt' value="+attribute.encrypt+" /></td>");
			s++;
		}
		if(s%2!=0){
			newRow.append("<th style='width:25%'></th><td style='width:25%'></td>");
		}
		}
		//paymentDetail.payMethod=="1"和银行转账强关联,resStatus=5和待审核状态强关联
		if(paymentDetail.payMethod=="1"&&paymentDetail.status>=2&&resStatus&&resStatus==5){
			$("#paymentManageEdit"+row).find("select,input,textarea").attr("disabled","disabled");
		}
	}
	
	/*
	 * 支付方式变更处理
	 */
	function changePaymentType(target){
		var type = target.val();
		var ret = false;
		$("select[id^=paymentType]").each(function(){
			if(target.attr("id")!=$(this).attr("id")){
				if($(this).val()!=""&&$(this).val()==type){
					target.find("option[value="+target.data("prevPayMethod")+"]").attr("selected","selected");
					$.msg.alert(i18ns("Entity.payMethod.exist"));
					ret = true;
				}
			}
		});
		if(ret){
			return;
		}
		payments_his[target.data("prevPayMethod")]=target.parent().parent().nextAll();
		target.data("prevPayMethod",type);
		target.parent().parent().nextAll().remove();
		if(type==""){
			calTotalAmount();
			return;
		}
		if(payments_his[type]){
			target.parent().parent().after(payments_his[type]);
			fillupParams(this);
			sortPaymentManage();
			return;
		}
		var attributes = paymentsObjs[type].attributes;
		manage = $(target).parent().parent().parent();
		var newRow = null;
		var s = 0;
		for(var name in attributes){
			var attribute = attributes[name];
			if(s%2==0){
			newRow = $("<tr></tr>");
			manage.append(newRow);
			}
			var classz ='{required:'+(attribute.isNeed==1?'true':'false'); 
			if(attribute.regexs){
				classz+=',regex:'+attribute.regexs+'}';
			}else{
				classz+='}';
			}
			var style = attribute.domStyle?attribute.domStyle:"";
			var dom ;
			if(attribute.domType==0){
				dom = "<input type='text' class='inputbox "+classz+"' data='"+attribute.modelName+"' name='payments[0].attributes["+s+"].value' style='"+style+"'  />";
			}else{
				dom = "<textarea class='inputbox "+classz+"' data='"+attribute.modelName+"' name='payments[0].attributes["+s+"].value' style='"+style+"'  ></textarea>";
			}
			newRow.append("<th style='width:25%'>"+(attribute.isNeed==1?"<font color='red'>*</font>":"")+i18ns(attribute.showName)+"</th><td style='width:25%'><input type='hidden' class='inputbox'  name='payments[0].attributes["+s+"].id' value="+attribute.id+" />"+dom+"</td>"
					+"<td ><input type='hidden' class='inputbox '  name='payments[0].attributes["+s+"].encrypt' value="+attribute.encrypt+" /></td>");
			s++;
		}
		if(s%2!=0){
			newRow.append("<th style='width:25%'></th><td style='width:25%'></td>");
		}
		fillupParams(this);
		sortPaymentManage();
	}
	
	/*
	 * 填充默认的值
	 */
	function fillupParams(target){
		$(target).parent().parent().parent().find(".inputbox").each(function(){
			var item = $(this);
			var data = item.attr("data");
			if(data){
				item.val(params[data]);
			}
		});
	}
	
	
	/*
	 * 增加支付方式
	 */
	function addPayment(t,l){
		var len = l;
		if(len>payments_len){
			$.msg.alert(i18ns("Entity.payMethod.beyond"));
			return;
		}
		if(len==2){
			t.find("a[name='deletePayment']").show();
		}
		var manageTmp = $("<tbody id=paymentManageEdit"+len+">"+
						"<tr style='border-top:2px solid black'><th><a href='#;' name='deletePayment' data='fresh' >"+i18n['Entity.page.Delete']+"</a>&nbsp;&nbsp;"+i18n["Page.workOrder.payment"]+"<span name='showIndex'>"+len+"</span></th>"
						+'<td height="100px" id="paymentSelect'+len+'" colspan="3"></td>'
						+"</tr>"
						+"</tbody>");
		t.append(manageTmp);
		$("#paymentSelect"+len).append($("#payTypeTemplate").clone());
		var sel = $("#paymentSelect"+len).find("select");
		sel.attr("id","paymentType"+len).attr("name","payments["+(l-1)+"].paymentType");
		sel.data("prevPayMethod","");
		sel.rules("add",{required:true});
	}
	
	/*
	 * 删除支付方式，保留历史
	 */
	function removePayment(target){
		var data = $(target).attr("data");
		if(data=="old"){
			$.ajax({
				url:$("#paymentResDeleteUrl").val(),
				type:"POST",
				data:{_method:'DELETE'},
				success:function(){
					removePaymentHandler(target);
				},
				error:function(d1){
					if(d1.status=='403'){
						$.msg.alert(i18ns("Entity.payMethod.notRight"));
					}
				}
			});
		}else{
			removePaymentHandler(target);
		}
	}
	
	function removePaymentHandler(target){
		var sel = $(target).parent().next().children();
		payments_his[sel.val()]=sel.parent().parent().nextAll();
		$(target).parent().parent().parent().remove();
		sortPaymentManage();
	}
	
	/*
	 * 排序
	 */
	function sortPaymentManage(){
		var pms = $("tbody[id^='paymentManageEdit']");
		pms.each(function(i){
			var d = i+1;
			var obj = $(this);
			obj.attr("id","paymentManageEdit"+d);
			obj.find("td[id^='paymentSelect']").attr("id","paymentSelect"+d);
			obj.find("select[id^=paymentType]").attr("id","paymentType"+d);
			obj.find("span[name='showIndex']").html(d);
			obj.find(".inputbox").each(function(){
				$(this).attr("name",(""+$(this).attr("name")).replace(/payments\[\d+\]/,"payments["+i+"]"));
			});
		});
		if(pms.length==1){
			$(pms[0]).find("a[name='deletePayment']").hide();
		}
		calTotalAmount();
	}
	
	//公司热键
	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) {
						var v = data.companyId;
						params["settlingUnit"] = data.companyName;
						params["recipient"]=data.companyContact1st;
						params["mailingAddress"]=data.companyAddress;
						$("#companyId").val(v);
						if(v!="-1"&&v!=""){
							$("select[id^=paymentType]").each(function(){
								$(this).find("option[value=1]").removeAttr("disabled");
								fillupParams(this);
							});
							$("#payTypeTemplate").find("option[value=1]").removeAttr("disabled");
						}else{
							$("select[id^=paymentType]").each(function(){
								$(this).find("option[value=1]").attr("disabled","disabled");
								if($(this).val()==1){
									$(this).find("option[value='']").attr("selected","selected");
									changePaymentType($(this));
								}
							});
							$("#payTypeTemplate").find("option[value=1]").attr("disabled","disabled");
						}
					});
		}
		});
	}
	
	/**
	 * 判断付款方式的总价和费用估计是否一致
	 */
	function checkIsSameAmount(isNoShow){
		if(isNoShow){
			return true;
		}
		var v1 ;
		var mess;
		if(resStatus>=4){
			v1 = Globalize.parseFloat($("#totalCharges").val());
			mess = i18n["JS.workOrder.actualNotEqual"];
		}else{
			mess = i18n["JS.workOrder.ultimateNotEqual"];
			v1 = Globalize.parseFloat($("#revenue").val());
		}
		// var payAmountEdit=Number($("#payAmountEdit").text());
		var v2 = Globalize.parseFloat($("#payAmountEdit").text());
		if(v1!=v2){
		$.msg.alert(mess);
		}
		return v1==v2?true:false;
	}
	
});