//改变选中的值
/**进货准备开始**/
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 search_goods(){
// 	var keyword=$('#keyword').val().trim();//输入的商品关键字
//     var chu_type = $("#chu_type").val();//出库单位类型 默认是2 供货商 3是仓库
//     //判断是否输入商品关键字
// 	if (keyword=='' || keyword==0 || keyword=='undefined'){
//       $.showErr('请填写商品编号或商品名称',0,'hc');return false;
//     }
// 	var query= new Object();
// 	query.keyword = keyword;  //商品关键词
//     query.chu_type = chu_type; //出库类型 默认是2 供货商
// 	$.ajax({
// 		type: "post",
// 		url: APP+"Shop/InvoicingOrder/search_goods",
// 		data: query,
// 		success: function(data){
// 			var html = "";
// 			if(data.status==1){
// 				$("#goods").html(data.info);
// 			}else{
// 				$.showErr(data.msg,3,'hc');
// 			}
//             return false;
// 		}
// 	});
// }
//直接搜索商品
function serchgoods(){
    var keyword=$('#keyword').val();
    if(keyword)$('#search_keywords').val(keyword);
    var query = new Object();
    query.sn=keyword;
    $.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,1);}//0：全部商品，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;
            //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+"' />"
        +"<input type='hidden' name='infos[storage_id][]' value='1' />"
        +"<input type='hidden' name='infos[index][]' value='"+index+"' />"
        +"<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>";
    if(product_list[index].attr_name){
        tpl += "<td>"+product_list[index].attr_name+"</td>";
    }else{
        tpl += "<td>无</td>";
    }    

    tpl+="<td class='shop_price'><input type='hidden' name='infos[shop_price][]' value='"+product_list[index].shop_price+"' />"+product_list[index].shop_price+"</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].shop_price+"'><span>"+product_list[index].shop_price+"</span></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;}
    //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 = 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 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/littleorder_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);
        }
    });
}
function confirm_order(){
    var goods_id = $("input[name = 'infos[goods_id][]']");
    if(goods_id.length == 0){
        $.showErr('请选择商品',0,'hc');
        return false;
    }
    var sumprice=parseFloat($("input[name='sum_money']").val());
    if(sumprice>200000){
        $.showErr('总额不能超过20万','0','hc');return false;
    }
    var uid=$("#user_id").val();
    if(uid)$(".user_moeny").show();
    $('.order_move').show();
    $('.order_move_maks').show();
        
}
//关闭预付款
function close_confirm(){
    $(".btn3").attr('disabled',false);
    $('.confirm_insert').hide();
    $('.confirm_insert_maks').hide();
}
function serchmermber(){
    $('.zhezhao').show();
    $('.zhezhao .user_card').show();
}
//提交订货或是进货订单
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){
        var form = $("form[name='myform']");
        var query=new Object();
        query= $(form).serialize();
        var url = APP+"Shop/InvoicingOrder/return_goods";
        $.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/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 = 0;
//     $("input[name = 'infos[all_money][]']").each(function(){
//         var one_sumprice=parseFloat($(this).val());
//         sumprice= sumprice + one_sumprice;
//     });
//     $("#sum_money").html(foramtmoney(sumprice));
// }
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));

    if(sumprice>200000){
        $.showErr('总额不能超过20万','0','hc');
    }
    $("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);
        
    });
    $("input[name='sum_money']").val(sumprice);
    $("input[name='cash_money']").val(foramtmoney(sumprice));
    $("#shop_money").html(foramtmoney(shop_money));
    $("#sum_num").html(parseInt(sum_num));
}
function change_user_money(obj){
    var price=parseFloat($(obj).val());    
    var sum_money=parseFloat($("input[name='sum_money']").val());
    var cash_money=sum_money;
    if(sum_money>=price){
        var cash_money=sum_money-price;
    }else{
        price=sum_money;
        cash_money=0;
    }
    $("input[name='money']").val(foramtmoney(price));
    $("input[name='cash_money']").val(foramtmoney(cash_money));
}
//格式化价格
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;
}
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 close_move(){
    $('.order_move').hide();
    $('.order_move_maks').hide();
}