$(function(){
	var focusId;
	$("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) {
        if (event.keyCode != "13") {return false;}
        $("#outOrderNo").val(trimStr($("#outOrderNo").val()));
        //播放扫描声音
    	playSound('../raw/scan.wav');
    	
        submitOutOrderNo();
    });
	
    //提交箱号
    $('#boxNo').keyup(function (event) {
    	if (event.keyCode != "13") {return false;}
    	$("#boxNo").val(trimStr($("#boxNo").val()));
    	//播放扫描声音
    	playSound('../raw/scan.wav');
    	
    	submitBoxNo();
    });
    
    //条码回车
    $('#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()));
    	
    	submitOutBox();
    });
});

//提交出库单号
function submitOutOrderNo(){
	var outOrderNo = $('#outOrderNo').val();
   	if(outOrderNo == ''){return;}
   
   	var appRequest = $appRequest;//复制请求封装对象
   	appRequest.opType = OP_TYPE_MENU.OUT_BOXED_1;
   	appRequest.msg = outOrderNo;//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 outOrder = appResponse.extend;
        	
        	$("#outOrderId").val(outOrder.id);
        	$("#customerCode").val(outOrder.customerCode);
			$("#warehouseCode").val(outOrder.warehouseCode);
        		
        	$("#statusName").text(outOrder.statusName);
        	$("#shipwayName").text(outOrder.shipwayName);
        	
        	//刷新显示待装箱明细
        	refreshItems();
        	
        	//进入箱子操作
        	nextBox();//自动生成箱号
	        	
        	//自动提交箱号
        	if($("#isAutoCreateBox").val() == 'true'){submitBoxNo();}
        },
        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_BOXED_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;
    		}
        	//mui.toast(appResponse.msg);
	      	var waitQtyTotal = 0;
  			var itemList = appResponse.extend;
	  		for(var index = 0; index < itemList.length; index ++){
	  			var item = itemList[index];
	  			handleNullFiled(item);
	  			
	  			item.boxedQty = item.boxedQty != null ? item.boxedQty:0;
	  			var waitBoxQty = item.totalQty - item.boxedQty;//未装数量
	  			waitQtyTotal += waitBoxQty; 
	  			
	  			if(waitBoxQty > 0){
	  				waitBoxQty = "<span style='color:red;'><b>"+waitBoxQty+"</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.totalQty+"</div></th>";
	    			tr += "<th><div style='width:100%overflow: hidden;font-size: 9pt;text-align: left;'>"+waitBoxQty+"</div></th>";	
	  			tr += "</tr>";
	  			$("#itemList").append(tr);
	  		}
  		
  			$("#waitQtyTotal").text(waitQtyTotal);
      	},
      	error: function () {
      		mui.toast('网络断开或服务器发生异常');  
      	}
	});	
}

//提交箱号
//提交装箱
var isSubmintBoxNoIng = false;//是否正在提交
function submitBoxNo(){
	if(isSubmintBoxNoIng){return;}
	isSubmintBoxNoIng = true;
	
	var boxNo = $('#boxNo').val();
	var outOrderNo = $('#outOrderNo').val();
	var outOrderId = $('#outOrderId').val();
	if(boxNo=='' || boxNo==null){
	   mui.toast('箱号不能为空');  
	   return
	}
	if(outOrderNo=='' || outOrderNo==null){
	   mui.toast('订单号不能为空');  
	   return
	}
	 
	var formData = {outOrderId:outOrderId,outOrderNo:outOrderNo,boxNo:boxNo};
	
   	var appRequest = $appRequest;//复制请求封装对象
   	appRequest.opType = OP_TYPE_MENU.OUT_BOXED_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) {
        	isSubmintBoxNoIng = false;
        	
        	if(!appResponse.success){
        		playSound('../raw/error.wav');
        		mui.alert(appResponse.msg, '警告', function() {  setFocus('orderNo');  }); 
    			return;
    		}
	      	var box = appResponse.extend;
	      	$("#boxId").val(box.id);
	      	
	      	nextBarcode();
    	},
    	error: function () {
    		isSubmintBoxNoIng = false;
      		mui.toast('网络断开或服务器发生异常');  
	    }
  	});
}

//提交条码
function submitBarcode(){
	var outOrderNo = $('#outOrderNo').val();
	var outOrderId=$("#outOrderId").val();
	var boxNo=$('#boxNo').val();
	var barcode= $('#barcode').val();
	if(outOrderId == ''){
		mui.toast('请先提交出库单号');  
		return;
	}
	if(boxNo == ''){
		mui.toast('箱子号码不能为空');  
		return;
	}
	if(barcode == ''){
		mui.toast('商品条码不能为空');  
		return;
	}
	//显示商品条码
	$("#barcodeShow").val(barcode);
	
	//判断是否扫描条码增加数量 
	if($('#autoSubmit').val() == 'true') {
		//扫描加1
		var oralQty = $("#productQty").val();
		if(oralQty == null || oralQty == ''){oralQty = 0;}
		$("#productQty").val((parseInt(oralQty)+1));
		//回到条码输入框,用户应当继续扫描条码
		
		//每扫一条就自动提交,因为商品摆放是杂乱的.不能要求每次拿相同的商品扫
		submitOutBox(); //-- 每扫描一次,提交,并判断完成整单还是整个条码
		//刷新明细,交互次数太多... --待改善
		
	} else {
		//非自动提交.. 需手工输入装箱数量
		$("#productQty").val("");//装箱数量
		setFocus('productQty');
	}
}

//提交装箱
var isSubmintIng = false;//是否正在提交
function submitOutBox(){
	if(isSubmintIng){return;}
	isSubmintIng = true;
	
	var outOrderNo = $('#outOrderNo').val();
	var outOrderId = $('#outOrderId').val();
	var boxNo = $('#boxNo').val();
	var boxId = $('#boxId').val();
	var barcode = $("#barcode").val();
	//如果是扫描增加数量,条码输入框是空的,从展示条码取
	var barcode= $('#barcode').val();
	if(barcode == null || barcode == ''){
		barcode = $("#barcodeShow").val();	
		$('#barcode').val(barcode);
	}
	var productQty = $("#productQty").val();
	if(boxNo==''){
	 	isSubmintIng = false;
	 	mui.alert('箱号不能为空', '警告', function() {  setFocus('boxNo');  }); 
	 	return;
	}
	if(boxId==''){
		isSubmintIng = false;
		mui.alert('请先提交箱号,在箱号输入框按回车', '警告', function() {  setFocus('boxNo');  }); 
		return;
	}
	if(productQty==''){
		isSubmintIng = false;
		mui.alert('商品数量不能为空', '警告', function() {  setFocus('productQty');  }); 
		return;
	}
	if(barcode==''){
		 isSubmintIng = false;
		 mui.alert('条码不能为空', '警告', function() {  setFocus('barcode');  }); 
		 return
	}
	if(outOrderNo==''){
		 isSubmintIng = false;
		 mui.alert('订单号不能为空', '警告', function() {  setFocus('outOrderNo');  }); 
		 return;
	}
		 
	var formData = {outOrderId:outOrderId,outOrderNo:outOrderNo,boxNo:boxNo,boxId:boxId,barcode:barcode,productQty:productQty};
	 
 	var appRequest = $appRequest;//复制请求封装对象
   	appRequest.opType = OP_TYPE_MENU.OUT_BOXED_4;
   	appRequest.msg = JSON.stringify(formData);//msg是消息内容主体
	
	var nwaiting = plus.nativeUI.showWaiting('正在提交中...');
	
	$.ajax({
        type: 'POST',
        url: $appRequestUrl,
        contentType: "application/json; charset=utf-8",
        data: JSON.stringify(appRequest),
        success: function (appResponse) {
        	isSubmintIng = false;
        	nwaiting.close(); 
        	
        	if(!appResponse.success){
        		playSound('../raw/error.wav');
        		mui.alert(appResponse.msg, '警告', function() {  setFocus('locationCode');  }); 
    			return;
    		}
        	mui.toast(appResponse.msg);
        	
        	//播放成功声音
        	playSound('../raw/ok.wav'); 
			
        	
    		//整单完成. 下一个出库单
        	if(appResponse.extend){
        		cleanAll();
        		return;
        	}
       		
       		//刷新显示待装箱明细
       		refreshItems();
       		//下一个条码
       		nextBarcode();
       },
       error: function () {
        	isSubmintIng = false;
        	nwaiting.close(); 
        	
        	playSound('../raw/error.wav');
        	mui.toast('网络断开或服务器发生异常'); 
       }
	});
}

function cleanAll(){
	isSubmintBoxNoIng = false;
	isSubmintIng = false;
	$("#outOrderId").val("");
	$("#outOrderNo").val("");
	
	$("#statusName").text("");
	$("#shipwayName").text("");
	$("#waitQtyTotal").text("");
	
	$("#itemList").empty();
	
	$("#warehouseCode").val("");
	$("#customerCode").val("");
	
	$("#boxNo").val("");
	$("#boxId").val("");
	
	$("#barcode").val("");
	$("#allocationId").val("");
	$("#barcodeShow").val("");
	
	$("#productQty").val("");
	$("#_quantity").val("0");
		
	$('#outOrderNo').focus();
}

//下一个箱子
function nextBox(){
	$("#boxId").val('');
	$("#boxNo").val('');
	//自动生成箱号
	if($("#isAutoCreateBox").val() == 'true'){genBoxNo();}
	$("#boxNo").focus();
}

//下一个条码
function nextBarcode(){
	$("#barcode").val("");
	$("#barcodeShow").val("");
	$("#productQty").val("");
		
	$("#barcode").focus();
}

//生成箱子号码
function genBoxNo(){
	//获取完整的日期  
	var date=new Date;  
	var year=date.getFullYear();
	
	var month=date.getMonth()+1;  
	month =(month<10 ? "0"+month:month);
	
	var day=date.getDate();  
	day =(day<10 ? "0"+day:day);
	
	var hours = date.getHours();
	hours =(hours<10 ? "0"+hours:hours);
	
	var minutes = date.getMinutes();
	minutes =(minutes<10 ? "0"+minutes:minutes);
	
	var seconds = date.getSeconds();
	seconds =(seconds<10 ? "0"+seconds:seconds);
	
	var currentDate = (year.toString() + month.toString() + day.toString() + hours.toString() + minutes.toString() + seconds.toString());
		
	//2019-05-11决定简化箱号,使用数字1,2,3..方便直观看到订单有几个箱子,方便输入
	$("#boxNo").val("1");
	//$("#boxNo").val(currentDate);
}