$(function() {

	var focusId;
	$("input").focus(function() {});

	setTimeout(function() {
		$('#orderNo').focus();
	}, 1000);

	$('#number').keyup(function(event) {
		if(event.keyCode != "13") {
			return false;
		}
		$("#number").val(trimStr($("#number").val()));
		if($('#number').val() != '') {
			//播放扫描声音
			playSound('../raw/scan.wav');
			submitNumber();
		}
	});

	$('#barcode').keyup(function(event) {
		if(event.keyCode != "13") {
			return false;
		}
		$("#barcode").val(trimStr($("#barcode").val()));
		if($("#barcode").val() != '') {
			//播放扫描声音
			playSound('../raw/scan.wav');
			submitBarcode();
		}
	});

	$('#productionDate').keyup(function(event) {
		if(event.keyCode != "13") {
			return false;
		}
		if($("#productionDate").val() != '') {
			//计算效期/批次
			var productionDate = $("#productionDate").val()
			if(isNaN(productionDate)) {
				//mui.alert("生产日期只能输入数字;现输入值为:" + productionDate, '警告', function() {setFocus('productionDate');});
				$("#productionDate").val("");//不合法直接清空
				return;
			}
			//验证是否时间是否合法  时间范围必须小于当前时间  不能小于当前时间10年/ 月份范围必须为:1到12 /该月日期必须合法 
			var checkResult = checkDate8(productionDate);
			if(checkResult != "1") {
				mui.alert(checkResult, '警告', function() {setFocus('productionDate');});
				return;
			}
			//不能大于当前时间
			var isGt = compareCurrentForDate8(productionDate, true)
			if(isGt) {
				mui.alert("生产日期不能大于当前时间", '警告', function() {setFocus('productionDate');});
				return
			}
			var inOrderItemEnt = inOrderItemMap[inOrderItemId];
			
			//生成效期
			var expDate = getExpDate(productionDate, inOrderItemEnt.shelfLifeDays);
			if(expDate != null) {
				$("#expiryDate").val(expDate)
				//生成批次
				var batchNo = genBatchNo(inOrderItemEnt.batchRuleCode, expDate);
				if(batchNo != null) {
					$("#batchNo").val(batchNo);
					setFocus("productQty");
				} else {
					setFocus("batchNo")
				}
				return
			}
		}
		
		setFocus("expiryDate")
	});	

	$('#expiryDate').keyup(function(event) {
		if(event.keyCode != "13") {
			return false;
		}
		var inOrderItemEnt = inOrderItemMap[inOrderItemId];
		if($("#expiryDate").val() != '') {
			//校验效期 并且  生成批次
			var expiryDate = $("#expiryDate").val();
			if(isNaN(expiryDate)) {
				//mui.alert("有效日期只能输入数字;现输入值为:" + expiryDate, '警告', function() {setFocus('expiryDate');});
				$("#expiryDate").val("");//不合法直接清空
				return
			}
			//验证是否时间是否合法  时间范围必须小于当前时间  不能小于当前时间10年/ 月份范围必须为:1到12 /该月日期必须合法 
			var checkResult = checkDate8(expiryDate);
			if(checkResult != "1") {
				mui.alert(checkResult, '警告', function() {setFocus('expiryDate');});
				return
			}
		}
		
		//生成批次
		var batchNo = genBatchNo(inOrderItemEnt.batchRuleCode, expiryDate);
		console.log('batchNo:' + batchNo)
		if(batchNo != null) {
			$("#batchNo").val(batchNo);
			setFocus("productQty");
		} else {
			setFocus("batchNo");
		}
	});

	//batchNo
	$('#batchNo').keyup(function(event) {
		if(event.keyCode != "13") {
			return false;
		}
		setFocus("productQty");
	});
	
	
	$('#productQty').keyup(function(event) {
		if(event.keyCode != "13") {
			return false;
		}
		if($("#productQty").val() != '') {
			checkAndSubmit();
		}
	});
	
	
});


var inOrderMap = {};
var inOrderId = -1;
//提交入库单号
function submitNumber() {
	var number = $('#number').val();
	var numberType = $('#numberType').val();

	var formData = {
		number: number,
		numberType: numberType
	};

	var appRequest = $appRequest; //复制请求封装对象
	appRequest.opType = OP_TYPE_MENU.RECEIPT_1;
	appRequest.msg = JSON.stringify(formData); //msg是消息内容主体;//msg是消息内容主体
	console.log("$appRequestUrl:" + $appRequestUrl)
	$.ajax({
		type: 'POST',
		url: $appRequestUrl,
		contentType: "application/json; charset=utf-8",
		data: JSON.stringify(appRequest),
		success: function(appResponse) {
			console.log(JSON.stringify(appResponse))

			if(!appResponse.success) {
				playSound('../raw/error.wav');
				mui.alert(appResponse.msg, '警告', function() {
					setFocus('orderNo');
				});
				return;
			}

			//mui.toast(appResponse.msg);

			var orderList = appResponse.extend;
			if(orderList.length == 1) {
				//如果有一条 直接查询预报-收货数据
				fillOrderDetail(orderList[0]);
				return;
			}

			//如果有多条 弹框选择 
			if(orderList.length > 1) { //出现多条记录时选择
				var listLi = [];
				for(var i = 0; i < orderList.length; i++) {
					var orderSingle = orderList[i];
					inOrderMap[orderSingle.id] = orderSingle;
					listLi.push('<li class="mui-table-view-cell" onclick="selectSingleOrder(\'' + orderSingle.id + '\')">货主:' + orderSingle.customerCode + ';	仓库:' + orderSingle.warehouseCode + ';	创建时间:' + fmtDateTime(orderSingle.createdTime) + '  </li>');
				}
				var listLiStr = listLi.join('')
				$("#inOrderListDetail").html(listLiStr);
				mui("#inOrderListShow").popover('show'); //show hide toggle
				return
			}

		},
		error: function() {
			console.log('网络断开或服务器发生异常')
			playSound('../raw/error.wav');
			mui.toast('网络断开或服务器发生异常');
		}
	});
}


var inOrderItemMap = {};
var inOrderItemId = -1;
//提交商品条码
function submitBarcode() {
	var orderNo = $("#number").val();
	var barcode = $('#barcode').val();
	var formData = {
		inOrderId: inOrderId,
		barcode: barcode,
		orderNo: orderNo
	};

	var appRequest = $appRequest; //复制请求封装对象
	appRequest.opType = OP_TYPE_MENU.RECEIPT_2;
	appRequest.msg = JSON.stringify(formData); //msg是消息内容主体

	$.ajax({
		type: 'POST',
		url: $appRequestUrl,
		contentType: "application/json; charset=utf-8",
		data: JSON.stringify(appRequest),
		success: function(appResponse) {
			console.log("appResponse:" + JSON.stringify(appResponse))
			if(!appResponse.success) {
				playSound('../raw/error.wav');
				mui.alert(appResponse.msg, '警告', function() {setFocus('barcode');});
				return;
			}
			mui.toast(appResponse.msg);
			
			//返回预报收货记录 可能是多条
			var list = appResponse.extend;
			if(list.length > 1) { //出现多条记录时选择
				var listLi = [];
				for(var i = 0; i < list.length; i++) {
					var singleItem = list[i];
					inOrderItemMap[singleItem.id] = singleItem;
					if(singleItem.receiptTotal == null) {
						singleItem.receiptTotal = 0;
					}
					listLi.push('<li class="mui-table-view-cell" onclick="selectBarcode(\'' + singleItem.id + '\')">批次:' + singleItem.batchNo + ';	商品品质:' + singleItem.qualityName + ';	预报数量:' + singleItem.quantity + '; 已收数量:' + singleItem.receiptTotal + '  </li>');
				}
				var listLiStr = listLi.join('')
				$("#barcodeListDetail").html(listLiStr);
				mui("#barcodeListShow").popover('show'); //show hide toggle
				return
			}
			
			//只有1条时
			inOrderItemMap[list[0].id] = list[0];
			fillOrderItem(list[0]);
		},
		error: function() {
			playSound('../raw/error.wav');
			mui.toast('网络断开或服务器发生异常');
		}
	});
}

//下一个条码
function next() {
	$("#barcode").val("");
	$("#inReceiptId").val("");

	$("#batchNo").val(""); //批次号码
	$("#receiptQuantity").val(""); //收货数量
	$("#toReceivingQty").val("");//待收数量

	$("#locationCode").val("");
		
	$("#barcode").focus();
}

/**
 * 填充明细  
 */
function fillOrderDetail(orderSingle) {
	$("#warehouseCode").val(orderSingle.warehouseCode);
	$("#customerCode").val(orderSingle.customerCode);
	//inOrderId
	inOrderId = orderSingle.id
	setFocus("barcode")
}

/**
 * 选择其中一单
 * @param {Object} id
 */
function selectSingleOrder(inOrderId) {
	var orderSingle = inOrderMap[inOrderId]
	fillOrderDetail(orderSingle)
	mui('#inOrderListShow').popover('toggle');
}

/**
 * 选择其中一个条码
 * @param {Object} inOrderItemId
 */
function selectBarcode(inOrderItemId) {
	var orderItemSingle = inOrderItemMap[inOrderItemId]
	fillOrderItem(orderItemSingle)
	mui('#barcodeListShow').popover('toggle');
	setFocus('productionDate')
}

function fillOrderItem(orderItemSingle) {
	console.log("orderItemSingle:" + JSON.stringify(orderItemSingle))
	inOrderItemId = orderItemSingle.id;
	
	//在条码下显示该inorderitem的部分预报信息
	$("#preSku").text(orderItemSingle.sku);
	$("#preBatchNo").text(orderItemSingle.batchNo);
	$("#preQty").text(orderItemSingle.quantity);
	$("#preQuality").text(orderItemSingle.qualityName);
	
	var expiryDateStr = fmtDate8(orderItemSingle.expiryDate);
	$("#expiryDate").val(expiryDateStr)
	
	var batchNo = orderItemSingle.batchNo;
	$("#batchNo").val(batchNo);
		
	var receiptTotal = orderItemSingle.receiptTotal
	if(isNaN(receiptTotal) || receiptTotal == null) {
		receiptTotal = 0;
		orderItemSingle.receiptTotal = receiptTotal;
	}
	//待收数量
	var toReceivingQty = orderItemSingle.quantity - receiptTotal;
	$("#toReceivingQty").val(toReceivingQty)
}

/**
 * 提交收货
 */
function checkAndSubmit() {

	var inOrderItemEntity = inOrderItemMap[inOrderItemId];

	var quantity = $('#productQty').val(); //本次收货数量

	var qtyTotal = inOrderItemEntity.quantity; // 预报总数
	qtyTotal = qtyTotal != null ? qtyTotal : 0;

	var receiptTotal = inOrderItemEntity.receiptTotal; // 已收货总数 - 不完全准
	receiptTotal = receiptTotal != null ? receiptTotal : 0;

	var waitReceipt = qtyTotal - receiptTotal; //待收货数

	if(quantity > waitReceipt) {
		var btnArray = ['否', '是'];
		mui.confirm("收货数量大于预报数量,您确定要执行操作吗？建议检查是否重复收货", '警告', btnArray, function(e) {
			if(e.index == 1) {
				submitReceipt();
			}
		})
	} else {
		submitReceipt();
	}
}

var isSubmintIng = false; //是否正在提交. 防止按回车太快
//提交收货明细
function submitReceipt() {
	if(isSubmintIng) {
		return;
	}
	isSubmintIng = true;

	var inOrderItemEntity = inOrderItemMap[inOrderItemId];
	var inOrderEntity = inOrderMap[inOrderId]

	var orderId = inOrderId;
	var barcode = inOrderItemEntity.barcode; //$("#barcode").val();

	var itemId = inOrderItemId; //$("#itemId").val();
	var sku = inOrderItemEntity.sku; //$("#itemSku").val();

	var batchRuleCode = inOrderItemEntity.batchRuleCode; //$("#batchRuleCode").val();
	var batchNo = $("#batchNo").val();

	var qualityCode = $('#qualityCode').val();
	var quantity = $('#productQty').val(); //本次收货数量

	//如果保质期跟有效期不为空  dateType取效期
	//	var dateType = $("#dateType").val();
	var productionDate = $("#productionDate").val();

	var expiryDate = $("#expiryDate").val();

	var shelfLifeDays = $("#shelfLifeDays").val();

	var msgBody = {
		orderId: orderId,
		barcode: barcode,
		itemId: itemId,
		sku: sku,
		batchRuleCode: batchRuleCode,
		batchNo: batchNo,
		qualityCode: qualityCode,
		quantity: quantity,
		productionDateStr: productionDate,
		expiryDateStr: expiryDate,
		shelfLifeDays: shelfLifeDays
	};

	//序列化成字符串
	var msgBodyStr = JSON.stringify(msgBody)
	var appRequest = $appRequest; //复制请求封装对象
	appRequest.opType = OP_TYPE_MENU.RECEIPT_3;
	appRequest.msg = msgBodyStr; //msg是消息内容主体
	var nwaiting = plus.nativeUI.showWaiting('正在提交中...');
	$.ajax({
		type: 'POST',
		url: $appRequestUrl, //标准收货方法
		contentType: "application/json; charset=utf-8",
		data: JSON.stringify(appRequest),
		success: function(result) {
			isSubmintIng = false;
			nwaiting.close();
			if(!result.success) {
				mui.alert(result.msg, '警告', function() {});
				return;
			}
			inOrderItemMap = {};
			inOrderItemId = -1;

			var clearClass = $(".allowClear");
			$(".allowClear").each(function() {
				$(this).val("")
			})
						
			//继续操作. 光标移至条码
			setFocus('barcode');
			mui.toast(result.msg);
		},
		error: function() {
			isSubmintIng = false;
			nwaiting.close();
			mui.alert('网络断开或服务器发生异常', '注意', function() {});
		}
	});
}


var isShowDetails = false;
function showDetails() {
	alert(isShowDetails)
	if(!isShowDetails) {
		$("#showDetails").show();
		isShowDetails = true;
		$("#showIco").attr("class", "fa fa-angle-double-up");
		//显示明细
	} else {
		$("#showDetails").hide();
		isShowDetails = false;
		$("#showIco").attr("class", "fa fa-angle-double-down");
	}

}

//下一个订单
function cleanAll() {
	$("input").each(function() {
		$(this).val('')
	})
	//  /number
	setFocus('number');
}