{% extends 'base.html.twig' %}

{% block title%}
    WONDER-Transporte Nacional
{% endblock %}
{% block titulo %}
    CUENTAS POR COBRAR TRANSPORTE NACIONAL
{% endblock %}
{% block bread %}
    X-Cobrar-T-Nal
{% endblock %}

{% block body %}
    <style>
        body {background-image: url({{ asset('recursos/imagenes/sistema/fondo_lateral.png')}});
            background-repeat: no-repeat;
            /*background-size: 200px;*/
            background-size: cover;
        }

        .table > tbody > tr > td, .table > tbody > tr > th, .table > tfoot > tr > td, .table > tfoot > tr > th, .table > thead > tr > td, .table > thead > tr > th {
            padding: 3px 12px;
        }
        body {
            font: 14px/1.5 sans-serif;
        }
        .btn {
            font-size: 10px;
            padding: .2rem 1.2rem;
        }




        .col-sm-2 {
            max-width: 100%;
        }



    </style>


{#    para el rango de fechas en datatable#}
{#    <script type="text/javascript" src="https://cdn.jsdelivr.net/momentjs/latest/moment.min.js"></script>#}
{#    <script type="text/javascript" src="https://cdn.jsdelivr.net/npm/daterangepicker/daterangepicker.min.js"></script>#}
{#    <link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/npm/daterangepicker/daterangepicker.css" />#}

    <div class="row">
        {#{% if is_granted('ROLE_SUPER')%}#}
        <div class="col-sm-12">
            {% include 'messages/success.html.twig' %}
            {% include 'messages/danger.html.twig' %}
            <div class="white-box">
                <h3 class="box-title m-b-0">LISTADO DE CUENTAS POR COBRAR A EMPRESAS - TRANSPORTE NACIONAL</h3>
                <div class="clearfix">
                    <div class=" tableTools-container col-md-3" style="text-align: right">RANGO DE FECHAS DE REPORTE: </div>
                    <div class=" tableTools-container col-md-3">
                        {#                        {% if is_granted('ROLE_ADMINISTRADOR') or is_granted('ROLE_TECNICO') or is_granted('ROLE_RECEPCION')%}#}
                        {#                            <a href="{{ path('tnacional_new') }}" class="btn btn-outline btn-rounded btn-success pull-right" title='Nuevo Registro' style="font-size: 18px; margin-left: 10px">Agregar Registro</a>#}
                        {#                        {% endif %}#}
                        {#                        <input class="form-control input-daterange-datepicker" type="text" name="daterange" value="01/01/2015 - 01/31/2015" /> </div>#}
                        {#                    <input class="form-control" type="text" data-toggle="daterangepicker" maxlength="23" name="timestamp" data-filter-type="date-range">#}

                        <input style="color: blue" type="text" name="reportrange" id="reportrange" class="form-control" data-filter-type="date-range">
                        {#                    <input type="text" name="global_filter" id="global_filter" class="form-control"  />#}

                    </div>
                </div>
                <hr>
                <div class="table-responsive">
                    <table id="myTable" class="table table-striped display">
{#                        <table id="myTable" class="display nowrap" width="100%">#}
                        <thead>
                        <tr>
                            <th>Nº</th>
                            <th>Tramo</th>
                            <th>Fecha</th>
                            <th>Empresa</th>
                            <th>No. Factura</th>
                            <th>Monto Bs.</th>
                            <th>Téc. Responsable</th>
                            <th>Observaciones</th>
{#                            <th class="text-right">Acciones</th>#}
                        </tr>
                        </thead>
                        <tbody>

                        {% set indice = 1 %}
                        {% for entity in tfactnals %}
                            <tr data-id="{{ entity.idnacional }}" >
                                <td>{{ indice }}</td>
                                <td>{{ entity.origen }} - {{ entity.destino}}</td>
                                <td>{{ entity.fcobrofact|date('d-m-Y') }}</td>
                                <td>{{ entity.nombre }}</td>
                                <td>{{ entity.factura}}</td>
                                <td style="text-align: right">{{ entity.suma|number_format(2, '.', ',') }}</td>
                                <td>{{ entity.nombres}}</td>
                                <td>{{ entity.observacion }}</td>

{#                                <td>hola</td>#}
                            </tr>


                            {% set indice = indice + 1 %}
                        {% endfor %}
                        </tbody>

                        <tfoot>
                            <tr>
                                <th></th>
                                <th></th>
                                <th></th>
                                <th></th>
                                <th style="text-align:right">Total:</th>
                                <th></th>
                            </tr>
                        </tfoot>
                    </table>
                </div>
            </div>
        </div>
        {#{% endif %}#}
    </div>
    <!-- /.row -->

{#    {{ include ('forms/delete.html.twig', { form: delete_form_ajax, message: 'Estás seguro de borrar el registro?', id:'form-delete', with_submit:false }) }}#}

{% endblock %}
{% block javascripts %}
    {#    <script src="{{ asset('admin/js/delete-user.js') }}"></script>#}
    <script>
        function controllet(e) {
            tecla = (document.all) ? e.keyCode : e.which;
            if (tecla==8) return true; // para la tecla de retroseso
            else if (tecla==0||tecla==9)  return true; //<-- PARA EL TABULADOR-> su keyCode es 9 pero en tecla se esta transformando a 0 asi que porsiacaso los dos
            patron =/[a-zA-Z\u00E0-\u00FC\s]/;// -> solo numeros
            te = String.fromCharCode(tecla);
            return patron.test(te);
        }
    </script>
    <script>
        function controlnum(e) {
            tecla = (document.all) ? e.keyCode : e.which;
            if (tecla==8) return true; // para la tecla de retroseso
            else if (tecla==0||tecla==9)  return true; //<-- PARA EL TABULADOR-> su keyCode es 9 pero en tecla se esta transformando a 0 asi que porsiacaso los dos
            //patron =/^\d{0,8}(\.\d{0,3})?$/;// -> solo letras
            patron =/[0-9\.\-\s]/;// -> solo numeros
            te = String.fromCharCode(tecla);
            return patron.test(te);
        }
    </script>




    <script>
        function formatNumber(num) {
            if (!num || num == 'NaN') return '-';
            if (num == 'Infinity') return '&#x221e;';
            num = num.toString().replace(/\$|\,/g, '');
            if (isNaN(num))
                num = "0";
            sign = (num == (num = Math.abs(num)));
            num = Math.floor(num * 100 + 0.50000000001);
            cents = num % 100;
            num = Math.floor(num / 100).toString();
            if (cents < 10)
                cents = "0" + cents;
            for (var i = 0; i < Math.floor((num.length - (1 + i)) / 3) ; i++)
                num = num.substring(0, num.length - (4 * i + 3)) + '.' + num.substring(num.length - (4 * i + 3));
            return (((sign) ? '' : '-') + num + ',' + cents);
        }












        var startdate;
        var enddate;

        $.fn.dataTableExt.afnFiltering.push(
            function (oSettings, aData, iDataIndex) {
                if (typeof startdate === 'undefined' || typeof enddate === 'undefined') {
                    return true;
                }
                var coldate = moment(aData[2], 'DD-MM-YYYY');
                console.log('coldate', coldate)

                var valid = true;

                if (coldate.isValid()) {
                    if (enddate.isBefore(coldate)) {
                        console.log('enddate before coldate', enddate)
                        valid = false;
                    }

                    if (coldate.isBefore(startdate)) {
                        console.log('coldate before startdate', startdate)
                        valid = false;
                    }
                } else {
                    valid = false;
                }

                return valid;

            });

        // function filterGlobal() {
        //     $('#myTable').DataTable().search(
        //         $('#global_filter').val()
        //     ).draw();
        // }

        function filterColumn(i) {
            $('#myTable').DataTable().column(i).search(
                $('#col' + i + '_filter').val()
            ).draw();
        }




        jQuery(document).ready(function ($) {
            var table;

            table = $('#myTable').DataTable({
                // initComplete: function () {
                // this.api().columns([1]).every( function () {
                //     var column = this;
                // var select = $('<select class="custom-select custom-select-sm rowSort"><option value="">Trans Type</option></select>')
                //     .appendTo( $('#rowSort' ))
                //     .on( 'change', function () {
                //         var val = $.fn.dataTable.util.escapeRegex(
                //             $(this).val()
                //         );
                //
                //         column
                //             .search( val ? '^'+val+'$' : '', true, false )
                //             .draw();
                //
                //     } );

                // column.data().unique().sort().each( function ( d, j ) {
                //     select.append( '<option value="'+d+'">'+d+'</option>' );
                // } );
                // });
                //
                // $('#poview_info').appendTo($('#sumInfo'));
                // $('#poview_paginate').appendTo($('#pageInfo'));

                // },

                "language": {
                    "url": "//cdn.datatables.net/plug-ins/1.10.16/i18n/Spanish.json"
                },
                dom: 'Bfrtip',
                buttons: [
                    {   extend: 'copy',
                        footer: true,
                        text: 'Copiar',
                        messageTop: 'CUENTAS POR COBRAR A EMPRESAS - TRANSPORTE NACIONAL'
                    },
                    {   name: 'excel',
                        extend: 'excel',
                        exportOptions: {columns: ':gt(0)', orthogonal: 'export'},
                        filename: 'Por_Cobrar_Empresas_Nal',
                        filename: function() {
                            var date_edition = moment().format("DD-MM-YYYY")
                            return date_edition + ' - ' + ' Por_Cobrar_Nal'
                        },
                        sheetName: 'Resultados',
                        footer: true,
                        tittle: 'Cuentas por Cobrar a Empresas - Transporte Nacional',
                        messageTop: 'CUENTAS POR COBRAR A EMPRESAS - TRANSPORTE NACIONAL'
                    },
                    {   extend: 'print',
                        orientation: 'landscape',
                        footer: true,
                        messageTop: 'CUENTAS POR COBRAR A EMPRESAS - TRANSPORTE NACIONAL',
                        customize: function ( win ) {
                            $(win.document.body)
                                .css( 'font-size', '10pt' )
                                .prepend(
                                    '<img src="https://wonder.sizcorp.com/public/recursos/imagenes/sistema/banner_superior.png" align="right"; height="50px"  />'
                                    // '<img src="http://datatables.net/media/images/logo-fade.png" style="position:absolute; top:0; left:0;" />'
                                );
                            $(win.document.body).find( 'table' )
                                .addClass( 'compact' )
                                .css( 'font-size', 'inherit' );
                        }
                    }

                ],
                "pagingType": "first_last_numbers",
                // "scrollX": true,

                fixedHeader: {
                    header: true,
                    footer: true
                },
                fixedColumns: {
                    leftColumns: 2
                },
                "bAutoWidth": true,
                // sDom: 't<i><""p>',
                // data: result,
                // columns: [
                //     { data: 'policy number' },
                //     { data: 'transaction type' },
                //     { data: 'transaction date' },
                //     { data: 'transaction effective date' },
                //     { data: 'minimum premium amount' },
                //     { data: 'deferred premium amount' },
                //     { data: 'total written premium' },
                //     { data: null,
                //         className: "center actionItem",
                //         defaultContent: '<button class="btn actionIcon" data-toggle="modal" data-target="#modal-1"><i class="fas fa-calculator"></i></button>'}
                // ],
                columnDefs: [{
                    targets: -1,

                    className: 'dt-nowrap',
                    className: 'dt-left'

                }],
                "pageLength": 25,

                "footerCallback": function ( row, data, start, end, display ) {
                    var api = this.api(), data;
                    debugger;
                    // Remove the formatting to get integer data for summation
                    var intVal = function ( i ) {
                        return typeof i === 'string' ?
                            i.replace(/[\$,]/g, '')*1 :
                            typeof i === 'number' ?
                                i : 0;
                    };

                    // Total over all pages
                    total = api
                        .column( 5 )
                        .data()
                        .reduce( function (a, b) {
                            return intVal(a) + intVal(b);
                        }, 0 );

                    // Total over this page
                    pageTotal = api
                        .column( 5, { page: 'current'} )
                        .data()
                        .reduce( function (a, b) {
                            return intVal(a) + intVal(b);
                        }, 0 );



                    // Update footer
                    $( api.column( 5 ).footer() ).html(
                        ' <a style="color: red;">Bs. '+ formatNumber(pageTotal) + '  <br/>(Total Bs. '+ formatNumber(total) +' ) </a>'
                    );

                }

            });








            $('[data-filter-type="date-range"]').daterangepicker({
                    // $('#reportrange').daterangepicker({
                    showDropdowns: true,
                    ranges: {
                        'Hoy': [moment(), moment()],
                        'Ayer': [moment().subtract(1, 'days'), moment().subtract(1, 'days')],
                        'Esta semana': [moment().startOf('week'), moment().endOf('week')],
                        'Última semana': [moment().subtract(6, 'days'), moment()],
                        'Últimas 2 semanas': [moment().subtract(13, 'days'), moment()],
                        'Este mes': [moment().startOf('month'), moment().endOf('month')],
                        'Mes anterior': [moment().subtract(1, 'month').startOf('month'),
                            moment().subtract(1, 'month').endOf('month')]
                    },
                    autoUpdateInput: true,
                    applyClass: 'btn-sm btn-danger',
                    cancelClass: 'btn-sm btn-default',
                    locale: {
                        format: 'DD/MM/YYYY',
                        applyLabel: 'Aplicar',
                        cancelLabel: 'Limpiar',
                        fromLabel: 'Desde',
                        toLabel: 'Hasta',
                        customRangeLabel: 'Seleccionar rango',
                        daysOfWeek: ['Do', 'Lu', 'Ma', 'Mi', 'Ju', 'Vi', 'Sa'],
                        monthNames: ['Enero', 'Febrero', 'Marzo', 'Abril', 'Mayo', 'Junio',
                            'Julio', 'Agosto', 'Septiembre', 'Octubre', 'Noviembre',
                            'Diciembre'],
                        firstDay: 1
                    },
                    "opens": "right",
                    "startDate":startdate,
                },
                function (start, end, label) {
                    /* var s = moment(start.toISOString());
                     var e = moment(end.toISOString());
                     startdate = s.format("DD-MM-YYYY");
                     enddate = e.format("DD-MM-YYYY");*/
                    console.log('New date range selected: ' + start.format('YYYY-MM-DD') + ' to ' + end.format('YYYY-MM-DD') + ' (predefined range: ' + label + ')');
                });



            // $('input.global_filter').on('keyup click', function () {
            //     filterGlobal();
            // });


            $('input.column_filter').on('keyup click', function () {
                filterColumn($(this).parents('tr').attr('data-column'));
            });

            $('#reportrange').on('apply.daterangepicker', function (ev, picker) {
                startdate = moment(picker.startDate.format('DD-MM-YYYY'), 'DD-MM-YYYY');
                enddate = moment(picker.endDate.format('DD-MM-YYYY'), 'DD-MM-YYYY');

                table.draw();
            });

        });

    </script>


{% endblock %}




