//改变选中的值
/**进货准备开始**/
var supplier_list=new Object();
var prevTrIndex = 0,thisTrIndex=0,yi_count=0;//默认3行，当前已添加0行
$(document).ready(function() {
	$("#goods").change(function (){
		var goodssn=$(this).val();
		sgoods(goodssn);
	});
});
//直接搜索商品
function searchgoods(){
    var keyword=$('#keyword').val();
    if(keyword)$('#search_keywords').val(keyword);
    var is_shop = $("input[name='is_shop']").val();
    if(is_shop != 1)is_shop = 0;
    var query = new Object();
    query.sn=keyword;
    query.is_shop=1;
    $.ajax({
        type: "post",
        url: APP+"Shop/InvoicingOrder/add_goods_list.html",
        data: query,
        success: function(data){
        console.log(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.shop_price = list.shop_price;
                product.goods_sn = list.goods_sn;
                product.stock = list.stock;
                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;
    var new_num=1;
    //查看表格中是否已有此商品有的话直接加数量
    $(".goodsn").each(function(){
        if($(this).attr('goods_index')==goods_index){
            var currentobj=$(this).children("input");
            var old_num=parseInt(currentobj.val());
            new_num=old_num + 1;
            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+"' />"
        +"<input type='hidden' name='infos[storage_id][]' value='1' />"
        +"<td>"+product_list[index].goods_name+"</td>"
        +"<td>";
    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 class='stock'><input type='hidden' name='infos[stock][]' value='"+product_list[index].stock+"' />"+product_list[index].stock+"</td>";
    var unit_all_stock=(product_list[index].stock?parseInt(product_list[index].stock):0);
    var unit_reality_num=1;
    product_list[index].loss_num=product_list[index].profit_sum=0;
    if((unit_all_stock-unit_reality_num)>0){//盘盈
        product_list[index].loss_num=unit_all_stock-unit_reality_num;
    }else{//盘亏
        product_list[index].profit_sum=unit_reality_num-unit_all_stock;
    }
    tpl+="<td class='profit_sum'><input type='hidden' name='infos[profit_sum][]' value='"+product_list[index].profit_sum+"' /><span>"+product_list[index].profit_sum+"</span></td>";
    tpl+="<td class='loss_num'><input type='hidden' name='infos[loss_num][]' value='"+product_list[index].loss_num+"' /><span>"+product_list[index].loss_num+"</span></td>";   

    tpl+="<td>"+product_list[index].attr_name+"</td>"; 
    tpl+="<td class='num goodsn' goods_index='"+index+"' attr_key = "+product_list[index].attr_key+"><input name='infos[freight_num][]' style='width:50px;' type='number' min='1' onchange='change_num(this)' value='1'></td>"           
        // +"<td class='money'><input type='hidden' name='infos[all_money][]' style='width:50px;' value='"+product_list[index].supply_price+"'><span>"+product_list[index].supply_price+"</span></td>"
        +"<td><a onclick='delCurrentRow(this);' class='del' style='cursor:pointer;'>删除</a></td>"
        +"</tr>";
    var wei_count = 0;
    var sum_count = $("input[name='sum_countval']").val();
    yi_count = yi_count + 1;
    wei_count = parseInt(sum_count - yi_count);
    $("#yi_count").html(yi_count);
    $("#wei_count").html(wei_count);
    //当当前已添加行数大于等于默认行数时，将添加行数据，否则覆盖空行
    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 change_num(obj){
    var num = parseInt($(obj).val());//数量
    if (isNaN(num) || num <= 0) {num = 1;}
    $(obj).val(num);
    var priceobj = $(obj).parent().parent().find("td.shop_price input");
    var price = parseFloat(priceobj.val());//本店价
    var sum_price = num * price;
    $(obj).parent().parent().find('.money input').val(sum_price);
    $(obj).parent().parent().find('.money span').html(sum_price);

    var unit_all_stock=$(obj).parent().parent().find('.stock input').val();
    var loss_num = profit_sum = 0;
    if((unit_all_stock-num)>0){//盘盈
        loss_num=unit_all_stock-num;
    }else{//盘亏
        profit_sum=num-unit_all_stock;
    }
    $(obj).parent().parent().find('.loss_num span').html(loss_num);
    $(obj).parent().parent().find('.loss_num input').val(loss_num);
    $(obj).parent().parent().find('.profit_sum span').html(profit_sum);
    $(obj).parent().parent().find('.profit_sum input').val(profit_sum);
    sum_money();//计算合计
}
// 输入入库数量change事件
function change_loss(obj){
	var num = parseInt($(obj).val());//盘点数量
	if (isNaN(num) || num < 0) {
		$(obj).val(1);
		num = 1;
	};
	if(num < 1){
		$.showErr('订货数量不能小于1',2,'hc');
		$(obj).val(1);
		num = 1;
	}
	var priceobj = $(obj).parent().prev().prev().prev().find("input");
	var price = parseFloat(priceobj.val());//本店价
	var sum_price = foramtmoney(num*price);
	$(obj).parent().prev().find("input").val(sum_price);
    sum_money();
}
//改变商品数量，进价和小计
function change_price(obj){
    var price=parseFloat($(obj).val());
    $(obj).val(foramtmoney(price));
    var num=parseInt($(obj).parent().next().next().next().find('input').val());
    var money=price*num;
    $(obj).parent().next().next().find('input').val(foramtmoney(money));
    sum_money();
}
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 wei_count = 0;
        var sum_count = $("input[name='sum_countval']").val();
        yi_count = yi_count - 1;
        wei_count = parseInt(sum_count - yi_count);
        $("#yi_count").html(yi_count);
        $("#wei_count").html(wei_count);

        sum_money();
		return false;
	}
}
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 confirm_sub(){
    var goods_id = $("input[name = 'infos[goods_id][]']");
    if(goods_id.length == 0){
        $.showErr('请选择商品',0,'hc');
        return false;
    }else{
        $.openUrl(APP+"Shop/InvoicingOrder/littlestocktaking_goods", '是否保存', 'ID', '500','hc', function () {
            return false;
        }, function () {
            return false;
        });
    }        
}
function confirm_stock(){
    var supplier_ids=new Array;
    $("select[name='infos[supplier_id][]']").each(function(){
        var supplier_id=$(this).val();
        if(supplier_id==0){
            is_return=true;
            $.showErr('请选择供货商',1,'hc');
            $(".btn3").attr('disabled',false);
            return false;
        }else{
            supplier_ids.push(supplier_id);
            supplier_ids= $.unique(supplier_ids);
            var pre_money_html="";
            for(var i in supplier_ids) {
                var txt = $("select[name='infos[supplier_id][]']:first option[value='"+supplier_ids[i]+"']").text();
                pre_money_html += txt + "：<input name='pre_money[" + supplier_ids[i] + "]' type='text' class='form-control w120' placeholder='预付款' />";
            }
            //alert(pre_money_html);
            $('#pre_money').html(pre_money_html);
        }
    });$('.confirm_insert').show();
    $('.confirm_insert_maks').show();
}
//关闭预付款
function close_confirm(){
    $(".btn3").attr('disabled',false);
    $('.confirm_insert').hide();
    $('.confirm_insert_maks').hide();
}
//提交订货或是进货订单
function sub_order(t,is,is_stock){
    if(is == 1){var is_print = $('#is_print').val(1);}//是否打印订单
    var goods_id = $("input[name = 'infos[goods_id][]']");
    if(goods_id.length == 0){
        $.showErr('请选择商品',0,'hc');
        return false;
    }
    $(".btn3").attr('disabled',true);
    if(t==2){//生成配货单
        var r=confirm("是否确认生成盘点单？");
    }
    if(r=true){
        if(is_stock==1){
            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);
        }else{
            var send_time=$('#send_time').val();
            $('#best_time').val(send_time);
            var remark=$('#remark').val();
            $('#remarks').val(remark);
        }
        var form = $("form[name='myform']");
        var query=new Object();
        query= $(form).serialize();
        var url = APP+"Shop/InvoicingOrder/stocktaking_add";
        $.ajax({
            url:url,
            data:query,
            type:"post",
            success:function(data){
                // alert(JSON.stringify(data));
                if(data.status == 1){
                    if(is == 1){
                        var data_url=APP+"Shop/InvoicingOrder/stocktaking_order_print/id/"+data.id+".html";
                        window.open(data_url); //打印订单的跳转
                        $.showSuccess(data.msg,3,'hc');
                    }else{
                        $.showSuccess(data.msg,3,'hc');
                        window.location.reload();
                    }
                }else{
                    $.showErr(data.msg,3,'hc');
                }
                return false;
            }
        });
    }else{
        $(".btn3").attr('disabled',false);
        return false;
    }
}
//合计
function sum_money(){
    var yi_stock = all_stock = profit_sum = loss_sum = 0;
    $("input[name = 'infos[stock][]']").each(function(i){
        var num = $("input[name = 'infos[freight_num][]']");
        yi_stock = yi_stock + parseInt(num[i].value);

        var profit = $("input[name = 'infos[profit_sum][]']");
        profit_sum = profit_sum + parseInt(profit[i].value);

        var loss = $("input[name = 'infos[loss_num][]']");
        loss_sum = loss_sum + parseInt(loss[i].value);

        all_stock = all_stock + parseInt($(this).val());
    });
    $("#all_stock").html(all_stock);
    $("input[name='all_stock']").val(all_stock);
    $("#yi_stock").html(yi_stock);
    $("input[name='reality_sum']").val(yi_stock);
    $("#profit_sum").html(profit_sum);
    $("input[name='profit_sum']").val(profit_sum);
    $("#loss_sum").html(loss_sum);
    $("input[name='loss_sum']").val(loss_sum);
}
//格式化价格
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;
}