/**进货准备开始**/
var supplier_list=new Object();//供货商列表
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;
    $.ajax({
        type: "post",
        url: APP+"Ajax/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;//每个商品的key值
                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;
                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);}
            }
            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().children("input");
            var old_num=parseFloat(currentobj.val());
            var new_num=old_num + 1;
            currentobj.val(parseFloat(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>"+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>"
        +"<td class='num'><input name='infos[freight_num][]' style='width:50px;' type='number' min='1' onchange='change_num(this)' value='1'></td>";
    //单位
    if(product_list[index].unit_name){
        tpl += "<td>"+product_list[index].unit_name+"</td>";
    }else{
        tpl += "<td>无</td>";
    }
    tpl += "<td><select name='infos[supplier_id][]' class='w100'>";
    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 += "<option value='0'>空</option>";
    }
    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>"
        +"<td class='shop_price'><input name='infos[supply_price][]' style='width:50px;' onchange='change_price(this)' value='"+product_list[index].supply_price+"'></td>"
        +"<td class='money'><input name='infos[all_money][]' style='width:50px;' onchange='change_all_money(this)' value='"+product_list[index].supply_price+"'></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 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></tr>';
        $('#tab_d').append(tpl);
    }
    thisTrIndex=thisTrIndex-1;
    resettr();
    sum_money();//计算合计
}
//改变商品进货数量
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');}
    }
    $(obj).val(parseFloat(num.toFixed(3)));
    var price = parseFloat($(obj).parent().parent().find("td.shop_price input").val());//获取进货价
    var sum_price = parseFloat(num * price).toFixed(2);//计算小计
    $(obj).parent().parent().find('.money input').val(sum_price);
    sum_money();//计算合计
}
//改变商品进货价
function change_price(obj){
    var price=parseFloat($(obj).val());//获取当前的进货价
    $(obj).val(parseFloat(price).toFixed(2));
    var num=parseFloat($(obj).parent().parent().find('td.num input').val());//获取当前数量
    var money=parseFloat(price*num).toFixed(2);//计算总价
    $(obj).parent().parent().find('td.money input').val(money);//给小计赋值
    sum_money();
}
//改变小计
function change_all_money(obj){
    var all_money=parseFloat($(obj).val());//获取当前小计
    $(obj).val(parseFloat(all_money).toFixed(2));
    var num=parseFloat($(obj).parent().parent().find('td.num input').val());//获取当前数量
    var single_money=parseFloat(all_money/num).toFixed(2);//计算进货价
    $(obj).parent().parent().find('td.shop_price input').val(single_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= parseFloat(sumprice) + one_sumprice;
        var one_sumcount=parseFloat($(this).parent().parent().find('td.num input').val());
        sumcount= parseFloat(sumcount) + one_sumcount;
    });
    $("#sum_money").html(foramtmoney(sumprice));
    $("#sum_count").html(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 check_info(is_re){
    if($("input[name='infos[goods_name][]']").length<=0){$.showErr('请选择商品进货',1,'hc');$(".btn3").attr('disabled',false);$(".confirm").attr('disabled',false);return false;}
    var shop_id=$("select[id='shop_id']").val();
    if(!shop_id){$.showErr('请选择进货仓库',1,'hc');$(".btn3").attr('disabled',false);$(".confirm").attr('disabled',false);return false;}
    $("input[name='shop_id_in']").val(shop_id);
    var is_return=false;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 if(is_re!=1){
            supplier_ids.push(supplier_id);
        }
    });
    //给每个供货商赋值预付款的值
    if(is_return){$.showErr('请选择供货商',1,'hc');$(".btn3").attr('disabled',false);return false;}
    else if(is_re!=1){
        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 += "<div class='mt5'>" + txt + "：<input name='pre_money[" + supplier_ids[i] + "]' type='text' class='form-control w120' placeholder='预付款' /></div>";
        }
        $('#pre_money').html(pre_money_html);
    }
}
/*进货操作数据库*/
function order_in_insert(print){
    $(".confirm").attr('disabled',true);
    var res=check_info(1);
    if(res==false){return false;}
    $("input[name='goods_status']").val(2);//进货的商品状态
    $("input[name='type']").val(1);//货单类型 0订货 1进货 2普通出库 3仓库退货 4仓库调货（出库）
    $("input[name='status']").val(2);//货单状态 0待审核.1配货中.2待入库.3已完成4.已拒绝5已作废
    var all_pre_money=0;
    $("#pre_money input").each(function(){
        if($(this).val()) {
            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();
    $.ajax({
        type: "post",
        url: APP+"InvoicingOrder/order_in_insert.html",
        data: query,
        success: function(data){//console.log(data);
            if(data.status==1){
                $.showSuccess(data.msg,1,'hc',function(){
                    if(print==1){window.open(data.url);}
                    window.location.href=APP+'Invoicing_order/order_ru';
                },function(){
                    if(print==1){window.open(data.url);}
                    window.location.href=APP+'Invoicing_order/order_ru';
                });
            }else{
                $.showErr(data.msg,1,'hc');
            }
            $(".confirm").attr('disabled',false);
            close_confirm();
            return false;
        }
    });
}
/**进货操作结束**/