//出库、调货
/**出库准备开始**/
var shop_id=0;
var prevTrIndex = 3,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=$("select[name='shop_id']").val();
    shop_id=$("select[name='shop_id']").val();
    query.is_shop=1;
    query.is_return_goods=1;
    query.is_stock=1;
    $.ajax({
        type: "post",
        url: APP+"Ajax/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.name?list.name:'无';
                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;
                product.stock = list.stock;
                if(product.stock<=0){
                    product.profit_num=1;
                    product.loss_num=0;
                    product.profit_price=parseFloat(product.supply_price*product.profit_num).toFixed(2);
                    product.loss_price=parseFloat(0).toFixed(2);
                }else{
                    product.loss_num=parseFloat(product.stock-1);
                    product.profit_num=0;
                    product.loss_price=parseFloat(product.supply_price*product.loss_num).toFixed(2);
                    product.profit_price=parseFloat(0).toFixed(2);
                }
                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);}
            }
            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().children("input");
            var old_num=parseFloat(currentobj.val());
            var new_num=parseFloat(old_num + 1);$(this).children("td:last-child").val();
            currentobj.val(new_num);
            change_num(currentobj);
            flag=1;
            return false;
        }
    });
    if(flag==1){return false;}
    var index=goods_index;
    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+"' />"
        +"<input type='hidden' name='infos[goods_index][]' value='"+index+"' />"
        +"<td>"+product_list[index].goods_name+"</td>"
        +"<td>"+product_list[index].attr_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>";
    tpl+="<td>"+product_list[index].stock+"</td>"
        +"<td class='num'><input name='infos[reality_num][]' style='width:50px;' type='number' min='1' onchange='change_num(this)' value='1'></td>"
        +"<td class='loss_num'><input name='infos[loss_num][]' style='width:50px;' type='text' readonly='readonly' value='"+product_list[index].loss_num+"'></td>"
        +"<td class='profit_num'><input name='infos[profit_num][]' style='width:50px;' type='text' readonly='readonly' value='"+product_list[index].profit_num+"'></td>";
    if(product_list[index].unit_name){
        tpl += "<td>"+product_list[index].unit_name+"</td>";
    }else{
        tpl += "<td>无</td>";
    }
    tpl += "<td><input type='hidden' name='infos[supplier_id][]' value='"+product_list[index].supplier_id+"'>";
    if(product_list[index].supplier_id==0 || !product_list[index].supplier_id || product_list[index].supplier_id==null || !supplier_list || supplier_list==null || supplier_list==''){
        tpl += "空";
    }
    if(supplier_list && product_list[index].supplier_id!=0) {
        tpl += supplier_list[product_list[index].supplier_id];
    }
    tpl += "</td>"
        +"<td class='shop_price'>"+product_list[index].supply_price+"<input name='infos[supply_price][]' style='width:50px;' type='hidden' value='"+product_list[index].supply_price+"'></td>"
        +"<td class='money'><input name='infos[loss_money][]' readonly='readonly' style='width:100px; background-color:#f9f9f9' value='"+product_list[index].loss_price+"'></td>"
        +"<td class='profit_money'><input name='infos[profit_money][]' readonly='readonly' style='width:100px; background-color:#f9f9f9' value='"+product_list[index].profit_price+"'></td>"
        +"<td class='stock'><input type='hidden' name='infos[stock][]' value='"+product_list[index].stock+"' /><a onclick='delCurrentRow(this);' class='del' style='cursor:pointer;'>删除</a></td>"
        +"</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><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 change_num(obj){
    var num = parseFloat($(obj).val());//数量
    var stock = parseFloat($(obj).parent().parent().find('td.stock input').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));
    $(obj).val(num);
    var priceobj = $(obj).parent().parent().find("td.shop_price input");
    var price = parseFloat(priceobj.val());//本店价
    var new_num = num - stock;
    if(new_num>=0){
        $(obj).parent().parent().find("td.profit_num input").val(parseFloat(new_num.toFixed(3)));
        $(obj).parent().parent().find("td.loss_num input").val(0);
        var sum_price = parseFloat(new_num * price).toFixed(2);
        $(obj).parent().parent().find('.profit_money input').val(foramtmoney(sum_price));
        $(obj).parent().parent().find('.money input').val(foramtmoney(0));
    }
    if(new_num<0){
        var loss_num = stock - num;
        $(obj).parent().parent().find("td.loss_num input").val(parseFloat(loss_num.toFixed(3)));
        $(obj).parent().parent().find("td.profit_num input").val(0);
        var sum_price = parseFloat(loss_num * price).toFixed(2);
        $(obj).parent().parent().find('.money input').val(foramtmoney(sum_price));
        $(obj).parent().parent().find('.loss_money input').val(foramtmoney(0));
    }
    sum_money();//计算合计
}
//合计
function sum_money(){
    var sum_loss_price = 0;var sum_profit_price = 0;
    var sum_loss_count = 0;var sum_profit_count = 0;
    $("tr td.money input").each(function(){
        var loss_sumprice=parseFloat($(this).val());//盘亏金额
        sum_loss_price= parseFloat(sum_loss_price) + loss_sumprice;
        var profit_sumprice=parseFloat($(this).parent().parent().find('td.profit_money input').val());//盘盈金额
        sum_profit_price= parseFloat(sum_profit_price) + profit_sumprice;
        var loss_sumcount=parseFloat($(this).parent().parent().find('td.loss_num input').val());//盘亏总数
        sum_loss_count= parseFloat(sum_loss_count) + loss_sumcount;
        var profit_sumcount=parseFloat($(this).parent().parent().find('td.profit_num input').val());//盘盈总数
        sum_profit_count= parseFloat(sum_profit_count) + profit_sumcount;
    });
    $("#sum_loss_money").html(foramtmoney(sum_loss_price));
    $("#sum_profit_money").html(foramtmoney(sum_profit_price));
    $("input[name='sum_loss_money']").val(foramtmoney(sum_loss_price));
    $("input[name='sum_profit_money']").val(foramtmoney(sum_profit_price));
    $("#sum_loss_count").html(parseFloat(sum_loss_count.toFixed(3)));
    $("#sum_profit_count").html(parseFloat(sum_profit_count.toFixed(3)));
    $("input[name='sum_loss_count']").val(parseFloat(sum_loss_count.toFixed(3)));
    $("input[name='sum_profit_count']").val(parseFloat(sum_profit_count.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 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;}
}
function confirm_order(){
    $(".confirm").attr('disabled',true);
    var res=check_info();
    if(res==false){return false;}
    $("input[name='shop_id']").val(shop_id);//出库类型
    var query = $("form[name='order_in_form']").serialize();
    $.ajax({
        type: "post",
        url: APP+"InvoicingOrder/confirm_pan_add.html",
        data: query,
        success: function(data){
            if(data.status==1){
                $.showSuccess(data.msg,1,'hc',function(){
                    window.location.href=APP+'Invoicing_order/bad_list';
                },function(){
                    window.location.href=APP+'Invoicing_order/bad_list';
                });
            }else{
                $.showErr(data.msg,1,'hc');
            }
            $(".confirm").attr('disabled',false);
            close_confirm();
            return false;
        }
    });
}
/**出货操作结束**/