//改变选中的值
/**进货准备开始**/
var supplier_list=new Object();var prevTrIndex = 0,thisTrIndex=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=is_shop;
    $.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;
                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,is_shop);}
            }
            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;
    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='shop_price'><input type='hidden' name='infos[supply_price][]' value='"+product_list[index].supply_price+"' />"+product_list[index].supply_price+"</td>";
    tpl+="<td><input type='hidden' name='infos[shop_price][]' value='"+product_list[index].shop_price+"' />"+product_list[index].shop_price+"</td>";
    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+="<td><input type='hidden' name='infos[supplier_id][]' value='0' />无</td>";
    }else{
        tpl += "<td><select name='infos[supplier_id][]' class='w100'>";
        if(supplier_list) {
            for (var i in supplier_list) {
                tpl += "<option value='"+i+"'";//+product_list[index].supplier_id;
                if(product_list[index].supplier_id == i){tpl += " selected='selected'"}
                tpl += ">"+supplier_list[i]+"</option>";
            }
        }
        tpl += "</select></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>";
    //当当前已添加行数大于等于默认行数时，将添加行数据，否则覆盖空行
    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);
    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);
        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/littlebad_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/bad_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/bad_order_print/id/"+data.id+".html";
                        window.open(data_url); //打印订单的跳转
                    }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 sumprice = shop_money = sum_num = 0;
    $("input[name = 'infos[all_money][]']").each(function(){
        var one_sumprice=parseFloat($(this).val());
        sumprice= sumprice + one_sumprice;
    });
    $("#sum_money").html(foramtmoney(sumprice));
    $("input[name = 'infos[shop_price][]']").each(function(i){
        var num_dui = $("input[name = 'infos[freight_num][]']");
        var num = num_dui[i].value;
        var one_shop_price=parseFloat($(this).val()) * num;
        shop_money= shop_money + one_shop_price;
        sum_num = sum_num + parseInt(num);
    });
    $("#shop_money").html(foramtmoney(shop_money));
    $("#sum_num").html(parseInt(sum_num));
    $("input[name='bad_all_money']").val(foramtmoney(sumprice));
    $("input[name='bad_all_num']").val(parseInt(sum_num));
}
//格式化价格
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;
}