{% load i18n %}

<style>   
    .ui-autocomplete {
        z-index: 10000;
    }

</style>


<script type="text/javascript">
    $(document).ready(function(){  
        $('.datepicker').datepicker({dateFormat: 'yy-mm-dd'});
        $('.datepicker').datepicker('setDate',new Date());
        setDatePickerZh();      

        var table=$('#tb').DataTable({
            dom: 'Bfrtip',
            autoWidth: true,
            pageLength: 10,
            buttons: [{extend:'excelHtml5',text: '导出到Excel'}],   
            language:lng,
            data:{{data|safe}},
            //2025-03-10
            {% if stk_confirm %}
                createdRow: function( nRow, aData, iDataIndex ) { 
                    var nColCnt=aData.length-1;                 
                    var s='',html='';                   
                    s=aData[nColCnt];                    
                    //if (s=='' && (aData[nColCnt-1]+aData[nColCnt-2]+aData[nColCnt-3])>0){
                    if (s==''){
                        html='<button class="btn btn-confirm btn-primary btn-xs">审核</button>';                        
                        $('td:eq('+nColCnt+')', nRow).html(html);
                    }  
                }                       
            {% endif %}
        });      
        table.columns().every( function () {                        
            var that = this;             
            $('input', this.footer() ).on( 'keyup change clear', function () {
                if ( that.search() !== this.value ) {
                    that.search( this.value ).draw();
                }
            });
        });   

        //2025-03-11        
        $('#tb').on("click","td .btn-confirm",function(event){
            
            event.preventDefault();

            var code=$(this).closest('tr').children().eq(1).text();   
            var h=$(this).closest('tr').find('td a').attr('href');
            
            let a=h.split('/');
            let id=a[a.length-1];
            let me=$(this);

            $.ajax({
                url:'/stkposting/batch/confirm/'+id+'/',
                type: 'POST',
                success:function (data){
                    if (data.e!=''){
                        toastr.error(
                            data['e'],
                            "数据错误：",
                            {timeOut: 800, positionClass: "toast-center-center"}
                        );                       
                    }else{
                        $(me).closest('td').text(data.tm);
                        toastr.success("单据 "+code+" 已审核!");
                    };
                }
            });             
        });         

        

         $('.btn-qry').click(function(){           
            var  date_fr=$('#dt_fr').val(),date_to=$('#dt_to').val();            
            var params=[];   
            if(date_fr!=''){params.push('date_fr='+date_fr)};
            if(date_to!=''){params.push('date_to='+date_to)};
            
          
            if(params.length==0){
                bootbox.alert("{% trans '请先输入查询条件！'%}");
            }else{
                $.RefreshContent('{{request.path}}?'+params.join('&'));
            }
        });

         $('.btn-add').click(function(){
            //数据清空
            $('#mat_tb tbody').html('');
            $('#code,#remark,#batch_no').val('');
            $('#dlg-inbound').modal('show');         
         });

         $('#mat-label').autocomplete({                
                source: function(request, response) {
                    $.ajax({
                        url: '/obj/ajax/autocomplete/inventory_material/',
                        dataType: "json",
                        data: {
                            term:   $("#mat-label").val() ,//搜索栏里的内容
                            company_id:  {{request.user.ancestor_id}} //额外参数
                        },
                        success: function(data) {
                            response(data);                          

                        }
                    });
                },   
                select: function (event, ui) {
                    var d=ui.item.value;  
                    $("#mat-id").val(d.id);
                    $("#mat-label").val(ui.item.label);
                    var html='';
                    for(var i = 0; i < d.unit_choices.length; i++) {
                        html=html+"<option value=''>"+d.unit_choices[i]+"</option>"                
                    };
                    $('#sel-unit').html(html);
                    $('#sel-unit option[text="'+d.unit_name+'"]').attr("selected",true);  
                    return false;   
                }
        });
        $('.mat-add').click(function(){
            var mid=$('#mat-id').val();    
            if($.isEmpty(mid) || $.isEmpty($('#mat-qty').val())){
                toastr.error("请先选择物料名称和数量", "操作错误：",
                    {timeOut: 800, positionClass: "toast-center-center"}
                );
                return;            
            }else{
                var html='<tr '+
                    'mat_id="'+$('#mat-id').val()+'" '+
                    'qty="'+$('#mat-qty').val()+'" '+
                    'unit_id="'+$('#sel-unit').val()+'" '+
                    'unit_name="'+$('#sel-unit').find("option:selected").text()+'" >'+
                        '<td>'+$('#mat-label').val()+'</td>'+                    
                        '<td>'+$('#mat-qty').val()+'</td>'+
                        '<td>'+$('#sel-unit').find("option:selected").text()+
                            '<button class="bnt btn-xs btn-danger btn-del pull-right">删除</button>'+
                        '</td>'+
                    '</tr>';
                $('#mat_tb tbody').append(html);            
            }        
        });

         $('#mat_tb').on('click','.btn-del',function(){            
            $(this).closest('tr').remove();    
        });
        
        
        $('#dlg-inbound .btn-save').click(function(){
            var code=$('#code').val();
            var a=[];
            $('#mat_tb tbody tr').each(function(){
                var me=$(this);
                a.push({
                    'id':$(me).attr('mat_id'),
                    'qty':$(me).attr('qty'),
                    'unit_id':$(me).attr('unit_id'),
                    'unit_name':$(me).attr('unit_name')
                })
            });

            
            if($.isEmpty(code)){
                toastr.error("单据编号不能为空", "操作错误：",
                    {timeOut: 800, positionClass: "toast-center-center"}
                );
                return;                
            }else{
                if (a.length==0){
                    toastr.error("物料明细不能为空！", "操作错误：",
                        {timeOut: 800, positionClass: "toast-center-center"}
                    );
                    return;               
                }else{     
                    var bid=$('#batch_id').val();
                    var url='/matposting/batch/editinbound/';
                    if (bid!=''){
                        url=url+bid+'/'
                    };
                    var d={
                        'code':code,
                        'batch_no':$('#batch_no').val(),
                        'remark':$('#remark').val(),
                        'details':a
                    };
                    $.ajax({
                        url: url,
                        dataType: "json",
                        type:"post",
                        data: JSON.stringify(d),
                        success: function(data) {
                            $('#dlg-inbound').modal('hide');     
                            $.RefreshContent('{{request.get_full_path}}');
                        }
                    });   
                }           
            } 
            
        });
        

    
    })
</script>



<ol class="breadcrumb">
        <li>促销物料</li>
        <li>物料入库</li>     
</ol>

<div class='col-md-12'>
    <div class="x_panel form-inline"> 
    
    <div class="col-sm-2 input-group">
        <span class="input-group-addon">{% trans "开始日期"%}</span>
        <input class="datepicker form-control" id="dt_fr" />
    </div>
    <div class="col-sm-2 input-group">
        <span class="input-group-addon">{% trans "结束日期"%}</span>
        <input class="datepicker form-control" id="dt_to" />
    </div>
    <div class="col-sm-2 input-group" >
        <span class='input-group-btn'>
            <a type="button" class='btn btn-primary btn-qry'>
                <span class='glyphicon glyphicon-search' style='padding-right:5px;'></span>{% trans '查找' %}
            </a>
        </span>        
    </div>
    <div class="col-sm-3 input-group" >        
        <button type="button" class='btn btn-primary btn-add pull-right'>
            新建物料入库
        </button>               
    </div>
    
        
    </div>
</div>


<div class="col-md-12 col-sm-12 col-xs-12">   
    <div class="x_panel">
        <div  class="table-responsive">
            <table id='tb'  class="table table-striped table-bordered dt-responsive nowrap" cellspacing="0" width="100%">
            <thead>
                {% for c in clmns %}
                    <th>{{c}}</th>
                {% endfor %}
            </thead>
            <tbody></tbody>
            <tfoot>
                {% for c in clmns %}
                    <th><input type="text" placeholder="{{c}}"></th>            
                {% endfor %}            
            </tfoot>
            </table>
        </div>
    </div>
</div>



<div class="modal fade" tabindex="-1" role="dialog" id="dlg-inbound">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span>
                </button>
                <h4 class="modal-title">新建物料入库:</h4>
            </div>
            <div class="modal-body">              
                <input type='hidden' id="batch_id" value="" />
                
                <div class="form-group ">                    
                    <label class="col-sm-2 control-label ">单据编号:</label>
                    <div class="col-sm-10">
                        <input id='code' class='form-control'>
                    </div>
                </div>
                <div class="clearfix" style="margin-bottom:5px;"></div>

                <div class="form-group ">                    
                    <label class="col-sm-2 control-label ">物料批次:</label>
                    <div class="col-sm-10">
                        <input id='batch_no' class='form-control'>
                    </div>
                </div>            
                <div class="clearfix" style="margin-bottom:10px;"></div>


                <div class="form-group ">                    
                    <label class="col-sm-2 control-label ">备注说明:</label>
                    <div class="col-sm-10">
                        <input id='remark' class='form-control'>
                    </div>
                </div>            
                <div class="clearfix" style="margin-bottom:10px;"></div>
                
                
                <div class="form-group" >   
                    <div class="col-sm-6">
                        <input id='mat-id' type='hidden' />
                        <input id='mat-label' class='form-control' placeholder='物料名称'>
                    </div>
                    <div class="col-sm-2">
                        <input id='mat-qty' class='form-control' placeholder='数量'>
                    </div>
                    <div class="col-sm-2">
                        <select id='sel-unit' class='form-control'>
                            <option value=''>单位</option>
                        </select>                        
                    </div>
                    <div class="col-sm-2">
                        <span>
                            <a type="button" class='btn btn-success mat-add'>
                                <span class='glyphicon glyphicon-arrow-down' style='padding-right:5px;'></span>添加
                        </a></span> 
                    </div>                    
                </div>  
                <div class="clearfix"></div>         

                <div style='min-height:100px;'>
                    <div id="div-list" class="table-responsive" width="100%" style='padding-left:10px;padding-right:10px'>  
                    <table id="mat_tb" class="table table-striped table-bordered dt-responsive" width="100%" >
                    <thead>
                        <tr>                           
							<th>物料名称</th>
                            <th>数量</th> 
							<th>单位</th>                                                      
                        </tr>
                    </thead>
                    <tbody></tbody>
                    </table>
                </div>
                </div>

            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-primary btn-save">保存</button>
            </div>
        </div><!-- /.modal-content -->
    </div><!-- /.modal-dialog -->
</div><!-- /.modal -->
