{% extends 'VGMWOBundle::layout.html.twig' %}
{% block stylesheets %}
    {{ parent() }}
    <link href="{{ asset('bundles/vgmwo/css/bootstrap-datetimepicker.css') }}" rel="stylesheet" media="screen">
    <link href="{{ asset('bundles/vgmwo/css/waitMe.css') }}" rel="stylesheet" media="screen">
    <link href="https://cdn.datatables.net/1.10.9/css/jquery.dataTables.min.css" rel="stylesheet" media="screen">
    <link href="https://cdn.datatables.net/buttons/1.0.3/css/buttons.dataTables.min.css" rel="stylesheet" media="screen">
    <style>.dataTables_wrapper .ui-toolbar {padding: 0px !important;}.dataTables_filter {display: none;}div.DTTT_container {margin-left: 1em;}#workorders-list>tbody>tr{cursor: pointer;}
        table.dataTable thead th, table.dataTable thead td {padding: 5px;}table.dataTable tbody th, table.dataTable tbody td {padding: 5px;}
        table.dataTable thead .sorting {
            background-image: none;
        }
        table.dataTable thead .sorting_desc, table.dataTable thead .sorting_desc_disabled {
            background-image: url("{{ asset('bundles/vgmwo/images/sort_desc.png') }}");
            background-position: center bottom;
        }
        table.dataTable thead .sorting_asc, table.dataTable thead .sorting_asc_disabled {
            background-image: url("{{ asset('bundles/vgmwo/images/sort_asc.png') }}");
            background-position: center bottom;
        }
    </style>
{% endblock %}
{% block content%}
    <div id="invoices_list" class="container">
        <div id="header-area">
            <strong style="font-size: 3vmin;">Invoices</strong>{#
            <a style="display: inline-block; margin-left: 2vmin; color: #428bca; cursor: pointer;"
               href="{{ path('invoices_new') }}"><span class="glyphicon glyphicon-plus"></span></a>#}
            <div class="form-inline pull-right">
                <div class="form-group" id="table-buttons-div" style="padding: 0vw 0.5vw;"></div>
                <div class="form-group">
                    <label class="sr-only" for="datatable-searchbox">Search</label>
                    <input id="datatable-searchbox" class="form-control" placeholder="Search"/>
                </div>
                <div class="vertical-divider"></div>
                <div class="form-group">
                    <a href="#" data-toggle="modal" data-target="#advanced-serach-panel" style="display: inline-block">Advanced Search</a>
                </div>
            </div>
        </div>
        <div id="advanced-search-area" class="text-right">
            <div class="form-inline" style="display: inline-block;">
                <div class="form-group">
                    <label for="invoice-purpose-selection" style="height: 100%; vertical-align: bottom; margin-bottom: 0px;">Invoice purpose:</label>
                    <select id="invoice-purpose-selection" class="form-control"
                            data-bind="options: invoice_destinations,optionsText: 'name',value: chosen_dest"></select>
                </div>
                <div class="vertical-divider"></div>
                <div class="form-group">
                    <label for="invoice-status-selection"  style="height: 100%; vertical-align: bottom; margin-bottom: 0px;">Invoice status:</label>
                    <select id="invoice-status-selection" class="form-control">
                        <option value="0" selected>All</option>
                        <option value="1">F</option>
                        <option value="2">PF</option>
                        <option value="3">S</option>
                    </select>
                </div>
            </div>
        </div>
        <secction id="list-area" class="table-responsive row" style="padding-left: 0px; padding-right: 0px;">
            <table class="table table-hover fixed-header display table-int-grid" cellspacing="0" id="invoices-list">
                <thead>
                <tr style="background-color: #fff;">
                    <th class="col-xs-05">Created</th>
                    <th class="col-xs-05">Purpose</th>
                    <th>Status</th>
                    <th class="col-xs-2 col-sm-">Client</th>
                    <th class="col-xs-3 col-sm-3">Equipment</th>
                    <th class="col-xs-2 col-sm-1">WO-Stock</th>
                    <th class="col-xs-1 col-sm-1" style="white-space: nowrap;">Stock</th>
                    <th class="col-xs-1 col-sm-1" style="white-space: nowrap;">To invoice</th>
                    <th class="col-xs-1  col-sm-1">Invoiced</th>
                    <th class="col-xs-1 col-sm-1" style="white-space: nowrap;">Inv. date</th>
                    <th class="col-xs-1 col-sm-1">Invoice</th>
                </tr>
                </thead></table>
            <div id="total-area" class="pull-right col-xs-3 col-sm-3">
                <table class="table table-responsive totals">
                    <tbody>
                        <tr>
                            <td style="border-top: none; border-bottom: 1px solid #ddd; font-size: 17px;"><strong>Stock:</strong></td>
                            <td class="text-right" style="border-top: none; border-bottom: 1px solid #ddd; font-size: 17px;">
                                {#<span class="glyphicon glyphicon-usd" style="font-size: 12px;"></span>#}
                                <strong id="total-to-stock-value"></strong>
                                <strong>x K</strong>
                            </td>
                        </tr>
                        <tr>
                            <td style="border-top: none; border-bottom: 1px solid #ddd; font-size: 17px;"><strong>To invoice:</strong></td>
                            <td class="text-right" style="border-top: none; border-bottom: 1px solid #ddd; font-size: 17px;">
                                {#<span class="glyphicon glyphicon-usd" style="font-size: 12px;"></span>#}
                                <strong id="total-to-invoice-value"></strong>
                                <strong>x K</strong>
                            </td>
                        </tr>
                        <tr>
                            <td style="border-top: none; border-bottom: 1px solid #ddd; font-size: 17px;"><strong>Invoiced:</strong></td>
                            <td class="text-right" style="border-top: none; border-bottom: 1px solid #ddd; font-size: 17px;">
                                {#<span class="glyphicon glyphicon-usd" style="font-size: 12px;"></span>#}
                                <strong id="total-invoiced-value"></strong>
                                <strong>x K</strong>
                            </td>
                        </tr>
                    </tbody>
                </table>
            </div>
        </secction>
    </div>
    {% block advanced_search_panel %}{% include "VGMWOBundle:Invoicing/Modal_panels:advance_search.html.twig" %}{% endblock advanced_search_panel %}
{% endblock %}
{% block javascripts %}
    {{ parent() }}
    <script type="text/javascript" src="{{ asset('bundles/vgmwo/js/bootstrap-datetimepicker.js') }}"></script>
    <script type="text/javascript" src="{{ asset('bundles/vgmwo/js/jquery/jquery.inputmask.js') }}"></script>
    <script type="text/javascript" src="{{ asset('bundles/vgmwo/js/jquery/jquery.dataTables.min.js') }}"></script>
    <script type="text/javascript" src="{{ asset('bundles/vgmwo/js/customized/Invoices/invoices.lists.js') }}"></script>
    <script type="text/javascript" src="https://cdn.datatables.net/buttons/1.0.3/js/dataTables.buttons.min.js"></script>
    <script type="text/javascript" src="https://cdn.datatables.net/buttons/1.0.3/js/buttons.print.min.js"></script>
    <script type="text/javascript">
        function get_invoices_list_url(){return '{{ path("get_invoices_list") }}';};
        function convertImgToBase64(url, callback, outputFormat){
            var img = new Image();
            img.crossOrigin = 'Anonymous';
            img.onload = function(){
                var canvas = document.createElement('CANVAS');
                var ctx = canvas.getContext('2d');
                canvas.height = this.height;
                canvas.width = this.width;
                ctx.drawImage(this,0,0);
                var dataURL = canvas.toDataURL(outputFormat || 'image/png');
                callback(dataURL);
                canvas = null;
            };
            img.src = url;
        };
        var calcDataTableHeight = 0;
        var total_to_stock = 0;
        var total_to_invoice = 0;
        var total_invoiced = 0;
        var dt_config = {"processing": true,"loading": false,"scrollCollapse": true,
            "paging": false,
            "scrollY": function(){return ($(window).height() - $("nav.navbar-inverse.menu-bar").height()) -  120;},
            "responsive": true,"dom": 'Bfrtip',
            "buttons": [{extend:'print',text:"Print PreView",autoPrint:false,exportOptions:{columns:':visible'},
                customize:function(win){
                    $(win.document.body).css('font-size','10pt').css('height','95vh').css('margin','0px 10px');
                    $(win.document.body).find('h1').text("Aeroservicios - Invoicing");
                    $(win.document.body).find('table').addClass('compact').css('font-size','inherit');
                    var to_add = $('#total-area').wrap('<p/>').parent().html();
                    $('#total-area').unwrap();
                    $(win.document.body).append(to_add);
                }},
                {extend:'print',text:"Print",exportOptions:{columns:':visible'},key:{key:80,ctrlKey: true},
                    customize:function(win){
                        $(win.document.body).css('font-size','10pt').css('height','95vh').css('margin','0px 10px');
                        $(win.document.body).find('h1').text("Aeroservicios - Invoicing");
                        $(win.document.body).find( 'table' ).addClass( 'compact' ).css( 'font-size', 'inherit' );
                        var to_add = $('#total-area').wrap('<p/>').parent().html();
                        $('#total-area').unwrap();
                        $(win.document.body).append(to_add);
                    }},
                {text: "Excel",key:{key:'e',ctrlKey: true},action: function(){
                    $.ajax({type:'post',async:true,dataType:'json',url: '{{ path("export_invl2excel") }}',
                        data:ajax_parameters(),
                        success: function(response){window.location.assign(response.url);},
                        error:function() {alert("Error");}});}}],
            "aaSorting": [[8,'desc']],
            "info": true,
            "ajax":{
                url: get_invoices_list_url(),
                type: "POST",
                data: ajax_parameters()},
            "aoColumns": [{"sType" : "usdate", "bSortable": true, "visible": true},
                {"sType" : "text", "bSortable": true, "visible": true},
                {"sType" : "text", "bSortable": true, "visible": true},
                {"sType" : "text", "bSortable": true, "visible": true},
                {"type" : "text", "bSortable": true, "visible": true},
                {"type" : "ot-number", "bSortable": true, "visible": true, "searchable": false},
                {"type" : "us-money", "bSortable": true, "visible": true},
                {"type" : "us-money", "bSortable": true, "visible": true},
                {"type" : "us-money", "bSortable": true, "visible": true, "searchable": false},
                {"sType" : "usdate", "bSortable": true, "visible": true},
                {"sType" : "text", "bSortable": true, "visible": true}],
             "rowCallback": function(nRow,aData,iDisplayIndex,iDisplayIndexFull){
                 if(iDisplayIndex == 0){total_to_stock = 0;total_to_invoice = 0;total_invoiced = 0;}
                 total_to_stock += aData[6] != null && aData[6] != "" ? (parseFloat(aData[6].replace(',',''))) : 0;
                 total_to_invoice += aData[6] != null && aData[7] != "" ? (parseFloat(aData[7].replace(',',''))) : 0;
                 total_invoiced += aData[7] != null && aData[8] != "" ? (parseFloat(aData[8].replace(',',''))) : 0;
             },
            "drawCallback": function(){
                $('#total-to-stock-value').text(parseFloat(total_to_stock).format(3,3,',','.'));
                $('#total-to-invoice-value').text(parseFloat(total_to_invoice).format(3,3,',','.'));
                $('#total-invoiced-value').text(parseFloat(total_invoiced).format(3,3,',','.'));}
        };
        $(document).ready(function(){
            loadPageFeatures();
            clear_ajax_parameters();
            jQuery.extend(jQuery.fn.dataTableExt.oSort,{"usdate-pre":function(a){if(a==null||a==""){return 0;}
                var usDatea=a.replace(' ','').split('/');return (usDatea[2]+usDatea[0]+usDatea[1]) * 1;},
                "usdate-asc":function(a,b){return ((a<b)?-1:((a>b)?1:0));},
                "usdate-desc":function(a,b){return ((a<b)?1:((a>b)?-1:0));},
                "ot-number-asc":function(a,b){
                    a = a.replace(' ','').split('-');
                    a = (a.length > 1 ? (a[1].length == 1? parseFloat(a[0] + ".0" + a[1]) : parseFloat(a[0] + "." + a[1])) : parseFloat(a[0]));
                    b = b.replace(' ','').split('-');
                    b = (b.length > 1 ? (b[1].length == 1? parseFloat(b[0] + ".0" + b[1]) : parseFloat(b[0] + "." + b[1])) : parseFloat(b[0]));
                    return ((a<b)?-1:((a>b)?1:0));
                },
                "ot-number-desc":function(a,b){
                    a = a.replace(' ','').split('-');
                    a = (a.length > 1 ? (a[1].length == 1? parseFloat(a[0] + ".0" + a[1]) : parseFloat(a[0] + "." + a[1])) : parseFloat(a[0]));
                    b = b.replace(' ','').split('-');
                    b = (b.length > 1 ? (b[1].length == 1? parseFloat(b[0] + ".0" + b[1]) : parseFloat(b[0] + "." + b[1])) : parseFloat(b[0]));
                    return (parseInt(a) == parseInt(b) ? ((a<b)?-1:((a>b)?1:0)) : ((a<b)?1:((a>b)?-1:0)));
                },
                "us-money-asc":function(a,b){
                    a = parseFloat(a);
                    b = parseFloat(b);
                    return ((a<b)?-1:((a>b)?1:0));
                },
                "us-money-desc":function(a,b){
                    a = parseFloat(a);
                    b = parseFloat(b);
                    return ((a<b)?1:((a>b)?-1:0));
                },
                "text-asc":function(a,b){return ((a<b)?-1:((a>b)?1:0));},
                "text-desc":function(a,b){return ((a<b)?1:((a>b)?-1:0));}});

            var oTable = $('#invoices-list').DataTable(dt_config);
            oTable.buttons( 0, null ).container().appendTo($("#table-buttons-div"));

            $("#datatable-searchbox").on("keyup",function(event){if(event.keyCode == 13 || this.value == "")oTable.search(this.value).draw();});
            $("#invoice-status-selection, #invoice-purpose-selection").on("change",function(){oTable.ajax.reload();this.blur();});
            $('#execute-search-link').on( 'click', function(){oTable.ajax.reload();this.blur();});
            $(document).bind("keyup keydown", function(e){if(e.ctrlKey&&(e.keyCode==80||e.keyCode==69)){return false;}});
            $(window).bind('resize',function(){$(".dataTables_scrollBody").css('max-height',dt_config.scrollY()+'px');});
            $('#total-area').appendTo($('#invoices-list_wrapper'));
        });
        viewModel.LoadData = ko.dependentObservable(function() {
            {% if salest %}
                var ttsales=[];
                ttsales.push({id:'',name:"All"});
                {% for tsale in salest %}
                    ttsales.push({id:"{{ tsale.id }}",name:"{{ tsale.saletype }}"});
                {% endfor %}
                viewModel.invoice_destinations(ttsales);
            {% endif %}
            viewModel.chosen_dest(viewModel.invoice_destinations()[0]);
            }, viewModel);ko.applyBindings(viewModel, document.getElementById("content-body"));
    </script>
{% endblock %}