define(function(require,exports) {
	//加载JS库
	var $ = require('jquery');
	var IFA = require('util');
	require('../../../js/seaJsExtends/autoComplete.js')($);
	require('../../../styles/cim/autoComplete.css');
	var params = seajs.params;	
	var compayCdpId = $("#compayCdpId").val();
	exports.checkIsSameAmount = checkIsSameAmount;
	$(function(){
		loadPayments();
		$("#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(Number($(this).val()))){
				calTotalAmount();
			}
		});
		
		
		hotKeyCompany();
		
	});
	
	
	function calTotalAmount(){
		var total = Number(0.00);
		$("input[data='paymentAmount']").each(function(){
			total += Number($(this).val());
		});
		$("#payAmountEdit").text(total.toFixed(2));
	}
	
	var paymentsObjs = {};
	var payments_len = 0;
	var payments_his = {};
	function loadPayments(){
		var url1 = $("#paymentTypesUrl").val();
		$.get(url1,
			function(data){
				var sel = $("#payTypeTemplate");
				var payments = data.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++;
				}
				var manage = $("#paymentManageTable");
				manage.append('<tbody id="paymentManageEdit1"><tr style="border-top:2px solid black"><th><a href="#;" name="deletePayment" style="display:none">'+i18n['Entity.page.Delete']+'</a>&nbsp;'+i18n["Page.workOrder.payment"]+'<span name="showIndex">1</span></th><td  colspan="3" id="paymentSelect1"></td></tr></tbody>');
				$("#paymentSelect1").append($("#payTypeTemplate").clone());
				var sel = $("#paymentSelect1").find("select");
				sel.attr("id","paymentType1").attr("name","payments[0].paymentType");
				sel.data("prevPayMethod","");
				sel.rules("add",{required:true});
			}
		);
	}
	
	
	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(target);
			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 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 ;
			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>");
			s++;
		}
		if(s%2!=0){
			newRow.append("<th style='width:25%'></th><td style='width:25%'></td>");
		}
		fillupParams(target);
		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' >"+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.rules("add",{required:true});
		sel.data("prevPayMethod","");

	}
	/**
	 * 删除支付方式
	 */
	function removePayment(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");
						}
						
						
//						$("#settlingUnit").val(data.companyName);
//						$("#recipient").val(data.companyContact1st);
//						$("#mailingAddress").val(data.companyAddress);
						//limit(data.companyId);
					});
		}
		});
	}
	/**
	 * 判断付款方式的总价和费用估计是否一致
	 */
	function checkIsSameAmount(){
		var v1 = Number($("#revenue").val());
		var v2 = Number($("#payAmountEdit").text());
		if(v1!=v2){
			$.msg.alert(i18n["JS.workOrder.ultimateNotEqual"]);
		}
		return v1==v2?true:false;
	}
});