$(document).ready(function() {
    $("#prevTrIndex").val("-1"); //默认-1        
	resettr();
	clickTr(0);
	$("#goods").change(function (){
		var goodssn=$(this).val();
		sgoods(goodssn);
	});
	$("#shops").change(function (){
		$("#shop_id").val($(this).val());
	});
	$("#c_type").change(function(event) {
		$('#c_type').val($(this).val());
	});

	$("#chustock").change(function(event) {
		if ($('#order_status').val() == 4 && $('#chustock').val() != 0 && $('#rustock').val() != 0 ) {
			if ($('#chustock').val() == $('#rustock').val()) {
				$.showErr('出入库不能相同',0,'hc');
				$("#chustock").val('');
				return false;
			};
		};		
		if ($('#order_status').val() == 5 && $('#chustock').val() != '') {
			var query = new Object();
			query.id = $('#chustock').val();
		    $.ajax({
			    url: APP+"Storage/search_supplier",
				data:query,
				type:"post",
			    success: function(data){
			      	var html = "<option value='0'>==请选择==</option>";
			      	if(data.status == 1){ 
		              	for(var i=0;i<data.info.length;i++){
		              		html += "<option value='"+data.info[i].id+"'>"+data.info[i].name+"</option>";
		              	}
			            $("#rustock").html(html);
			      	}else{
			      		$("#rustock").html(html);
			      		$.showErr(data.msg,0,'hc');
			      	}
					return false;
			    }
		  	});
		}
		$('#c_dw').val($(this).val());
	});

	$("#ru_type").change(function(event) {
		$('#r_type').val($(this).val());
	});

	$("#rustock").change(function(event) {
		if ($('#order_status').val() == 4 && $('#chustock').val() != 0 && $('#rustock').val() != 0 ) {
			if ($('#chustock').val() == $('#rustock').val()) {
				$.showErr('出入库不能相同',0,'hc');
				// searchshops('ru_name');
				$("#rustock").val('');
				return false;
			};
		};
		$('#r_dw').val($(this).val());
	});

	$("#is_order").change(function(event) {
		$('#isorder').val($(this).val());
	});
	sum_money();
})
	
$(document).keydown(function(event){
	if(event.keyCode==13){
		$(':focus').parent().next().find('button').triggerHandler('click');
		return false;
	}
}); 

function resettr(){
    $(".gridtable tr").each(function(i) { //初始化 id 和 index 属性
        $(this).attr("id", "tr_" + i).attr("index", i);
	}).click(function() { //鼠标单击
		clickTr($(this).attr("index"));
	});
}
function clickTr(currTrIndex) {
    var prevTrIndex = $("#prevTrIndex").val();
    if (currTrIndex > -1) {
        $("#tr_" + currTrIndex).addClass("over");
    }
	$("#tr_" + prevTrIndex).removeClass("over");
    $("#prevTrIndex").val(currTrIndex);
}
function searchgoods(obj){//退货单用参数

	var chu_stock = $("#chustock").val();//出库单位下拉框
	var ru_stock = $("#rustock").val();//入库单位下拉框
	var substrs=$('#goods_sn').val().trim();//商品输入框
    if (substrs==''){
      $.showErr('商品不能为空',0,'hc');
      return false;  
    } 

    if (chu_stock=='' || chu_stock==0 ){
      $.showErr('请先选择出库单位',0,'hc');
      return false;  
    }
    if (obj == 5 ){
	    if (ru_stock=='' || ru_stock==0 ){
	      $.showErr('请先选择入库单位',0,'hc');
	      return false;  
	    }
    }else{
    	ru_stock = 0;
    }

  	var goods_sn=$('#goods_sn').val();//商品名称或编号
  	// var chu=$('#chustock').val();//出货单位ID


  	var chu_type=$('#c_type').val();//出库单位类型 2：供应商, 3：平台仓库
  	var query = new Object();
	query.goods_sn = goods_sn;  //商品关键词
	query.chu_type = chu_type;  //供货商/仓库
	query.chu_id = chu_stock;   //出库单位id
	query.ru_id = ru_stock;     //入库单位id
  	$.ajax({
	    url: APP+"Storage/search_goods",
		data:query,
		type:"post",
		dataType:"json",
	    success: function(data){
	      	var html = "<option value='0'>==请选择==</option>";
	      	if(data.status == 1){ 
              	for(var i=0;i<data.info.length;i++){
              		if(data.info[i]['attr_name']){
              			html += "<option value='"+data.info[i]['attr_key']+"'>"+data.info[i]['goods_name']+"("+data.info[i]['goods_sn']+")"+data.info[i]['attr_name']+"</option>";
              		}else{
 						html += "<option value='"+data.info[i]['attr_key']+"'>"+data.info[i]['goods_name']+"("+data.info[i]['goods_sn']+")"+"</option>";
              		}
              	}
	            $("#goods").html(html);
	      	}else{
	      		$("#goods").html(html);
	      		$.showErr(data.msg,0,'hc');
	      	}
			return false;
	    }
  	}); 
}


function cha(goods,type){
	var query = new Object();
	query.goods = goods;
	query.type = type;
	$.ajax({
	    url: APP+"Storage/search_dian",
		data:query,
		type:"post",
		dataType:"json",
	    success: function(data){
	      	var html = "<option value='0'>==请选择==</option>";
	      	if(data.status == 1){
	      		html += "<option value='"+data.id+"'>"+data.name+"</option>";
	        	$("#chustock").html(html);
	      	}else{
	        	$("#chustock").html(html);
	      		$.showErr(data.msg,0,'hc');
	      	}
			return false;
	    }
  	}); 
}

function searru(){
	//供货商/仓库
	var chu_stock = $("#chustock").val();
    if (chu_stock=='' || chu_stock==0 ){
		$.showErr('出库单位不能为空',0,'hc');
      return false;  
    }
	var ru_name = $("#ru_name").val();
	var query = new Object();
	query.chu_id = chu_stock;
	query.chu_name = ru_name;
	if (ru_name==''){
		$.showErr('关键字不能为空',0,'hc');
      return false;  
    }
    $.ajax({
	    url: APP+"Storage/searchu",
		data:query,
		type:"post",
	    success: function(data){
	      	var html = "<option value='0'>==请选择==</option>";
	      	if(data.status == 1){ 
              	for(var i=0;i<data.info.length;i++){
              		html += "<option value='"+data.info[i].id+"'>"+data.info[i].name+"</option>";
              	}
	            $("#rustock").html(html);
	      	}else{
	      		$("#rustock").html(html);
	      		$.showErr(data.msg,0,'hc');
	      	}
			return false;
	    }
  	}); 

}



function searchshops(id,order_type,storage_type){

	var id_name = '#'+id;
	if (id == 'chu_name') {
		var stock = '#chustock';
	}else if (id == 'ru_name') {
		var stock = '#rustock';
	};
	var keyword=$(id_name).val().trim();
    if (keyword==''){
    	$.showErr('关键字不能为空',0,'hc');
      	return false;  
    }
  	var query = new Object();
	query.ru_name = keyword;
	query.order_type = order_type;
	query.storage_type = storage_type;
  	$.ajax({
	    url: APP+"Storage/search_shops",
		data:query,
		type:"post",
	    success: function(data){
	      	var html = "<option value='0'>==请选择==</option>";
	      	if(data.status == 1){ 
              	for(var i=0;i<data.info.length;i++){
              		html += "<option value='"+data.info[i].id+"'>"+data.info[i].name+"</option>";
              	}
	            $(stock).html(html);
	      	}else{
	            $(stock).html(html);
	      		$.showErr(data.msg,0,'hc');
	      	}
			return false;
	    }
  	}); 
}

function change_price(obj){
	var num = parseInt($(obj).val());//数量
	if (isNaN(num) || num <= 0) {
		$(obj).val(1);
		num = 1;
	};
	var stock = parseInt($(obj).parent().next().html());
    if(stock < num){
    	$(obj).val(stock);
    	$.showErr('库存不足',0,'hc');
    }
	var priceobj = $(obj).parent().next().next().find("input");
	var price = parseFloat(priceobj.val());//本店价
	var sum_price = num*price;
	$(obj).parent().next().next().next().html(sum_price);
	sum_money();//计算合计
}
function sum_money(){
	var sumprice = 0;
	$(".money").each(function(){
        var one_sumprice=parseFloat($(this).html());
        sumprice= sumprice + one_sumprice;
    });
    $("#summoney").val(sumprice);
	$("#sum_money").html(sumprice);
}
function searchu(){
	//供货商/仓库
	var chu_name = $("#chu_name").val();
	var query = new Object();
	query.chu_name = chu_name;
	if (chu_name==''){
		$.showErr('关键字不能为空',0,'hc');
      return false;  
    }
    $.ajax({
	    url: APP+"Storage/searchu",
		data:query,
		type:"post",
	    success: function(data){
	      	var html = "<option value='0'>==请选择==</option>";
	      	if(data.status == 1){ 
              	for(var i=0;i<data.info.length;i++){
              		html += "<option value='"+data.info[i].id+"'>"+data.info[i].name+"</option>";
              	}
	            $("#chustock").html(html);
	      	}else{
	      		$("#chustock").html(html);
	      		$.showErr(data.msg,0,'hc');
	      	}
			return false;
	    }
  	}); 

}
function sgoods(goodssn){

	if (goodssn=='' || goodssn==0){
		$.showErr('请选择商品',0,'hc');
      return false;  
    }

	var chu=$('#chustock').val();//出货单位ID
	var chu_id = $("input[name = 'goods_type[chu_id][]']");

	var flag = 0;
	if(chu_id.length > 0){
        chu_id.each(function(){
            var id = $(this).val();
            if(chu != id){//所有商品必须是一个供应商的
            	$.showErr('商品必须出自一个出库单位',0,'hc');
            	flag = 1;
      			return false; 
            }
        });
	}
	if (flag) {
		return false;
	};

	var flag=0;
    //查看表格中是否已有此商品有的话直接加数量
    $(".goodsn").each(function(){
       	if($(this).attr('attr_key')==goodssn){
	        var currentobj=$(this).next().children(":first");
	        var old_num=currentobj.val();
	        var new_num=parseInt(old_num) + 1;
	        var stock=parseInt($(this).next().next().html());
            if(stock < new_num){
              new_num=old_num;
              $.showErr('库存不足',0,'hc');
            }
	        currentobj.val(new_num);
	        change_price(currentobj);//计算合计
	        flag=1;
	        return false;     
       	}
    });
    if(flag==1){
      return false;
    }
    var goods=$('#goods_sn').val();//商品名称或编号
    var chu=$('#chustock').val();//出货单位ID
  	var goods_info=$('#goods_info').val();
  	var type=$('#c_type').val();//出库单位类型 2：供应商, 3：平台仓库
  	// var sid=$('#sid').val();
  	var ru=$('#r_dw').val();//入库单位ID
  	var query = new Object();
	query.goods_sn = goods;//商品名称或编号
	query.attr_sn = goodssn;//属性编号
	query.type = type;//出库单位类型 1：供应商, 2：平台仓库
	query.chu_id = chu;//出货单位ID
	// query.cid = cid;
	if($('#order_status').val() == 5){//退货单
		query.ru_id = ru;
	}else{
		query.ru_id = 0;
	}
	
  	$.ajax({
	    url: APP+"Storage/sgoods",
		data:query,
		type:"post",
		dataType:"json",
	    success: function(data){
	      	if(data.status==6){
		        $.showErr('没有'+substrs+'这个商品',0,'hc');
		        $('#goods_sn').val('');
		        $('#goods_sn').focus();
	      	}
	      	if(data.status == 1){ 

		        var thisnum=parseInt($('#thisTrIndex').val());

		        var supplier_id=parseInt($('#supplier_id').val());
		        if(supplier_id){
		        	var n=0;
		        }else{
		        	var n=4;
		        }
		        if (thisnum > n) {
		           $('#tab_d').append(data.tr);
		        }else{
		           re=/^<(\/?)tr>/g;
		           data.tr=data.tr.replace(re,'');
		           $('#tr_'+thisnum).html(data.tr);
		        }      
		        thisnum=thisnum + 1;       
		        $('#thisTrIndex').val(thisnum);
		        clickTr(0);
		        resettr();
		        sum_money();//计算合计
	      	}else{
	      		$.showErr(data.msg,0,'hc');
	      	}
	    }
  	});  
}
function add_stock(t){
	$(".btn3").attr('disabled',true);
	var goodsn = $(".goodsn").attr('attr_key');

	if (typeof(goodsn) == "undefined") {
		$.showErr('请选择商品',0,'hc');
		return false;
	};

	if ($("#rustock").val() == '' || $("#rustock").val() == 0) {
		$.showErr('请选择入库单位',0,'hc');
		return false;
	};

	var flag = 0;
	$(".stock").each(function(){
		if($(this).html() < 1){
			$.showErr($(this).attr('goods_name')+'商品库存不足',0,'hc');
			flag = 1;
			return false;
		}
	})
	if (flag) {
		return false;
	};

	if(t==1){//订货单
		var r=confirm("是否确认生成订货单？");
	}else if(t==2){
		var r=confirm("是否确认生成调拨单？");
	}else if(t==3){
		var r=confirm("是否确认生成入库单？");
	}else if(t==5){
		var r=confirm("是否确认生成退货单？");
	}
  	if (r==true){
		var form = $("form[name='info']");
		var query = $(form).serialize();
		var url = APP+"Storage/add_stock";
		$.ajax({
			url:url,
			data:query,
			type:"post",
			success:function(data){
				$(".btn3").attr('disabled',false);
				if(data.status == 1){
					if(data.oid){
						window.open(data.url); 
					}
				}else{
					$.showErr(data.msg,0,'hc');
				}
				return false;
			}
		});
	}else{
		$(".btn3").attr('disabled',false);
   		return false;
  	}
}
function delCurrentRow(obj){ 
    if(confirm("确定要删除这个物品吗?")){ 
      	var tr=$(obj).parent().parent();
     	var num=parseInt(tr.attr('index'));
      	var type=$("#type").val();
      	if(type == 0){

      	 	var tpl='<td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td>&nbsp;</td>';   
      	}else if(type == 1){
			var tpl='<td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td>&nbsp;</td>';
      	}
      	tr.remove();
      	htmls='<tr>'+tpl+'</tr>';
      	$('#tab_d').append(htmls);  
      	var thisnum=parseInt($('#thisTrIndex').val());  
      	thisnum=thisnum - 1;    
      	$('#thisTrIndex').val(thisnum);
      	resettr();
      	sum_money();//计算合计
      	return false;
    }
}