$(function(){
 
	var focusId;
	$("input").focus(function(){
		//记住焦点位置
		focusId = this.id;
		//this.scrollIntoView(true);//回到顶部
		//window.setTimeout("myScrollIntoView()",100);  
	});	
	
	//如不使用延迟执行, 有时候会无效
	setTimeout(function() {
    	var $warehouseCode = localStorage.getItem('$warehouseCode');
		$("#warehouseCode").val($warehouseCode);
		
		$('#outShelfLocationCode').focus();
	}, 1000);

	//当失去焦点按回车时,焦点回到之前焦点位置
	$(window).keydown(function(event){
	 	if((event.keyCode==13)) {
	 		if(document.activeElement.id == null || document.activeElement.id ==''){
	 			//回到上次焦点地方
		 		//$("#"+focusId).focus();
	 		}
	 	}  
	});	

	//提交下架库位
    $('#outShelfLocationCode').keyup(function (event) {
        if (event.keyCode != "13") {return false;}
        $("#outShelfLocationCode").val(trimStr($("#outShelfLocationCode").val()));
        if($('#outShelfLocationCode').val()!=''){
        	//播放扫描声音
        	playSound('../raw/scan.wav');
         
        	submitOutShelfLocationCode();
        }
    });
 
    //提交商品条码
    $('#barcode').keyup(function (event) {
    	console.log("barcode："+event.keyCode)
    	if (event.keyCode != "13") {return false;}
    	console.log("barcode")
    	$("#barcode").val(trimStr($("#barcode").val()));
    	if($("#barcode").val() !='' ){
    		//播放扫描声音
        	playSound('../raw/scan.wav');
        	
    		submitBarcode();
    	}
    });
	
	//输入转移数量
    $('#qty').keyup(function (event) {
    	if (event.keyCode != "13") {return false;}
    	$("#qty").val(trimStr($("#qty").val()));
    	
    	if($("#qty").val() =='' ||  $("#qty").val() == 0){
			return;
    	}
    	
		if(isNaN($("#qty").val())){
			playSound('../raw/error.wav');
			mui.toast($("#qty").val()+'不是一个数字');  
			return;
		}
		if(parseInt($("#sysQty").val()) < parseInt($("#qty").val())){
			playSound('../raw/error.wav');
			mui.toast('转移数量不能大于可用数量');  
			return;
		}
		if(parseInt($("#qty").val())<=0){
			playSound('../raw/error.wav');
			mui.toast('转移数量不能小于等于0');  
			return;
		}
		playSound('../raw/scan.wav');
		//输入数量回车,光标到上架库位
		setFocus('onShelfLocationCode')    	
    });
	    
    //提交上架库位
     $('#onShelfLocationCode').keyup(function (event) {
    	if (event.keyCode != "13") {return false;}
    	$("#onShelfLocationCode").val(trimStr($("#onShelfLocationCode").val()));
    	
    	if($("#onShelfLocationCode").val() !='' ){
    		 submitInventoryMv();
    	}
    });
});


//提交下架库位
function submitOutShelfLocationCode(){
	var outShelfLocationCode=$("#outShelfLocationCode").val();
	
	var msgBody = {};
	msgBody.outShelfLocationCode=outShelfLocationCode;
	msgBody.warehouseCode=$("#warehouseCode").val();
	//序列化成字符串
	var msgBodyStr=JSON.stringify(msgBody)
	
	var appRequest = $appRequest;//复制请求封装对象
    appRequest.opType = OP_TYPE_MENU.INVENTORY_RANDOM_MV_1;
    appRequest.msg = msgBodyStr;//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.toast(appResponse.msg);
    			return;
    		}
        	
        	mui.toast(appResponse.msg);
        	setFocus('barcode');
        },
        error: function () {
        	playSound('../raw/error.wav');
        	mui.toast('网络断开或服务器发生异常');  
        }
    });
}

//提交商品条码
var inventoryMap = {};
var outShelfInventoryId = -1;
function submitBarcode() {
	outShelfInventoryId = -1;
	
	var outShelfLocationCode = $("#outShelfLocationCode").val();
	var barcode = $("#barcode").val();

	var msgBody = {};
	msgBody.outShelfLocationCode = outShelfLocationCode;
	msgBody.warehouseCode = $("#warehouseCode").val();
	msgBody.barcode = barcode;

	//序列化成字符串
	var msgBodyStr = JSON.stringify(msgBody)

	var appRequest = $appRequest; //复制请求封装对象
	appRequest.opType = OP_TYPE_MENU.INVENTORY_RANDOM_MV_2;
	appRequest.msg = msgBodyStr; //msg是消息内容主体
    console.log("$appRequestUrl:"+$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.toast(appResponse.msg);
				return;
			}
			$("#barcodeShow").val(barcode);

			var listInventory = appResponse.extend;

			if(listInventory.length > 1) { //出现多条记录时选择
				var listLi = [];
				for(var i = 0; i < listInventory.length; i++) {
					var inventorySingle = listInventory[i];
					inventoryMap[inventorySingle.id] = inventorySingle;
					listLi.push('<li class="mui-table-view-cell" onclick="selectInventory(\'' + inventorySingle.id + '\')">批次:' + inventorySingle.batchNo + ';	商品品质:' + inventorySingle.qualityName + ';	溯源:' + inventorySingle.inOrderNo1 + '; 可用数量:' + inventorySingle.qtyAvail + '  </li>');
				}
				var listLiStr = listLi.join('')
				$("#inventoryListDetail").html(listLiStr);
				mui("#inventoryListShow").popover('show'); //show hide toggle
				return
			}

			var inventorySingle = listInventory[0];
			$("#inOrderNo").val(inventorySingle.inOrderNo1);
			$("#batchNo").val(inventorySingle.batchNo)
			$("#qualityName").val(inventorySingle.qualityName)
			$("#sysQty").val(inventorySingle.qtyAvail)

			outShelfInventoryId = inventorySingle.id;

			console.log("outShelfInventoryId:" + outShelfInventoryId)

			setFocus('qty');
		},
		error: function() {
			playSound('../raw/error.wav');
			mui.toast('网络断开或服务器发生异常');
		}
	});
}
//选择一个库存
function selectInventory(inventoryId){
	outShelfInventoryId = inventoryId;
	 
	var inventorySingle=inventoryMap[outShelfInventoryId]
	$("#inOrderNo").val(inventorySingle.inOrderNo1);
    $("#batchNo").val(inventorySingle.batchNo)
    $("#qualityName").val(inventorySingle.qualityName)
    $("#sysQty").val(inventorySingle.qtyAvail)
    
    mui('#inventoryListShow').popover('toggle');
    setFocus('qty');
}

//提交完成移位
var isSubmintIng = false;//是否正在提交. 防止按回车太快
function submitInventoryMv() {
	if(isSubmintIng){return;}
	isSubmintIng = true;
	
	var outShelfLocationCode = $("#outShelfLocationCode").val();
	var barcode = $("#barcode").val();
	var onShelfLocationCode = $("#onShelfLocationCode").val();
	var qty = $("#qty").val();
	
	var msgBody = {};
	msgBody.outShelfLocationCode = outShelfLocationCode;
	msgBody.warehouseCode = $("#warehouseCode").val();
	msgBody.barcode = barcode;
	msgBody.onShelfLocationCode = onShelfLocationCode;
	msgBody.outShelfInventoryId = outShelfInventoryId;
	msgBody.qty = qty;
	
	//序列化成字符串
	var msgBodyStr = JSON.stringify(msgBody)

	var appRequest = $appRequest; //复制请求封装对象
	appRequest.opType = OP_TYPE_MENU.INVENTORY_RANDOM_MV_4;
	appRequest.msg = msgBodyStr; //msg是消息内容主体

	if(outShelfLocationCode == null || outShelfLocationCode == '') {
		playSound('../raw/error.wav');
		mui.toast('请输入下架库位');
		isSubmintIng = false;
		return;
	}
	if(barcode == null || barcode == '') {
		playSound('../raw/error.wav');
		mui.toast('请输入商品条码');
		isSubmintIng = false;		
		return;
	}	
	if(outShelfInventoryId == -1) {
		playSound('../raw/error.wav');
		mui.toast('请先提交下架库位,商品条码');
		isSubmintIng = false;		
		return;
	}
	if(qty == '' || qty < 0) {
		playSound('../raw/error.wav');
		mui.toast('转移数量必须大于0');
		isSubmintIng = false;		
		return;
	}
	if(onShelfLocationCode == null || onShelfLocationCode == '') {
		playSound('../raw/error.wav');
		mui.toast('请输入上架库位');
		isSubmintIng = false;		
		return;
	}
	if(onShelfLocationCode == outShelfLocationCode) {
		playSound('../raw/error.wav');
		mui.toast('下架库位号跟上架库位号不能相同');
		isSubmintIng = false;		
		return;
	}
	playSound('../raw/scan.wav');
	
	mui(document.getElementById("subButton")).button('loading'); //切换为loading状态
	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(); 
			mui(document.getElementById("subButton")).button('reset'); //重置button
			
			if(!appResponse.success) {
				playSound('../raw/error.wav');
				mui.alert(appResponse.msg, '警告', function() {
					//移库失败,光标停留在上架库位
					setFocus('onShelfLocationCode');
				});
				return;//return无效的,mui.alert是异步的
			} else {
				//不写在else里,也会被执行
				playSound('../raw/ok.wav');
				mui.toast(appResponse.msg);
				cleanAll()				
			}
		},
		error: function() {
			isSubmintIng = false;
			playSound('../raw/error.wav');
			mui.toast('网络断开或服务器发生异常');
		}
	});
}

//下一个转移任务
function cleanAll() {
	$(".allowClear").each(function() {
		$(this).val("")
	})
	$("#outShelfLocationCode").focus();
}