$(document).ready(function() {
	function calculateData() {
		getDataJson();
		$.ajax({
			url : "/quotationManagement/calculateIrr",
			data : allJson,
			type : 'post',
			async : true,
			success : function(data) {
				if (data) {
					if (data.success == false || data.code == '500') {
						layer.msg(data.msg, { icon : 0 });// 提示信息
					} else {
						$("#quotationResult").html(data);
						$("#quotationForm").find(".toDataJson").each(function(){
							var thisoptions= $(this).find("option").length;
							if(thisoptions){
								inputarr.push($(this).find("option:selected").text());
							}else {
								var thisvalue=$(this).val();
								inputarr.push(thisvalue);
							}
						})
						
					}
				}
			},
			error : function(XMLHttpRequest, textStatus, errorThrown) {
				sxUtil.msgbox.error(textStatus, "数据不符合实际导致irr计算报错~");
			}
		});
	}
	var flag=true;
	var inputarr=[];
	$(".quote_calculatebtn").bind("click", function() {
		inputarr.length=0;
		if ($("#quotationForm").valid()) {// 表单校验通过
			if(irrFlag){
				allJson = "";// 先清空数据，防止未重置，重复点击计算，拼接的重复数据传到后台
				calculateData();
			}else{
				layer.msg("请输入正确的IRR百分数，最多保留两位小数");
			}
		}
	});

	// 重置
	$(".quote_resetbtn").bind("click", function() {
		$(".quote_caculate_resultbox").empty().css({"display":"none"});
		$(".quote_caculate_resultbox .table").empty();
	});
	
	var irrFlag = true;
	$(".quote_caculate_resultbox").on("blur","[name='strCorrectIrr']",function(){
		if( $(this).val()!="" ){
			var patt = new RegExp( /^(100|[1-9]?\d(\.\d\d?)?)%$/);
			if( patt.test($(this).val()) ){
				irrFlag = true;
			}else{
				irrFlag = false;
				layer.msg("请输入正确的IRR百分数，最多保留两位小数");
			}
		}else{
			irrFlag = true;
		}
	})
	
	$("#quotationForm").validate({
		promptPosition : "bottomLeft",
		submitHandler : function(form) {
			if( !irrFlag ){
				return;
			}
		
			if(inputarr.length!=0){
				var arrlength=inputarr.length;
				$("#quotationForm").find(".toDataJson").each(function(i){
					var thisoptions= $(this).find("option").length;
					if(thisoptions){
						var optiontext=$(this).find("option:selected").text();
						if(optiontext!=inputarr[i]){
							flag=false
						}
					}else {
						var inputtext=$(this).val();
						if(inputtext!=inputarr[i]){
							flag=false
						}
					}
					if(i>arrlength){
						flag=false;	
					}
				})
			}else {
				flag=false;
			}
			
			if(!judgeAdd()){
				return;
			}
			if(flag){
				$(form).ajaxSubmit({
					success : function(e) {
						if (e && e.success == true) {
							$("#quotationList").trigger("reloadGrid");
							sxUtil.msgbox.success('操作成功！');
							sxUtil.dialog.close($(form).data('index'));
						} else {
							sxUtil.msgbox.error(e, '新增失败');
						}
					},
					error : function(XMLHttpRequest, textStatus, errorThrown) {
						sxUtil.msgbox.error(textStatus, "新增融资报价失败！");
					}
				});
			}else {
				layer.msg("数据已更改，请重新点击“计算”！");
				flag=true;
				return
			}
		},
		rules : {
			'financingAmount' : {
				required : true
			},
			'currency.id' : {
				required : true
			},
			'month' : {
				required : true,
				positiveInteger : true
			},
			'strAnnualRate' : {
				required : true,
				percentage : true
			},
			'prepaid.id' : {
				required : true
			},
			'settleInterest.id' : {
				required : true
			},
			'repayment.id' : {
				required : true
			},
			'interestTerm' : {
				positiveInteger : true
			},
			'interval' : {
				positiveInteger : true
			},
			'actualDays' : {
				positiveInteger : true
			},
			'yearDays' : {
				positiveInteger : true
			}
		},
		messages : {
			'financingAmount' : {
				required : "请输入融资总额"
			},
			'currency.id' : {
				required : "请选择币种"
			},
			'month' : {
				required : "请输入融资期限（月）",
				positiveInteger : "请输入正整数"
			},
			'strAnnualRate' : {
				required : "请输入年利率",
				percentage : "请输入正确的百分数，以%结尾，且小数点最多精确到两位"
			},
			'prepaid.id' : {
				required : "请输入还款方式"
			},
			'settleInterest.id' : {
				required : "请输入还款方式"
			},
			'repayment.id' : {
				required : "请输入还款方式"
			},
			'interestTerm' : {
				positiveInteger : "请输入正整数"
			},
			'interval' : {
				positiveInteger : "请输入正整数"
			},
			'actualDays' : {
				positiveInteger : "请输入正整数"
			},
			'yearDays' : {
				positiveInteger : "请输入正整数"
			}
		}
	});

	// 融资期限与还款方式限制
	$("input[name='month']").blur(function() {
		var monthresult = $(this).val();
		$("select[name^='settleInterest']").find("option").each(function(i) {
			var flag = false;
			if (i == 1) {
				if ((monthresult < i) || (monthresult % 1 != 0)) {
					flag = true;
				}
			} else if (i == 2) {
				if ((monthresult < i) || (monthresult % 3 != 0)) {
					flag = true;
				}
			} else if (i == 3) {
				if ((monthresult < i) || (monthresult % 6 != 0)) {
					flag = true;
				}
			} else if (i == 4) {
				if ((monthresult < i) || (monthresult % 12 != 0)) {
					flag = true;
				}
			}
			flag == true ? $(this).attr("disabled", true).css({
				"backgroundColor" : "#ccc"
			}) : $(this).attr("disabled", false).css({
				"backgroundColor" : "white"
			});
		})
	});
});

function repaymentChange(repaymentId) {
	var afterPrincipal = $("#afterPrincipalId").val();
	if (undefined != afterPrincipal && undefined != repaymentId
			&& '' != repaymentId && repaymentId == afterPrincipal) {
		$("#afterPrincipal input").prop("disabled", false);
		$("#daysOccupied input").prop("disabled", false);
		$("#afterPrincipal input").attr("class", "toDataJson");
		$("#daysOccupied input").attr("class", "toDataJson");
		$("#afterPrincipal").css("display", "block");
		$("#daysOccupied").css("display", "block");
		$("#buttonLocation").css("display","none");
	} else {
		$("#afterPrincipal input").val("").prop("disabled", true);
		$("#daysOccupied input").val("").prop("disabled", true);
		$("#afterPrincipal input").removeClass("toDataJson");
		$("#daysOccupied input").removeClass("toDataJson");
		$("#afterPrincipal").css("display", "none");
		$("#daysOccupied").css("display", "none");
		$("#buttonLocation").css("display","block");
	}
}

var allJson = "";
function getDataJson() {
	var all_tdInput = $(".toDataJson");
	var name;
	var value;
	$.each(all_tdInput, function(i) {
		name = $(all_tdInput[i]).attr("name");
		value = $(all_tdInput[i]).val();
		allJson = allJson + name + "=" + value + "&";
	});
	allJson = allJson + "yearDays=" + $("[name='yearDays']:checked").val() + "&";
	allJson = allJson + "marginFlag=" + $("[name='marginFlag']:checked").val() + "&";
	allJson = allJson.replace(/%/g, "%25");// 注意：特殊字符百分号替换
}

function actualNetCash(selfDoc) {
	var value = selfDoc.val();
	var v =selfDoc.val();
	if (undefined != v && '' != v) {// 防止输入空字符串格式化返回NaN
		var x = v.split(',');
		if(x[0]=="-"){
			var newx=[];
			for(var i=1;i<x.length;i++){
				newx.push(x[i])
			}
			x=newx;
			if(x.length>0){
				var returnV = parseFloat(x.join(""));
				value = "-"+returnV;
			}else{				
				value = 0;
			}
		}else{
			var value = parseFloat(x.join(""));
		}
	}
	var name = selfDoc.attr("name");
	name_last=name.split(".")[1];
	name = name.split(".")[0];
	
	var principalName = name + ".perPeriodPrincipalInterest";
	var netCashName = name + ".actualNetCash";
	var perprincipalName=name+".perPeriodPrincipal";
	var perinterestName=name+".perPeriodInterest";
	var cashFlowAdjustName=name+".cashFlowAdjust";
	if (value == "" || isNaN(value)) {
		value = 0;
	}
	var perPeriod = selfDoc.parent().parent().find("[name='"+principalName+"']").val();
	if(perPeriod==''){perPeriod=0}
	var tdInput = selfDoc.parent().parent().find("[name='"+netCashName+"']");
	if(name_last=="perPeriodPrincipal"){
		var perInterestVal=selfDoc.parent().parent().find("[name='"+perinterestName+"']").val();
		if(perInterestVal==''){perInterestVal=0}
		var tdInput1=selfDoc.parent().parent().find("[name='"+principalName+"']");
		var flowAdjustVal=selfDoc.parent().parent().find("[name='"+cashFlowAdjustName+"']").val();
		if(flowAdjustVal==''){flowAdjustVal=0}
		tdInput1.val(perInterestVal*1+value*1);
		tdInput.val((tdInput1.val() - flowAdjustVal).toFixed(2));
	}else if(name_last=="perPeriodInterest"){
		var perPrincipalVal=selfDoc.parent().parent().find("[name='"+perprincipalName+"']").val();
		if(perPrincipalVal==''){perPrincipalVal=0}
		var tdInput2=selfDoc.parent().parent().find("[name='"+principalName+"']");
		var flowAdjustVal=selfDoc.parent().parent().find("[name='"+cashFlowAdjustName+"']").val();
		if(flowAdjustVal==''){flowAdjustVal=0}			
		tdInput2.val((perPrincipalVal*1 + value*1).toFixed(2));		
		tdInput.val((tdInput2.val() - flowAdjustVal).toFixed(2));	
	}else if(name_last=="cashFlowAdjust"){		
		tdInput.val((perPeriod - value).toFixed(2));
	}
}
$(".quote_caculate_resultbox").off("keyup").on("keyup",".bindCashFlowAdjust,.bindPerPeriodPrincipal,.bindPerPeriodInterest",function(){
	if (window.event.keyCode != 13) {
		actualNetCash($(this));
	}
});

/**
 * 提交之前判断数据是否可新增
 * @returns
 */
function judgeAdd(){
	var falg=false;
	$.ajax({
		url:'/quotationManagement/do_judgeAdd',
		async:false,
		data:$("#quotationForm").serializeArray(),
		success:function(data){
			if(data&&data.success==false){
				layer.msg(data.msg, {icon: 0});
				falg=false;
			}else{
				falg=true;
			}
		}
	});
	return falg;
}
