/*出货准备开始**/
var shop_id=0;
var prevTrIndex = 0,thisTrIndex=0;//默认3行，当前已添加0行
$(document).ready(function() {
    resettr();
})
function resettr(){
    $(".gridtable tr").each(function(i) { //初始化 id 和 index 属性
        $(this).attr("id", "tr_" + i).attr("index", i);
    });
}
//直接搜索商品
function searchgoods(){
    var keyword=$('#goods_sn').val();
    var query = new Object();
    query.sn=keyword;
    query.shop_id=shop_id;
    query.out_price=0;
    query.is_shop=0;
    $.ajax({
        type: "post",
        url: APP+"Shop/InvoicingOrder/add_goods_list.html",
        data: query,
        success: function(data){
            if(data.status==1){
                var list=data.data.list;
                var goods_index=list.index;
                product_list=[];
                var product = {};
                product.goods_index = goods_index;
                product.goods_name = list.goods_name;
                product.attr_key = list.attr_key;
                product.attr_name = list.attr?list.attr:'';
                product.supplier_id = list.suppliers_id;
                product.goods_id = list.id;
                product.unit_name = list.unit_name;
                product.supply_price = list.supply_price;
                product.goods_sn = list.goods_sn;
                if(list.goods_attr_sn) {
                    product.goods_attr_sn = list.goods_attr_sn;
                }
                product_list[goods_index] = product;
                sgoods(goods_index);
            }else{
                if(data.info){$.showErr(data.info,1,'hc');}
                else{choose_goods(2,'tab_d','','tab_d','',keyword,1);}//0：全部商品，1：本店商品
            }
            return false;
        }
    });
}
//选择商品准备出货
function sgoods(goods_index){
    if (goods_index=='' || goods_index==0){return false;}
    var flag=0;
    //查看表格中是否已有此商品有的话直接加数量
    $(".goodsn").each(function(){
        if($(this).attr('goods_index')==goods_index){
            var currentobj=$(this).next().next().next().children("input");
            var old_num=parseInt(currentobj.val());
            var new_num=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_num(currentobj);
            flag=1;
            return false;
        }
    });
    if(flag==1){return false;}
    var index=goods_index;
    //if(goods_list[index].stock<=0){$.showErr('暂无库存', 0, 'hc');return false;}
    var chu_id=$("select[name='chustock']").val();//出货单位ID

    var tpl="<tr>"
        +"<input type='hidden' name='infos[goods_name][]' value='"+product_list[index].goods_name+"' />"
        +"<input type='hidden' name='infos[goods_id][]' value='"+product_list[index].goods_id+"' />"
        +"<td class='money'><input type='hidden' name='infos[all_money][]' style='width:50px;' onchange='sum_money()' value='"+product_list[index].supply_price+"'>"+product_list[index].goods_name+"</td>"
        +"<td class='goodsn' goods_index='"+index+"' attr_key = "+product_list[index].attr_key+">";
    if(product_list[index].goods_attr_sn){
        tpl+=product_list[index].goods_attr_sn;
        tpl+="<input type='hidden' name='infos[goods_sn][]' value='"+product_list[index].goods_attr_sn+"' />";
    }else{
        tpl+=product_list[index].goods_sn;
        tpl+="<input type='hidden' name='infos[goods_sn][]' value='"+product_list[index].goods_sn+"' />";
    }
    tpl+="<input type='hidden' name='infos[goods_attr_sn][]' value='"+product_list[index].attr_key+"' /></td>"

    if(product_list[index].attr_name){
        tpl += "<td>"+product_list[index].attr_name+"</td>"
    }else{
        tpl += "<td>无</td>"
    }
    tpl+="<td class='shop_price'><input name='infos[supply_price][]' style='width:50px;' onchange='change_price(this)' value='"+product_list[index].supply_price+"'></td>"
    tpl+="<td class='num'><input name='infos[freight_num][]' style='width:50px;' type='number' min='1' onchange='change_num(this)' value='1'></td>";
        
    tpl+="<td><a onclick='delCurrentRow(this);' class='del' style='cursor:pointer;'>删除</a></td>"
    tpl+="</tr>";
    //当当前已添加行数大于等于默认行数时，将添加行数据，否则覆盖空行
    if(thisTrIndex>=prevTrIndex){
        $('#tab_d').append(tpl);
    }else{
        re=/^<(\/?)tr>/g;
        tpl=tpl.replace(re,'');
        $('#tr_'+(thisTrIndex+1)).html(tpl);
    }
    thisTrIndex=thisTrIndex+1;
    resettr();
    sum_money();//计算合计
}
function delCurrentRow(obj){
    if(confirm("确定要删除这个物品吗?")){
        delCurrentRows(obj);
        return false;
    }
}
function delCurrentRows(obj){
    var tr=$(obj).parent().parent();
    //删除当前行
    tr.remove();
    //当当前已添加行数小于等于默认行数时，将添加空行，否则将减少行数据
    if(thisTrIndex<=prevTrIndex){
        var tpl='<tr><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td></tr>';
        $('#tab_d').append(tpl);
    }
    thisTrIndex=thisTrIndex-1;
    resettr();
    sum_money();//计算合计
}
function clear_all(){
    if(confirm("确定要清空吗?")){
        $(".goodsn").each(function(){
            var tr=$(this).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);
            sum_money();
        });
        return false;
    }
}
//改变商品出货数量
function change_num(obj){
    var num = parseFloat($(obj).val());//数量
    if (isNaN(num) || num <= 0) {num = 1;}
    if(num.toString().indexOf(".")>-1){if(num.toString().split(".")[1].length>3){$.showErr('商品数量不能超过三位小数',1,'hc');}}
    num=parseFloat(num.toFixed(3));
    //var stock = parseInt($(obj).parent().next().html());
    //if(stock <= 0) {
    //    $.showErr('没有库存,确认删除', 0, 'hc',function(){
    //        var del=$(obj).parent().parent().find('td a.del');
    //        delCurrentRows(del);
    //    });
    //}else {
    //    if (stock < num) {num=stock;$.showErr('库存不足', 0, 'hc');}
        $(obj).val(num);
        var priceobj = $(obj).parent().parent().find("td.shop_price input");
        var price = parseFloat(priceobj.val());//本店价
        var sum_price =  parseFloat(num * price).toFixed(2);
        $(obj).parent().parent().find('.money input').val(foramtmoney(sum_price));
    //}
    sum_money();//计算合计
}
//改变商品单价
function change_price(obj){
    var price=parseFloat($(obj).val()); $(obj).val(parseFloat(price.toFixed(2)));
    var num=parseInt($(obj).parent().parent().find('td.num input').val());
    var money=parseFloat(price*num).toFixed(2);
    $(obj).parent().parent().find('td.money input').val(foramtmoney(money));
    sum_money();
}
//合计
function sum_money(){
    var sumprice = 0;
    var sumcount = 0;
    $("tr td.money input").each(function(){
        var one_sumprice=parseFloat($(this).val());
        sumprice= sumprice + one_sumprice;
        var one_sumcount=parseFloat($(this).parent().parent().find('td.num input').val());
        sumcount= sumcount + one_sumcount;
    });
    $("#sum_money").html(foramtmoney(sumprice));
    $("input[name='all_money']").val(foramtmoney(sumprice));
    $("#sum_count").html(parseFloat(sumcount).toFixed(3));
    $("input[name='count']").val(parseFloat(sumcount).toFixed(3));

}
/**出货准备结束**/

/**出货操作开始**/
//确认货单，输入备注
// function open_confirm(){
//     $(".btn3").attr('disabled',true);
//     var res=check_info();
//     if(res==false){return false;}
//     $('.confirm_insert').show();
//     $('.confirm_insert_maks').show();
// }
//关闭备注
function close_confirm(){
    $(".btn3").attr('disabled',false);
    $('.confirm_insert').hide();
    $('.confirm_insert_maks').hide();
}
function close_move(){
    $('.order_move').attr('style', 'display:none');
}
//检查必填项
function check_info(){
    if($("input[name='infos[goods_name][]']").length<=0){
        $.showErr('请选择商品出货',1,'hc');
        $(".btn3").attr('disabled',false);
        $(".confirm").attr('disabled',false);
        return false;
    }
    if(!shop_id){
        $.showErr('请选择出货门店',1,'hc');
        $(".btn3").attr('disabled',false);
        $(".confirm").attr('disabled',false);
        return false;
    }
    $("input[name='shop_id']").val(shop_id);
}
function open_confirm(){
    var res=check_info();
    if(res==false){return false;}
    $('.order_move').show();
    // $('.order_move').attr('style', 'display:block');
}
function sub_order(){
    $(".confirm").attr('disabled',true);
    var res=check_info();
    if(res==false){return false;}
    // $("input[name='goods_status']").val(3);
    // $("input[name='status']").val(3);
    $("input[name='out_type']").val(0);
    // $("input[name='out_price']").val(0);
    var all_pre_money=0;
    $("#pre_money input").each(function(){
        all_pre_money=all_pre_money+parseFloat($(this).val());
    });
    $("input[name='all_pre_money']").val(all_pre_money);
    var query = $("form[name='order_in_form']").serialize();
	if($("input[name='goods_status']").val() ==1){
		$.ajax({
			type: "post",
			url: APP+"Shop/InvoicingOrder/transfer_add.html",
			data: query,
			success: function(data){
				if(data.status==1){
					$.showSuccess(data.msg,1,'hc',function(){
						window.location.reload();
					},function(){
						window.location.reload();
					});
				}else{
					$.showErr(data.msg,1,'hc');
				}
				$(".confirm").attr('disabled',false);
				close_confirm();
				return false;
			}
		});
	}else{
		$.ajax({
			type: "post",
			url: APP+"Shop/InvoicingOrder/order_shipment_insert.html",
			data: query,
			success: function(data){
				if(data.status==1){
					$.showSuccess(data.msg,1,'hc',function(){
						window.location.reload();
					},function(){
						window.location.reload();
					});
				}else{
					$.showErr(data.msg,1,'hc');
				}
				$(".confirm").attr('disabled',false);
				close_confirm();
				return false;
			}
		});
		
		
		
		}
}
//格式化价格
function foramtmoney(num,len) {
    len = len > 0 && len <= 20 ? len : 2;
    var result = parseFloat(num);
    num=isNaN(result)?0:result;
    var numpow=Math.pow(10,len);
    result = Math.round(num * numpow) / numpow;//round四舍五入 ceil进一 floor舍去
    var s_x = result.toString();
    var pos_decimal = s_x.indexOf('.');
    if (pos_decimal < 0) {
       pos_decimal = s_x.length;
       s_x += '.';
    }
    while (s_x.length <= pos_decimal + len) {s_x += '0';}
    return s_x;
}
/**出货操作结束*/