var billServiceIdArray = new Array();// 账单对应的服务信息数组
var delBillServiceIdArray = new Array();// 账单对应的服务信息删除数组
var orderIdArray = new Array();// 账单-服务信息-订单详情对应数组
var delOrderIdArray = new Array();// 账单-服务信息-订单详情删除对应数组
var data;
var delServiceData;
var delOrderData;
var generalBillsDate;
$(function() {
	/**
	 * 查询
	 */
	$("#btn-search").click(function() {
		$("#conditionform").submit();
	});

	initGeneralBillsArray();
});

/**
 * 初始化账单相对应服务大类和服务订单数组
 */
function initGeneralBillsArray() {
	var billServiceId = document.getElementsByName("billServiceId");
	var orderId = document.getElementsByName("orderId");
	$.each(billServiceId, function(index, item) {
		billServiceIdArray.push(Number(item.value));
	});
	$.each(orderId, function(index, item) {
		orderIdArray.push(item.value);
	});
}

/**
 * 返回
 * 
 * @returns
 */
function canel() {
	var contextPath = $("#contextPath").val();
	var virtualId = $("#virtualId").val();// 企业ID
	location.href = contextPath + "/admin/bill/generalBillsPage?funcid="
			+ $("#funcid").val() + "&virtualId=" + virtualId;
}

/**
 * 新增账单服务大类信息
 */
function addGeneralBillsService() {
	if(validateForm()){
		return;
	}
	var billServiceId = 1;
	var orderId = 1;
	if (billServiceIdArray.length > 0) {
		billServiceId = Number(Math.max.apply(null, billServiceIdArray))+ 1;
		billServiceIdArray.push(billServiceId);
	} else {
		billServiceIdArray.push(billServiceId);
	}
	var dafmt = "yyyy-MM-dd";
	var html = "";
	var orderIds = billServiceId + "_" + orderId;
	orderIdArray.push(orderIds);
	html += "<div class='seviceitem' id='seviceitem" + billServiceId + "'>";
	html += "<input type='hidden' value=''  id='billServiceId" + billServiceId
			+ "'/>";
	html += "<div class='seviceitemtit'><div class='selectwrap'>";
	html += "<select name='serviceName' onchange='validateSelectService("
			+ billServiceId + ")' id='serviceCode" + billServiceId
			+ "'></select>";
	html += "</div>";
	html += "<div class='seviceright'><div class='form-group seviceinputright'>";
	html += "<label>优惠</label><em>￥</em><input id='freeFee" + billServiceId
			+ "' type='text' value='0.00' onkeyup='youhuiPrice(" + billServiceId + ")'/>";
	html += "</div>";
	html += "<div class='form-group seviceinputright'><label>合计</label><em>￥</em>";
	html += "<input type='text' readonly='readonly' id='totalFee"
			+ billServiceId
			+ "'/></div><div class='seviceadditem'><a href='javascript: void(0);' style='margin-right: 2px;' class='btn-small btn-success js_subseviceitem' onclick='addGeneralBillsOrders("
			+ billServiceId + ")'>添加</a>";
	html += "<a href='javascript: void(0);' class='btn-small btn-red js_deletesevice' onclick='delGeneralBillsService("
			+ billServiceId + ")'>删除</a>";
	html += "</div></div></div>";
	html += "<table class='billtable table' id='table" + billServiceId
			+ "'><tbody><tr id='orderTr" + orderIds
			+ "'><td class='datetd'><div class='form-group'>";
	html += "<input type='hidden' value=''   id='orderId" + orderIds + "'/>";
	html += "<label for='' class='sr-only'>日期</label><input id='orderTime"
			+ orderIds
			+ "'  class='Wdate' style='width: 120px;' onfocus='WdatePicker({firstDayOfWeek:1,dateFmt:\""
			+ dafmt + "\"})' readonly='true' />";
	html += "</div></td><td class='contd'><div class='form-group'>";
	html += "<label for='' class='sr-only'>服务内容</label><input id='goodName"
			+ orderIds
			+ "' type='text' /></div></td><td class='billtabletd'><div class='form-group'>";
	html += "<label for='' class='sr-only'>数量</label><input type='text' id='amount"
			+ orderIds + "' /></div></td>";
	html += "<td class='billtabletd billmoneytd'><div class='form-group'><label for=''>￥</label><input type='text' id='totalFee"
			+ orderIds
			+ "' onkeyup='orderEidtPrice(\""
			+ orderIds
			+ "\")' /></div></td><td>";
	html += "<div class='seviceadditem'><a href='javascript: void(0);' class='btn-small btn-red js_subdeletesevice' onclick='delGeneralBillsOrders(\""
			+ orderIds + "\")'>删除</a>";
	html += "</div>";
	html += "</td>";
	html += "</tr>";
	html += "</tbody>";
	html += "</table>";
	html += "</div>";
	$(".table-form").append(html);
	loadServiceInfo(billServiceId);
}

/**
 * 删除服务大类信息
 */
function delGeneralBillsService(billServiceId) {
	var orderIdArrays = new Array();
	$.each(orderIdArray,function(index,item){
		var itemArray=item.split("_");
		if(itemArray[0]==billServiceId){
			orderIdArrays.push(item);
			delGeneralBillsServiceOrders(item);
		}
	});
	$.each(orderIdArrays,function(index,item){
		orderIdArray.splice(orderIdArray.indexOf(item),1);
	})
	billServiceIdArray.splice(billServiceIdArray.indexOf(billServiceId), 1);
	var serviceId = $("#billServiceId" + billServiceId + "").val();
	if (serviceId != "") {
		delBillServiceIdArray.push(serviceId);
	}
	$("#seviceitem"+billServiceId+"").remove();
	youhuiPrice(billServiceId);
}

/**
 * 添加服务大类的商品列表信息
 * 
 * @param billServiceId
 */
function addGeneralBillsOrders(billServiceId) {
	var orderId = "";
	var orderIdsb = "";
	var number=1;
	var orderIdArrays=new Array();
	$.each(orderIdArray, function(indxe, item) {
		var str = item.split("_");
		if (str[0] == billServiceId) {
			orderIdArrays.push(str[1]);
		}
	});
	if(orderIdArrays.length>0){
		var orderNo=Math.max.apply(null, orderIdArrays);
		var number = Number(orderNo) + 1;
		orderId = billServiceId + "_" + number;
	}else{
		orderId=billServiceId + "_" + number;
	}
	orderIdArray.push(orderId);
	var html = "";
	html += "<tr id='orderTr" + orderId
			+ "'><td class='datetd'><div class='form-group'>";
	html += "<input type='hidden' value=''   id='orderId" + orderId + "'/>";
	html += "<label for='' class='sr-only'>日期</label><input id='orderTime"+orderId+"'  class='Wdate' style='width: 120px;' onfocus='WdatePicker({firstDayOfWeek:1,dateFmt:\"yyyy-MM-dd\"})' readonly='true' />";
	html += "</div></td>";
	html += "<td class='contd'><div class='form-group'>";
	html += "<label for='' class='sr-only'>服务内容</label><input type='text' id='goodName"+orderId+"' /></div></td>";
	html += "<td class='billtabletd'><div class='form-group'>";
	html += "<label for='' class='sr-only'>数量</label><input type='text' id='amount"+orderId+"' /></div>";
	html += "</td><td class='billtabletd billmoneytd'>";
	html += "<div class='form-group'>";
	html += "<label for=''>￥</label><input type='text' id='totalFee" + orderId
			+ "' onkeyup='orderEidtPrice(\"" + orderId
			+ "\")' /></div></td><td><div class='seviceadditem'>";
	html += "<a href='javascript: void(0);' class='btn-small btn-red js_subdeletesevice' onclick='delGeneralBillsOrders(\"" + orderId+ "\")'>删除</a></div></td></tr>";
	$("#table" + billServiceId + "").append(html);
}

/**
 * 删除单个订单商品列表信息
 * 
 * @param billServiceId
 * @param orderId
 */
function delGeneralBillsOrders(orderId) {
	var orderIds = $("#orderId" + orderId + "").val();
	if (orderIds != "") {
		delOrderIdArray.push(orderIds);
	}
	orderPrice(orderId);
	orderIdArray.splice(orderIdArray.indexOf(orderId), 1);
	$("#orderTr" + orderId).remove();
}

/**
 * 删除单个订单商品列表信息
 * 
 * @param billServiceId
 * @param orderId
 */
function delGeneralBillsServiceOrders(orderId) {
	var orderIds = $("#orderId" + orderId + "").val();
	if (orderIds != "") {
		delOrderIdArray.push(orderIds);
	}
	orderPrice(orderId);
}

/**
 * 根据动态ID绑定select下拉框
 * 
 * @param billServiceId
 */
function loadServiceInfo(billServiceId) {
	var contextPath = $("#contextPath").val();
	var url = contextPath + "/admin/bill/loadServiceInfo";
	$.ajax({
		url : url,
		type : "POST",
		success : function(data) {
			if (data != null && data != "" && data.length > 0) {
				$("#serviceCode" + billServiceId).empty();
				$("#serviceCode" + billServiceId).append(
						"<option value=''>请选择服务项</option>");
				$.each(data, function(index, item) {
					$("#serviceCode" + billServiceId).append(
							"<option value='" + item.itemcode + "_"
									+ billServiceId + "'>" + item.itemname
									+ "</option>");
				})
			}
		},
		error : function() {
			layer.msg("请检测网络", {
				icon : 5,
				end : function() {

				}
			});
		}
	});
}

/**
 * 计算金额
 * 
 * @param billServiceId
 */
function youhuiPrice(id) {
	var totalFee = 0.00;
	var flag = false;
	var exp = /^([1-9][\d]{0,7}|0)(\.[\d]{1,2})?$/;
	if (!exp.test($("#freeFee" + id).val()) && $("#freeFee" + id).val() != ""
			&& typeof ($("#freeFee" + id).val()) != "undefined") {
		layer.msg('请输入正确的金额');
		return;
	}
	$.each(billServiceIdArray, function(index, item) {
		var freeFee = 0.00;
		var total = 0.00;
		if ($("#freeFee" + item + "").val() != "" && typeof ($("#freeFee" + item + "").val()) != "undefined") {
			freeFee = Number($("#freeFee" + item + "").val());
		}
		$.each(orderIdArray, function(seriNo, obj) {
			var objArray = obj.split("_");
			if (item == objArray[0] && typeof ($("#totalFee" + obj).val()) != "undefined") {
				total += Number($("#totalFee" + obj).val());
			}
		});
		var sumPrice = total;
		total = total - freeFee;
		if (total >= 0 && id==item) {
			$("#totalFee" + id + "").val(total);
		} else if(total<0 && id==item){
			layer.msg('优惠金额不能大于商品总价！');
			$("#totalFee" + item + "").val(sumPrice);
			$("#freeFee" + item + "").val(0.00);
			total = sumPrice;
		}
		totalFee += total;
	});
	var sumOwed = Number($("#sumOwed").val());
	var reserveBalance = Number($("#reserveBalance").val());
	var payable = totalFee + sumOwed - reserveBalance;
	if(payable<0){
		payable=0.00;
	}
	$("#totalFee").val(totalFee);
	$("#payable").val(payable);
}

/**
 * 计算金额
 * 
 * @param billServiceId
 */
function orderPrice(id) {
	var totalFee = 0.00;
	var billsId;
	var exp = /^([1-9][\d]{0,7}|0)(\.[\d]{1,2})?$/;
	if (!exp.test($("#totalFee" + id).val()) && $("#totalFee" + id).val() != ""
			&& typeof ($("#totalFee" + id).val()) != "undefined") {
		layer.msg('请输入正确的金额');
		return;
	}
	$.each(billServiceIdArray, function(index, item) {
		var freeFee = 0.00;
		var total = 0.00;
		if ($("#freeFee" + item + "").val() != "") {
			freeFee = Number($("#freeFee" + item + "").val());
		}
		$.each(orderIdArray, function(seriNo, obj) {
			var objArray = obj.split("_");
			if (item == objArray[0]) {
				if(obj!=id){
					total+=Number($("#totalFee"+obj).val());
				}
			}
		});
		total=total-freeFee;
		if (total > 0) {
			$("#totalFee" + item + "").val(total);
		}else{
			total=0;
			$("#freeFee"+item).val(0.00);
			$("#totalFee"+item).val(0.00);
		}
		totalFee+=total;
	});
	var sumOwed = Number($("#sumOwed").val());
	var reserveBalance = Number($("#reserveBalance").val());
	var payable = totalFee + sumOwed - reserveBalance;
	if(payable<0){
		payable=0.00;
	}
	$("#totalFee").val(totalFee);
	$("#payable").val(payable);
}


/**
 * 计算金额
 * 
 * @param orderPrice
 */
function orderEidtPrice(id) {
	var totalFee = 0.00;
	var billsId;
	var exp = /^([1-9][\d]{0,7}|0)(\.[\d]{1,2})?$/;
	if (!exp.test($("#totalFee" + id).val()) && $("#totalFee" + id).val() != ""
			&& typeof ($("#totalFee" + id).val()) != "undefined") {
		layer.msg('请输入正确的金额');
		return;
	}
	$.each(billServiceIdArray, function(index, item) {
		var freeFee = 0.00;
		var total = 0.00;
		if ($("#freeFee" + item + "").val() != "") {
			freeFee = Number($("#freeFee" + item + "").val());
		}
		$.each(orderIdArray, function(seriNo, obj) {
			var objArray = obj.split("_");
			if (item == objArray[0]) {
					total+=Number($("#totalFee"+obj).val());
			}
		});
		total=total-freeFee;
		if (total > 0) {
			$("#totalFee" + item + "").val(total);
		}else{
			total=0;
			$("#freeFee"+item).val(0.00);
			$("#totalFee"+item).val(0.00);
		}
		totalFee+=total;
	});
	var sumOwed = Number($("#sumOwed").val());
	var reserveBalance = Number($("#reserveBalance").val());
	var payable = totalFee + sumOwed - reserveBalance;
	if(payable<0){
		payable=0.00;
	}
	$("#totalFee").val(totalFee);
	$("#payable").val(payable);
}

/**
 * 根据下拉选中 识别当前服务选项是否已存在
 * 
 * @param value
 */
function validateSelectService(billServiceId) {
	var serviceName = document.getElementsByName("serviceName");
	var serviceCode = $("#serviceCode" + billServiceId).val();
	var flag = false;
	if (serviceCode != "") {
		var array = serviceCode.split("_");
		$.each(serviceName, function(index, item) {
			var itemArray = item.value.split("_");
			if (array[1] != itemArray[1]) {
				if (itemArray[0] == array[0]) {
					flag = true;
					return;
				}
			}
		});
		if (flag) {
			layer.msg('已存在相同的服务项！');
			loadServiceInfo(billServiceId);
		}
	}
}

/**
 * 验证输入框的值
 */
function validateForm(){
	var startTime=$("#startTime").val();//计费开始时间
	var endTime=$("#endTime").val();//计费结束时间
	var desc="";
	var flag=false;
	if($.trim(startTime)==""){
		layer.msg('请选择计费开始日期！');
		flag=true;
		return flag;
	}
	if($.trim(endTime)==""){
		layer.msg('请选择计费开始结束！');
		flag=true;
		return flag;
	}
	var d1 = new Date(startTime.replace(/\-/g, "\/"));  
	var d2 = new Date(endTime.replace(/\-/g, "\/"));
	if(d1>d2){
		layer.msg('开始日期不能大于结束日期！');
		flag=true;
		return flag;
	}
	
	if(!flag){
		//验证服务信息
		$.each(billServiceIdArray,function(index,item){
			var serviceCode=$("#serviceCode"+item).val();
			if($.trim(serviceCode)==""){
				desc="请选择服务项";
				flag=true;
				return;
			}
		});
	}
	if(!flag){
		$.each(orderIdArray,function(jndex,obj){
			var orderTime=$("#orderTime"+obj).val();
			if($.trim(orderTime)==""){
				desc="请填写消费明细日期";
				flag=true;
				return;
			}
			var d3 = new Date(orderTime.replace(/\-/g, "\/"));
			if(d3<d1 || d3>d2){
				desc="消费日期不能超出计费周期范围";
				flag=true;
				return;
			}
			var goodName=$("#goodName"+obj).val();
			if($.trim(goodName)==""){
				desc="请填写服务内容";
				flag=true;
				return;
			}
			var amount=$("#amount"+obj).val();
			if($.trim(amount)=="" || amount<=0){
				desc="请填商品数量";
				flag=true;
				return;
			}
			var totalFee=$("#totalFee"+obj).val();
			if($.trim(totalFee)==""){
				desc="请填商品总价";
				flag=true;
				return;
			}
		});
	}
	if(flag){
		layer.msg(desc);
	}
	
	return flag;
	
}

/**
 *组合提交的参数 JSON对象
 */
function inItParam(){
	//账单主体信息data
	var generalBillsId=$("#generalBillsId").val();
	var totalFee=$("#totalFee").val();
	var startTime=$("#startTime").val();
	var endTime=$("#endTime").val();
	var makePerson=$("#makePerson").val();
	var makeTime=$("#makeTime").val();
	generalBillsDate="{'generalBillsId':'"+generalBillsId+"','totalFee':'"+totalFee+"','startTime':'"+startTime+"'," +
			"'endTime':'"+endTime+"','makePerson':'"+makePerson+"','makeTime':'"+makeTime+"'}";
	//新增或保存的data
	data="{'serviceBill':[";
	$.each(billServiceIdArray,function(index,item){
		var billServiceId=$("#billServiceId"+item).val();//账单服务类ID
		var serviceCode=$("#serviceCode"+item).val();//服务内容
		var serviceArray=serviceCode.split("_");
		var serviceName=$("#serviceCode"+item).find("option:selected").text();
		var freeFee=$("#freeFee"+item).val();//优惠金额
		var totalFee=$("#totalFee"+item).val();//合计金额
		if(index==0){
			data+="{'billServiceId':'"+billServiceId+"','serviceCode':'"+serviceArray[0]+"','serviceName':'"+serviceName;
			data+="','freeFee':'"+freeFee+"','totalFee':'"+totalFee+"','orderList':[";
		}else{
			data+=",{'billServiceId':'"+billServiceId+"','serviceCode':'"+serviceArray[0]+"','serviceName':'"+serviceName;
			data+="','freeFee':'"+freeFee+"','totalFee':'"+totalFee+"','orderList':[";
		}
		var sum=0;
		$.each(orderIdArray,function(jindex,obj){
			var orderAyyar=obj.split("_");
			if(item==orderAyyar[0]){
				var orderId=$("#orderId"+obj).val();
				var orderTime=$("#orderTime"+obj).val();
				var goodName=$("#goodName"+obj).val();
				var amount=$("#amount"+obj).val();
				var totalFee=$("#totalFee"+obj).val();
				if(sum==0){
					data+="{'orderId':'"+orderId+"','orderTime':'"+orderTime+"','goodName':'"+goodName+"','amount':'"+amount+"','totalFee':'"+totalFee+"'}";
				}else{
					data+=",{'orderId':'"+orderId+"','orderTime':'"+orderTime+"','goodName':'"+goodName+"','amount':'"+amount+"','totalFee':'"+totalFee+"'}";
				}
				sum++;
			}
		})
		data+="]}";
	});
	data+="]}";
	//刪除服務的data
	delServiceData="{'delServiceBill':[";
	$.each(delBillServiceIdArray,function(index,item){
		if(index==0){
			delServiceData+="{'billServiceId':'"+item+"'}";
		}else{
			delServiceData+=",{'billServiceId':'"+item+"'}";
		}
	});
	delServiceData+="]}";
	//刪除order的data
	delOrderData="{'delOrderBill':[";
	$.each(delOrderIdArray,function(index,item){
		var orderArray=item.split("_");
		if(index==0){
			delOrderData+="{'orderId':'"+orderArray[1]+"'}";
		}else{
			delOrderData+=",{'orderId':'"+orderArray[1]+"'}";
		}
	});
	delOrderData+="]}";
}

function saveUpdateBill(){
	if(validateForm()){
		return;
	}
	inItParam();
	var makePerson=$("#makePerson").val();
	var makeTime=$("#makeTime").val();
	if($.trim(makePerson)==""){
		layer.msg('请填写制单人！');
		return;
	}
	if($.trim(makeTime)==""){
		layer.msg('请选择制单时间！');
		return;
	}
	var contextPath = $("#contextPath").val();
	var url=contextPath+"/admin/bill/saveUpdateGeneralBills";
	$.ajax({
		url : url,
		data:{generalBissData:data,delServiceData:delServiceData,delOrderData:delOrderData,generalBillsDate:generalBillsDate},
		type : "POST",
		success : function(data) {
			if(data.flag){
				layer.alert(data.desc, {icon: 6,end:function(){
	        		location.href=contextPath+"/admin/bill/generalBillsPutView?generalBillsId="+$("#generalBillsId").val()+"&virtualId="+$("#virtualId").val()+"&funcid="+$("#funcid").val();
	        	}});
			}else{
				layer.alert(data.desc, {icon: 5,end:function(){
	        		
	        	}});
			}
		},
		error : function() {
			layer.msg("请检测网络", {
				icon : 5,
				end : function() {

				}
			});
		}
	});
	
}