var focusId;
$(function(){
	
	$("input").focus(function(){
		//记住焦点位置
		focusId = this.id;
		//this.scrollIntoView(true);//回到顶部
		//window.setTimeout("myScrollIntoView()",100);  
	});	
	
	setTimeout(function() {
		$('#outOrderNo').focus();
	}, 1000);
	
	//同步手工改数量
	var last_qty = $("#_quantity").val();
	function setQuantity(){
		var _qty = $("#_quantity").val();
		if(_qty < 0){
			$("#_quantity").val(0);
			return;
		}
		if(_qty == last_qty){
			return;		
		}
		last_qty = _qty;
		$("#productQty").val(_qty);
	}
	window.setInterval(setQuantity,500);
	
	//当失去焦点按回车时,焦点回到之前焦点位置
	$(window).keydown(function(event){
	 	if((event.keyCode==13)) {
	 		$(".messager-body").window('close');
	 		if(document.activeElement.id == null || document.activeElement.id ==''){
	 			//回到上次焦点地方
		 		//$("#"+focusId).focus();
	 		}
	 	}  
	});	

	//提交出库单号
    $('#outOrderNo').keyup(function (event) {
        console.log("event.keyCode:"+event.keyCode)
        if (event.keyCode != "13") {return false;}
        $("#outOrderNo").val(trimStr($("#outOrderNo").val()));
        //播放扫描声音
    	playSound('../raw/scan.wav');
    	
        submitOutOrderNo();
    });
	
    // //库位号回车
    // $('#locationCode').keyup(function (event) {
    // 	if (event.keyCode != "13") {return false;}
    // 	$("#locationCode").val(trimStr($("#locationCode").val()));
    // 	//播放扫描声音
    // 	playSound('../raw/scan.wav');
    	
    // 	$('#barcode').focus();
    // });
    
    //条码回车
    $('#barcode').keyup(function (event) {
    	if (event.keyCode != "13") {return false;}
    	$("#barcode").val(trimStr($("#barcode").val()));
    	//播放扫描声音
    	playSound('../raw/scan.wav');
    	
    	submitBarcode();
    }); 
    
    //提交
    $('#productQty').keyup(function (event) {
    	if (event.keyCode != "13") {return false;}
    	$("#productQty").val(trimStr($("#productQty").val()));
    	
    	submitOutShelf();
    });
});

//提交出库单号
function submitOutOrderNo(){
   var outOrderNo = $('#outOrderNo').val();
   if(outOrderNo == ''){return;}
   
   var appRequest = $appRequest;//复制请求封装对象
   appRequest.opType = OP_TYPE_MENU.OUT_SHELF_1;
   appRequest.msg = outOrderNo;//msg是消息内容主体
   console.log("请求后台提交出库单")
   console.log($appRequestUrl)
   $.ajax({
        type: 'POST',
        url: $appRequestUrl,
        contentType: "application/json; charset=utf-8",
        data: JSON.stringify(appRequest),
        success: function (appResponse) {
        	if(!appResponse.success){
        		playSound('../raw/error.wav');
        		mui.alert(appResponse.msg, '警告', function() {  setFocus('orderNo');  }); 
    			return;
    		}
        	
        	mui.toast(appResponse.msg);
        	
        	var outOrder = appResponse.extend;
        	
        	$("#outOrderId").val(outOrder.id);
        	$("#customerCode").val(outOrder.customerCode);
        	$("#warehouseCode").val(outOrder.warehouseCode);
        	
        	$("#statusName").text(outOrder.statusName);
        	$("#shipwayName").text(outOrder.shipwayName);
			     
			// 清空输入框
			nextBarcode();
			refreshItems();     
        	//进入下架操作
        	$("#barcode").focus();
        },
        error: function () {
        	playSound('../raw/error.wav');
        	mui.toast('网络断开或服务器发生异常');  
        }
    });
}


var isShowDetails = false;
function showDetails(){
	if(!isShowDetails){
		$("#showDetails").show();
		isShowDetails = true;
		$("#showIco").attr("class", "fa fa-angle-double-up");
		
		//刷新明细
		refreshItems();
	}else{
		$("#showDetails").hide();
		isShowDetails = false;
		$("#showIco").attr("class", "fa fa-angle-double-down");
	}
	//回到上次焦点地方
	if(focusId!=null && focusId != ''){
		$("#"+focusId).focus();		
	}
}

//显示待下架明细
function refreshItems(){
	var outOrderNo = $('#outOrderNo').val();
	var outOrderId = $('#outOrderId').val();
	if(outOrderId == ''){return;}
   
   	var appRequest = $appRequest;//复制请求封装对象
   	appRequest.opType = OP_TYPE_MENU.OUT_SHELF_2;
   	appRequest.msg = outOrderId;//msg是消息内容主体
   
	$("#itemList").empty();
   	$.ajax({
        type: 'POST',
        url: $appRequestUrl,
        contentType: "application/json; charset=utf-8",
        data: JSON.stringify(appRequest),
        success: function (appResponse) {
        	if(!appResponse.success){
        		//playSound('../raw/error.wav');
        		//mui.alert(appResponse.msg, '警告', function() {  setFocus('orderNo');  }); 
    			return;
    		}
        	
        	var waitQtyTotal = 0;
    		var itemList = appResponse.extend;
    		for(var index = 0; index < itemList.length; index ++){
    			var item = itemList[index];
    			handleNullFiled(item);
    			
    			var waitOutQty = item.quantity - item.outQuantity;//未下架数量
    			waitQtyTotal += waitOutQty; 
    			
    			if(waitOutQty > 0){
    				waitOutQty = "<span style='color:red;'><b>"+waitOutQty+"</b></span>";
    			}
    			
    			var tr = "<tr id='item_"+item.id+"'>";
	    			tr += "<th><div style='width:100%;overflow: hidden;font-size: 9pt;text-align: left;'>"+item.barcode+"</div></th>";
	    			tr += "<th><div style='width:100%;overflow: hidden;font-size: 9pt;text-align: left;'>"+item.locationCode+"</div></th>";
	    			tr += "<th><div style='width:100%;overflow: hidden;font-size: 9pt;text-align: left;'>"+waitOutQty+"</div></th>";	
    			tr += "</tr>";
    			
    			$("#itemList").append(tr);
    		}
    		
    		//总待下架数量
    		$("#waitQtyTotal").text(waitQtyTotal);
        },
        error: function () {
        	playSound('../raw/error.wav');
        	mui.toast('网络断开或服务器发生异常');  
        }
	});	
}

//提交条码
function submitBarcode(){
	var outOrderNo = $('#outOrderNo').val();
	var outOrderId=$("#outOrderId").val();
	var barcode= $('#barcode').val();
	// var locationCode=$('#locationCode').val();
	
	var formData={};
	formData.outOrderNo=outOrderNo;
	formData.outOrderId=outOrderId;
	// formData.locationCode=locationCode;
	formData.barcode=barcode;

   	var appRequest = $appRequest;//复制请求封装对象
   	appRequest.opType = OP_TYPE_MENU.OUT_SHELF_3;
   	appRequest.msg = JSON.stringify(formData);//msg是消息内容主体
	   	
   $.ajax({
        type: 'POST',
        url: $appRequestUrl,
        contentType: "application/json; charset=utf-8",
        data: JSON.stringify(appRequest),
        success: function (appResponse) {
        	if(!appResponse.success){
        		playSound('../raw/error.wav');
        		mui.alert(appResponse.msg, '警告', function() {  setFocus('orderNo');  }); 
    			return;
    		}
        	
        	//mui.toast(appResponse.msg);
        	
        	//返回待下架记录 可能是多条
        	var list = appResponse.extend;
        	if(list.length == 0 ){
        		playSound('../raw/error.wav');
        		mui.alert('后台返回list长度为0', '警告', function() {  setFocus('barcode');  });
        		return;
        	}
        	//暂先只处理第一条.. 后续可改为界面选择一条
        	var allocation = list[0];
        	
        	$("#allocationId").val(allocation.id);//收货记录id
        	$("#batchNo").val(allocation.batchNo);//批次号码
        	$("#barcodeShow").val(barcode);//显示商品条码
        	$("#qualityCode").val(allocation.qualityName);//显示商品品质
        	
        	//待下架数量
        	var waitOutQty = allocation.quantity - allocation.outQuantity;
        	
        	//判断是否扫描条码增加数量 
        	if($("#isAutoCount").val() == 'true'){
        		//扫描加1
        		var oralQty = $("#productQty").val();
        		if(oralQty == null || oralQty == ''){oralQty = 0;}
        		var nowQty = (parseInt(oralQty)+1);
        		$("#productQty").val(nowQty);
        		
        		//回到条码输入框,用户应当继续扫描条码
        		$("#barcode").val('');//清空条码,用户只需要看展示条码,最后手工点击提交
        		setFocus('barcode');
        		
        		//数量满足时自动提交
        		if(nowQty >= waitOutQty){
        			submitOutShelf();
        		}
        	} else {
        		$("#productQty").val(waitOutQty);//待下架数量
        		setFocus('productQty');
        	}
        },
        error: function () {
			playSound('../raw/error.wav');	
        	mui.toast('网络断开或服务器发生异常');          	
        }
    });
}

//提交呢下架
var isSubmintIng = false;//是否正在提交
function submitOutShelf(){
	
	console.log("提交下架:")
	if(isSubmintIng){return;}
	isSubmintIng = true;
	console.log("1")
	var outOrderId=$("#outOrderId").val();
	var outOrderNo = $('#outOrderNo').val();
	var allocationId=$('#allocationId').val();
	// var locationCode=$('#locationCode').val();
	
	//如果是扫描增加数量,条码输入框是空的,从展示条码取
	var barcode= $('#barcode').val();
	if(barcode == null || barcode == ''){
		barcode = $("#barcodeShow").val();	
		$('#barcode').val(barcode);
	}
	console.log("2")
	var productQty=$("#productQty").val();
	
	if(outOrderId == ''  || barcode == ''){
		mui.alert("商品条码,订单号 为必填项", '警告'); 
		
		isSubmintIng = false;
		return;
	}
		
	var formData={};
	formData.outOrderId=outOrderId;
	formData.outOrderNo=outOrderNo;
	formData.quantity=productQty;
	formData.allocationId=allocationId;
	// formData.locationCode=locationCode;
	formData.barcode=barcode;
		
	var appRequest = $appRequest;//复制请求封装对象
   	appRequest.opType = OP_TYPE_MENU.OUT_SHELF_4;
   	appRequest.msg = JSON.stringify(formData);//msg是消息内容主体
	
	console.log("提交参数:"+JSON.stringify(appRequest));
	
	var nwaiting = plus.nativeUI.showWaiting('正在提交中...');
	$.ajax({
        type: 'POST',
        url: $appRequestUrl,
        contentType: "application/json; charset=utf-8",
        data: JSON.stringify(appRequest),
        success: function (appResponse) {
			console.log(appResponse)
        	isSubmintIng = false;
        	nwaiting.close(); 
        	
        	if(!appResponse.success){
        		playSound('../raw/error.wav');
        		mui.alert(appResponse.msg, '警告', function() {  setFocus('barcode');  }); 
    			return;
    		}
        	
        	mui.toast(appResponse.msg);
        	
        	//播放成功声音
        	playSound('../raw/ok.wav');
			        	
        	
        	//智能判断该库位还有没有待下架的其他条码.如果还有,不要清空库位条码
        	
        	if(appResponse.extend == '1'){//该库位未下架完成
        		//下一个条码
        		nextBarcode();
				refreshItems();
        		return;
        	}     
        	if(appResponse.extend == '2'){//该库位已下架完成
        		//下一个库位
        		nextBarcode();
				refreshItems();
        		return;
        	}
    		//整单完成. 下一个出库单
        	if(appResponse.extend == '3'){
        		cleanAll();
        	}
        },
        error: function () {
        	isSubmintIng = false;
        	nwaiting.close(); 
        	
        	playSound('../raw/error.wav');
        	mui.toast('网络断开或服务器发生异常'); 
        }
	});
}


//下一个订单
function cleanAll(){
	isSubmintIng = false;
	
	$("#outOrderId").val("");
	$("#outOrderNo").val("");
	
	$("#statusName").text("");
	$("#shipwayName").text("");
	$("#waitQtyTotal").text("");
	
	$("#itemList").empty();
	
	$("#warehouseCode").val("");
	$("#customerCode").val("");
	
	// $("#locationCode").val("");
	$("#barcode").val("");
	$("#allocationId").val("");
	$("#batchNo").val("");
	$("#barcodeShow").val("");
	
	$("#qualityCode").val("");
	
	$("#productQty").val("");
	$("#_quantity").val("0");
		
	$('#outOrderNo').focus();
}
 
function nextLocation(){
	$("#locationCode").val("");
	$("#barcode").val("");
	$("#allocationId").val("");
	$("#batchNo").val("");
	$("#barcodeShow").val("");
	
	$("#qualityCode").val("");
	
	$("#productQty").val("");
	$("#_quantity").val("0");
	
	$('#locationCode').focus();
}

function nextBarcode(){
	$("#barcode").val("");
	$("#allocationId").val("");
	$("#batchNo").val("");
	$("#barcodeShow").val("");
	
	$("#qualityCode").val("");
	
	$("#productQty").val("");
	$("#_quantity").val("0");
	
	$('#barcode').focus();
}
