/**采购准备开始**/
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 change_supplier(){
    if(!product_list) return false;
    var options = $("#supplier_id option:selected");
    $(".suppliers span").html(options.text());
    $(".suppliers input").val(options.val());
    $("#supplier_ids").val(options.val());
}
//直接搜索商品
function searchgoods(){
    var keyword=$('#goods_sn').val();
    var supp_id=$('#supplier_id').val();
    var shop_id=$("select[id='shop_id']").val();
    var query = new Object();
    query.sn=keyword;
    //query.suppliers_id=supp_id;
    $.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;
                // console.log(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;
                product.suppliers_name = list.suppliers_name; //jxr 2019.02.13
                if(list.goods_attr_sn) {
                    product.goods_attr_sn = list.goods_attr_sn;
                }
                product_list[goods_index] = product;//返回商品显示信息
                sgoods(goods_index);
            }else{
                if(data.msg){$.showErr(data.msg,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;
    var options = $("#supplier_id option:selected");
    product_list[index].supplier_id = options.val();
    product_list[index].supplier_name = options.text();
    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[request_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>"+product_list[index].suppliers_name+"<input name='infos[supplier_id][]' type='hidden' style='width:50px;' value='"+product_list[index].supplier_id+"'></td>"
        +"<td class='shop_price'><input name='infos[supply_price][]' readonly='readonly' style='width:50px;' value='"+product_list[index].supply_price+"'></td>"
        +"<td class='money'><input name='infos[all_money][]' readonly='readonly' 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_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(){
    var res=check_info();
    if(res==false){return false;}
    order_cai_insert()
}
//检查必填项
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);
    //jxr start 2019.02.13
    var supplier_id=$('#supplier_id').val();
    if(!supplier_id){$.showErr('请选择供货商',1,'hc');$(".btn3").attr('disabled',false);$(".confirm").attr('disabled',false);return false;}
    $("input[name='supplier_id']").val(supplier_id);
    var best_time=$('#best_time').val();
    $("input[name='best_time']").val(best_time);
    //jxr start 2019.02.13
    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;}
}
/*采购操作数据库*/
function order_cai_insert(print){
    $(".confirm").attr('disabled',true);
    var res=check_info(1);
    if(res==false){return false;}
    $("input[name='goods_status']").val(0);//进货的商品状态
    $("input[name='type']").val(0);//货单类型 0采购单
    $("input[name='status']").val(0);//货单状态 0待审核.
    var query = $("form[name='order_in_form']").serialize();
    $.ajax({
        type: "post",
        url: APP+"InvoicingOrder/order_cai_insert.html",
        data: query,
        success: function(data){
            if(data.status==1){
                $.showSuccess(data.msg,1,'hc',function(){
                    if(print==1){window.open(data.url);}
                    window.location.href=APP+'Invoicing_order/purchase_index';
                },function(){
                    if(print==1){window.open(data.url);}
                    window.location.href=APP+'Invoicing_order/purchase_index';
                });
            }else{
                $.showErr(data.msg,1,'hc');
            }
            $(".confirm").attr('disabled',false);
            return false;
        }
    });
}
/**进货操作结束**/