<style>
    .fancy.fancy-grid{
        overflow-x:auto;
        }
</style>
@if (!empty($veh))

<form id="frmPeriodosVehiculo" name="frmPeriodosVehiculo" class="form form-inline">
<div class="row">
    <div class="col-md-12 text-right">
        <label for="periodo_vehiculo">@traducir('Período','Período')</label>
        <select name="periodo_vehiculo" id="periodo_vehiculo" class="form-control">
            @foreach($periodos as $per)
            <option value="{{$per->periodo}}" @if($per->periodo == $periodo) selected @endif>{{$per->periodo_my}}</option>
            @endforeach
        </select>
    </div>
</div>
</form>

<div class="row" style="display:none;" id="loading-vehiculos">
    <div class="col-md-2 col-md-offset-5">
        <br />
        <br />
        <img src="/images/loading.gif" class="img img-responsive" alt="" border="0" />
    </div>
</div>

<div class="row">
    <div class="col-md-12" id="recursosVehiculos"></div>
</div>

<form action="/imperium/recursos-data-vehiculos" method="post" id="frmRecursosVehiculo" name="frmRecursosVehiculo">
    {{ csrf_field() }}
    <input type="hidden" name="contraparte" value="{{$contraparte}}">
    <input type="hidden" name="contratista" value="{{$contratista}}">
    <input type="hidden" name="cliente" value="{{$cliente}}">
    <input type="hidden" name="led_seccion" value="V">
    <input type="hidden" name="vehiculo" value="">    
    <input type="hidden" name="periodo" value="{{$periodo}}">
    {{--<input type="hidden" name="periodo_vencido" value="{{$periodo_vencido}}">--}}    
</form>

<div id="modalRecursosVeh" class="modal fade" data-backdrop="static" data-keyboard="false">
    <!--div class="modal-dialog" style="width:99%"-->
    <div class="modal-dialog" style="width:100%;height:95%;margin-top:-5px;">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close cerrarmodalRecursosVeh" aria-hidden="true">&times;</button>
                <h3 class="modal-title" id="recursos-title-veh"></h3>
            </div>
            <div class="modal-body" id="recursos-data-veh"></div>
        </div>
    </div>
</div>

{{--<script type="text/javascript" src="/js/imperium/vehiculos.js"></script>--}}
<script type="text/javascript">
$(document).ready(function () {
	Fancy.MODULESDIR = '/js/fancy/';

    var vehiculos;
    var selvehiculo;
    var boton_excel = '@traducir("Exportar a excel", "Exportar a excel")'; 
    var registros = '@traducir("Registros", "Registros")';  
    var pagina = '@traducir("Pagina", "Página")'; 
    var de = '@traducir("de", "de")'; 

    var columns_v = [
        {
            type: "select",
            locked: true,
            width: 70,
            align: "center",
            cellAlign: "center",
            hidden : true
        },
        /*
        {
            type: "string",
            title: '@traducir("País", "País")',
            index: "country_code",
            width: 90,
            cellAlign: "center",
            sortable: true,
            resizable: false,
            align: "center",
            locked: true,
            filter : {header:true} 
        },
        */
        {
            type: "string",
            title: '@traducir("Marca y modelo", "Marca y modelo")',
            index: "nombre_vehiculo",
            flex: 1,
            cellAlign: "left",
            sortable: true,
            resizable: true,
            align: "center",
            locked: true,
            filter : {header:true} 
        },
        {
            type: "string",
            title: '@traducir("Dominio", "Dominio")',
            index: "dominio",
            width: 120,
            cellAlign: "center",
            sortable: true,
            resizable: true,
            align: "center",
            locked: true,
            filter : {header:true} 
        },
        {
            type: "string",
            title: '@traducir("Año", "Año")',
            index: "modelo",
            width: 100,
            cellAlign: "center",
            sortable: true,
            resizable: true,
            align: "center",
            locked: true,
            filter : {header:true} 
        },
        {
            type: "string",
            title: '@traducir("Tipo vehículo", "Tipo vehiculo")',
            index: "nombre_tipo_vehiculo",
            width: 200,
            cellAlign: "center",
            sortable: true,
            resizable: true,
            align: "center",
            locked: true,
            filter : {header:true} 
        },
     
        {
            type: "string",
            title: '@traducir("Estado actual", "Estado actual")',
            index: "estado",
            width: 120,
            cellAlign: "center",
            sortable: true,
            resizable: false,
            align: "center",
            locked: true,
            filter : {header:true} 
        },
        { type : 'date' , 
          title : '@traducir("Ultimo período", "Último Período")',
          format : {read:'Y-m',write:'Y-m'} ,
          index : 'ultimo_periodo' ,
          width : 120 ,
          cellAlign : 'center',
          sortable : true ,
          resizable : true ,
          filter : {header:true} ,
          align : 'center' ,
          locked : true 
        },

        { type : 'string' , 
          title : '@traducir("Doc pendientes", "Doc Pendientes")',
          index : 'total_pendientes' ,
          width : 90 ,
          cellAlign : 'center',
          sortable : true ,
          resizable : true ,
          align : 'center' ,
          locked : true 
        },
        { type : 'string' , 
          title : '@traducir("Doc verificar", "Doc A verificar")',
          index : 'total_ingresados' ,
          width : 90 ,
          cellAlign : 'center',
          sortable : true ,
          resizable : true ,
          align : 'center' ,
          locked : true 
        },
        { type : 'string' , 
          title : '@traducir("Doc rechazados", "Doc Rechazados")',
          index : 'total_rechazados' ,
          width : 90 ,
          cellAlign : 'center',
          sortable : true ,
          resizable : true ,
          align : 'center' ,
          locked : true 
        },
        { type : 'string' , 
          title : '@traducir("Doc verificados", "Doc Verificados")',
          index : 'total_verificados' ,
          width : 90 ,
          cellAlign : 'center',
          sortable : true ,
          resizable : true ,
          align : 'center' ,
          locked : true 
        },

        {
            type: "string",
            index: "edit",
            width: 120,
            cellAlign: "center",
            sortable: false,
            resizable: false,
            align: "center",
            hidden : true,
        },
    ];

    actualizarFancyVehiculos();
/*
    $(document).on("change", "#periodo_vehiculo", function () {
        $('#frmRecursosVehiculo [name="periodo"]').val(
            $("#periodo_vehiculo :selected").val()
        );
        actualizarFancyVehiculos();
    });
*/
    function actualizarFancyVehiculos() {


        $('#loading-vehiculos').show();

        //$("#recursosVehiculos").html("");
/*
        // si el periodo seleccionado es anterior al vencido no se pueden dar desafectaciones
        var pv = $('#frmRecursosVehiculo [name="periodo_vencido"]').val();
        var ps = $("#periodo_vehiculo :selected").val();
        var col0 = columns_v[0];
        col0.width = parseInt(ps) >= parseInt(pv) ? 70 : 0;
        columns_v[0] = col0;
        $(".desafectar").prop("disabled", !(parseInt(ps) >= parseInt(pv)));
*/
        //selvehiculo = null;
        if (ajax) {
            ajax.abort();
        }
        $.ajax({
            method: "post",
            url: "/imperium/recursos-data-vehiculos",
            data: $("#frmRecursosVehiculo").serialize(),
            beforeSend: function () {
                /*$('#actions_veh').hide();*/
                $('#loading_veh').show();
                $("#recursosVehiculos").html("");
            },
            success: function (response) {
                var data = JSON.parse(response);
                var values = data.data;
                var hay = data.hay;
                
                //if (values[0].estado == 'undefined') 
                //if (values.length==0)
                if (hay=='NO')
                {
                    $('#loading-vehiculos').hide();
                    $('#loading-veh').hide();
                    $("#recursosVehiculos").html("<div class='col-md-12 h4 text-center'>El contratista no posee vehículos registrados en este período</div>");
                    return; 
                }
                var pais = data.pais;
                var tipos = data.tipos;
                var estados = data.estados;
                var periodos = data.periodos;
                var ult_periodos = data.ult_periodos;
                pais = Object.keys(pais).map(function (key) {
                    return pais[key];
                });
                /*
                var col = columns_v[1];
                col.type = "combo";
                col.multiSelect = true;
                col.itemCheckBox = true;
                col.minListWidth = 100;
                col.data = pais;
                col.displayKey = "info";
                col.valueKey = "info";
                col.listItemTpl =
                    '<span class="flag-icon flag-icon-background {cls}"></span>';
                col.render = function (o) {
                    var cls = "flag-icon-" + o.value;
                    //o.value = '<span class="flag-icon flag-icon-background ' + cls + '"></span>';
                    o.value =
                        '<span class="flag-icon flag-icon-background ' +
                        cls +
                        '"></span>';
                    //console.log("b"+o.value);
                    return o;
                };
                columns_v[1] = col;
                */

                tipos = Object.keys(tipos).map(function (key) {
                    return tipos[key];
                });
                var col = columns_v[4];
                col.type = "combo";
                col.multiSelect = true;
                col.itemCheckBox = true;
                col.minListWidth = 100;
                col.data = tipos;
                col.displayKey = "nombre_tipo_vehiculo";
                col.valueKey = "nombre_tipo_vehiculo";
                col.listItemTpl = "";
                col.render = function (o) {
                    return o;
                };
                columns_v[4] = col;

                estados = Object.keys(estados).map(function (key) {
                    return estados[key];
                });
                var col = columns_v[5];
                col.type = "combo";
                col.multiSelect = true;
                col.itemCheckBox = true;
                col.minListWidth = 100;
                col.data = estados;
                col.displayKey = "nombre_estado";
                col.valueKey = "nombre_estado";
                col.listItemTpl = "";
                col.render = function (o) {
                    return o;
                };
                columns_v[5] = col;
               
                ult_periodos = Object.keys(ult_periodos).map(function (key) {
                    return ult_periodos[key];
                });
                var col = columns_v[6];
                col.type = "combo";
                col.multiSelect = true;
                col.itemCheckBox = true;
                col.minListWidth = 100;
                col.data = ult_periodos;
                col.displayKey = "periodo_Ym";
                col.valueKey = "periodo_Ym";
                col.listItemTpl = "";
                col.render = function (o) {
                    return o;
                };
                columns_v[6] = col;

                $('#loading-vehiculos').hide();

                //if (values[0].estado !== 'undefined') {
                //if (values.length > 0) {
                if (hay == 'SI') {
                    //vehiculos = null;
                    vehiculos = new FancyGrid({
                        renderTo: "recursosVehiculos",
                        width: $('#seccion-empleados').width() - ($('#seccion-empleados').width() * .00),
                        height: 640,
                        theme: {
                            name: "gray",
                        },
                         lang: {
                            paging: {
                                info: registros + ' [0] - [1] '+ de +' [2]',
                                page: pagina,
                                of: de + ' [0]'
                            },
                        },      
                       
                          /* Excel */
                        exporter: true,
                        subTBar: [
                         {
                          text: "<button style='background-color:#20a464; width:150px; margin-top: 0px;' type = 'button' class= 'form-control botones-paginador'><i class='fas fa-file-excel'></i>&nbsp;&nbsp;" + boton_excel + "</button>",
                          handler: function() {
                            this.exportToExcel({
                              fileName: 'vehiculos',
                              all: true,
                              header: true, 
                              ignoreRender: true
                            });
                            }
                          },
                        /*, {
                          text: 'Export to CSV',
                          handler: function() {
                            grid.exportToCSV({
                              fileName: 'Contrapartes',
                              ignoreRender: true,
                              header: true,
                              all: false
                            });
                          }*/
                        
                        ],
                        columns: columns_v,
                        paging : true,
                        paging : {
                            pageSize: 20,
                            pageSizeData: [10,20,50],
                            barType: 'tbar'
                        },  
                        selModel: { type: "rows", memory: true },
                        data: values,
                        /* Agregado 8/5/2020 */
                        scrollable: true,
                        cellHeight: 26,
                        //Habilita el agregado de css en todas las celdas de un fila cuando se hace mouseover.
                        trackOver: true,   

                        events: [
                                  {
                                  init: function (g) {                                          
                                             $('#recursosVehiculos .fancy').removeClass('fancy-panel-shadow');
                                        $('#recursosVehiculos .fancy-bar-button').removeAttr("style");
                                             
                                            $('#recursosVehiculos .fancy-panel-tbar').css('border-bottom', '0px'); 
                                            $('#recursosVehiculos                                    .fancy-panel-tbar .fancy-bar-left-scroller').remove(); 
                                            $('#recursosVehiculos                                    .fancy-panel-tbar .fancy-bar-right-scroller').remove(); 
                                           
                                                                              

                                           /*
                                            $('#recursosVehiculos .fancy-bar-button').removeAttr("style");
                                            //$('#recursosVehiculos .fancy-bar-left-scroller').removeAttr("style");
                                            //$('#recursosVehiculos .fancy-bar-right-scroller').removeAttr("style");
                                            $('#recursosVehiculos .fancy-panel-tbar').css('border-bottom', '0px'); 
                                            $('#recursosVehiculos .fancy-panel-sub-tbar').css('border-bottom', '0px'); 
                                            $('#recursosVehiculos .fancy-bar-button').css('border','0px'); */
                                            },
                                                scope: {}
                                           
                                    }, {
                                cellclick: function (vehiculos, obj) {
                                    var selvehiculo = vehiculos.getSelection();
                                    $('#frmRecursosVehiculo [name="vehiculo"]').val(
                                        selvehiculo[0].vehiculo
                                    );
                                    var per_sel = $('#frmRecursosVehiculo [name="periodo"]').val();
                                    var per_sel = per_sel.substring(4,6) + "/" + per_sel.substring(0,4); 
                                    if (ajax) {
                                        ajax.abort();
                                    } 
                                    $.ajax({
                                        method: "post",
                                        url:
                                            "/imperium/recursos-datos-vehiculo",
                                        data: $("#frmRecursosVehiculo").serialize(),
                                        beforeSend: function () {
                                            $("#recursos-title-veh").html(
                                                "Datos del vehículo - Período: " + per_sel
                                            );
                                            $("#recursos-data-veh").html("");
                                        },
                                        success: function (response) {
                                            $('.cerrarmodalContraparte').attr('disabled','disabled');
                                            $("#recursos-data-veh").html(response);
                                            $("#modalRecursosVeh").modal("show");
                                        },
                                    });
                                },
                            },
                        ],
                    });
                } 

                $("#recursosVehiculos").show();
            },
        });
    }

    $(window).resize(function () {
        if (vehiculos != null) {
            vehiculos.setWidth(seccion-vehiculos.innerWidth - (seccion-vehiculos.innerWidth * .00));
            vehiculos.setHeight(seccion-vehiculos.innerHeight - (seccion-vehiculos.innerHeight * .20));
            vehiculos.update();
        }
    });

    $('#periodo_vehiculo').on('change', function() {
        $('#frmRecursosVehiculo [name="periodo"]').val($('#periodo_vehiculo :selected').val());
        actualizarFancyVehiculos();
    });

    $('.cerrarmodalRecursosVeh').on('click', function() {
        $('#modalRecursosVeh').modal('hide');
        // Si se cambio el estado, redibuja la fancy de vehiculos, porque no trae los desafectados en el periodo....
        if($('#frmEditVehiculo [name="estado"]').val() != '' &&
           $('#frmEditVehiculo [name="contratista"]').val() == $('#frmEditVehiculo [name="contratista_1"]').val())
        {
            alert ('Recargamos los datos, porque se cambio el estado del vehículo.');     
            $('#frmRecursosVehiculo [name="periodo"]').val($('#periodo_vehiculo').val());
            actualizarFancyVehiculos();
        } 
        $('.cerrarmodalContraparte').removeAttr('disabled');
    });

   
});
</script>
<!--script>
    $(document).ready(function() {
    $('.cerrarmodalRecursosVeh').on('click', function() {
        $('#modalRecursosVeh').modal('hide');
        // Si se cambio el estado, redibuja la fancy de vehiculos, porque no trae los desafectados en el periodo....
        if($('#frmEditVehiculo [name="estado"]').val() != '' &&
           $('#frmEditVehiculo [name="contratista"]').val() == $('#frmEditVehiculo [name="contratista_1"]').val())
        {
            //alert('Actualiza fancy vehiculos... ');
            $('#frmRecursosVehiculo [name="periodo"]').val($('#periodo_vehiculo').val());
            actualizarFancyVehiculos();
        } 
        $('.cerrarmodalContraparte').removeAttr('disabled');
    });
    });
</script-->

@else
<div class="row" >
    <div class="col-md-12 h4 text-center">@traducir('El contratista no posee vehículos registrados','El contratista no posee vehículos registrados')</div>
</div>
@endif