<style>
    .fancy.fancy-grid{
        overflow-x:auto;
        }
</style>
@if (!empty($subc))

<form id="frmPeriodosSubcontratista" name="frmPeriodosSubcontratista" class="form form-inline">
<div class="row">
    <div class="col-md-12 text-right">
        <label for="periodo_subcontratista">@traducir('Período','Período')</label>
        <select name="periodo_subcontratista" id="periodo_subcontratista" 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">
    <div class="col-md-12" id="recursosSubcontratistas"></div>
</div>	

<form action="/imperium/recursos-data-subcontratistas" method="post" id="frmRecursosSubcontratista" name="frmRecursosSubcontratista">
    {{ 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="S">
    <input type="hidden" name="subcontratista" value="">
    <input type="hidden" name="periodo" value="{{$periodo}}">
    {{--
    <input type="hidden" name="periodo_vencido" value="{{$periodo_vencido}}">
    --}}
</form>
<!--form name="frmEmpleadosSub" id="frmEmpleadosSub" method="post" action="/imperium/subcontratista/empleados"-->
<form name="frmEmpleadosSub" id="frmEmpleadosSub">
	{{ csrf_field() }}
	<input type="hidden" name="subcontratista" value="">
    <input type="hidden" name="contraparte" value="{{ $contraparte }}">
    <input type="hidden" name="cliente" value="{{ $cliente }}">
</form>

<!--form name="frmVehiculosSub" id="frmVehiculosSub" method="post" action="/imperium/subcontratista/vehiculos"-->
<form name="frmVehiculosSub" id="frmVehiculosSub">
	{{ csrf_field() }}
	<input type="hidden" name="subcontratista" value="">
    <input type="hidden" name="contraparte" value="{{ $contraparte }}">
    <input type="hidden" name="cliente" value="{{ $cliente }}">
</form>

<div id="modalRecursosSub" class="modal fade" data-backdrop="static" data-keyboard="false" style="overflow-y: auto;">
    <!--div class="modal-dialog" style="width:99%;height:80%"-->
    <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 cerrarmodalRecursosSub" aria-hidden="true">&times;</button>
                <h3 class="modal-title" id="recursos-title-sub"></h3>
            </div>
            <div class="modal-body" id="recursos-data-sub"></div>
        </div>
    </div>
</div>

<!--script>
    $(document).ready(function() {
        $('.cerrarmodalRecursosSub').on('click', function() {
            $('#modalRecursosSub').modal('hide');
            $('.cerrarmodalContraparte').removeAttr('disabled');
        });
    });
</script-->



{{--<script type="text/javascript" src="/js/imperium/subcontratistas.js"></script>--}}
<!-- -->
<script type="text/javascript">
$(document).ready(function () {
	Fancy.MODULESDIR = '/js/fancy/';
	
    var subcontratistas;
    var selsubcontratista;
    var boton_excel = '@traducir("Exportar a excel", "Exportar a excel")'; 
    var registros = '@traducir("Registros", "Registros")';  
    var pagina = '@traducir("Pagina", "Página")'; 
    var dede = '@traducir("de", "de")'; 

    var colSubcontratista = [
        {
            type: "select",
            locked: false,
            width: 70,
            align: "center",
            cellAlign: "center",
            hidden : true
        },
        {
            type: "string",
            title: '@traducir("País","País")',
            index: "country_code",
            exportable: false, 
            width: 90,
            cellAlign: "center",
            sortable: true,
            resizable: false,
            align: "center",
            locked: true,
            filter : {header:true} ,
        },
        {
            type: "string",
            title: '@traducir("Identificacion","Identificación")',
            index: "taxid",
            width: 120,
            cellAlign: "left",
            sortable: true,
            resizable: true,
            align: "center",
            locked: true,
            filter : {header:true} 
        },
        {
            type: "string",
            title: '@traducir("Nombre o razón social","Nombre o razón social")',
            index: "nombre_persona",
            width: 150,
            cellAlign: "left",
            sortable: true,
            resizable: true,
            align: "center",
            locked: true,
            filter : {header:true} 
        },
        {
            type: "string",
            title: '@traducir("Tipo contratista","Tipo contratista")',
            index: "nombre_tipo_contratista",
            //width: 200,
            flex: 1,
            cellAlign: "center",
            sortable: true,
            resizable: true,
            locked: true,
            filter : {header:true} ,
            align: "center"
        },
        {
            type: "string",
            title: '@traducir("Estado","Estado")',
            index: "estado",
            width: 120,
            cellAlign: "center",
            sortable: true,
            resizable: false,
            locked: true,
            filter : {header:true} ,
            align: "center"
        },
        {
            type: "string",
            title: '@traducir("Subcontratista de","Subcontratista de")',
            index: "nombre_persona_d",
            //width: 200,
            flex: 1,
            cellAlign: "left",
            sortable: true,
            resizable: true,
            locked: true,
            filter : {header:true} ,
            align: "center"
        },
        /*{
            type: "string",
            title: "Ver",
            index: "edit",
            width: 120,
            cellAlign: "center",
            sortable: false,
            resizable: false,
            align: "center",
            hidden: false,
        },*/
        /*{
            type: "string",
            title: '@traducir("Recursos","Recursos")',
            index: "recursos",
            exportable: false, 
            width: 120,
            cellAlign: "center",
            sortable: false,
            resizable: false,
            locked: true,
            align: "center"
        },*/
        {
            type: "string",
            title: '@traducir("Empleados","Empleados")',
            index: "empleados",
            exportable: false, 
            width: 120,
            cellAlign: "center",
            sortable: false,
            resizable: false,
            locked: true,
            align: "center"
        },
        {
            type: "string",
            title: '@traducir("Vehiculos","Vehiculos")',
            index: "vehiculos",
            exportable: false, 
            width: 120,
            cellAlign: "center",
            sortable: false,
            resizable: false,
            locked: true,
            align: "center"
        },
        { 
            type : 'date' , 
            title : '@traducir("Último Período","Último Período")',
            format : {read:'Y-m',write:'Y-m'} ,
            index : 'ultimo_periodo' ,
            width : 100 ,
            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("Do verificar","Doc A verificar")',
            index : 'total_ingresados' ,
            width : 90 ,
            cellAlign : 'center',
            sortable : true ,
            resizable : true ,
            align : 'center' ,
            locked : true 
        },
        { 
            type : 'string' , 
            title : '@traducir("Doc echazados","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 
        },
    ];

    actualizarFancySubcontratistas();
    /*
    $(document).on("change", "#periodo_subcontratista", function () {
        $('#frmRecursosSubcontratista [name="periodo"]').val(
            $("#periodo_subcontratista :selected").val()
        );
        actualizarFancySubcontratistas();
    });
    */

    function actualizarFancySubcontratistas() {
        $("#recursosSubcontratistas").html("");
        /*
        // si el periodo seleccionado es anterior al vencido no se pueden dar desafectaciones
        var pv = $('#frmRecursosSubcontratista [name="periodo_vencido"]').val();
        var ps = $("#periodo_subcontratista :selected").val();
        var col0 = colSubcontratista[0];
        col0.width = parseInt(ps) >= parseInt(pv) ? 70 : 0;
        colSubcontratista[0] = col0;
        $(".desafectar").prop("disabled", !(parseInt(ps) >= parseInt(pv)));

        selsubcontratista = null;
        */
        if (ajax) {
            ajax.abort();
        }
        $.ajax({
            method: "post",
            url: "/imperium/recursos-data-subcontratistas",
            data: $("#frmRecursosSubcontratista").serialize(),
            beforeSend: function () {
                /*$('#actions_sub').hide();*/
				$('#loading_sub').show();
                $("#recursosSubcontratistas").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_sub').hide();
                    $("#recursosSubcontratistas").html("<div class='col-md-12 h4 text-center'>El contratista no posee subcontratistas registrados en este período</div>");
                    return; 
                }
                var pais = data.pais;
                var tipos = data.tipos;
                var estados = data.estados;
                var periodos = data.periodos;
                var de = data.de;

                pais = Object.keys(pais).map(function (key) {
                    return pais[key];
                });
                var col = colSubcontratista[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}" title="{country_name}"></span>';
                col.render = function (o) {
                    var cls = "flag-icon-" + o.value;
                    var country_name = o.data.country_name;
                    //o.value = '<span class="flag-icon flag-icon-background ' + cls + '"></span>';
                    o.value =
                        '<span title="' + country_name + '" class="flag-icon flag-icon-background ' +
                        cls +
                        '"></span>';
                    return o;
                };
                colSubcontratista[1] = col;

                tipos = Object.keys(tipos).map(function (key) {
                    return tipos[key];
                });
                var col = colSubcontratista[4];
                col.type = "combo";
                col.multiSelect = true;
                col.itemCheckBox = true;
                col.minListWidth = 100;
                col.data = tipos;
                col.displayKey = "nombre_tipo_contratista";
                col.valueKey = "nombre_tipo_contratista";
                col.listItemTpl = "";
                col.render = function (o) {
                    return o;
                };
                colSubcontratista[4] = col;

                estados = Object.keys(estados).map(function (key) {
                    return estados[key];
                });
                var col = colSubcontratista[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;
                };
                colSubcontratista[5] = col;

                periodos = Object.keys(periodos).map(function (key) {
                    return periodos[key];
                });

                var col = colSubcontratista[6];
                col.type = "combo";
                col.multiSelect = true;
                col.itemCheckBox = true;
                col.minListWidth = 100;
                col.data = de;
                col.displayKey = "de";
                col.valueKey = "de";
                col.listItemTpl = "";
                col.render = function (o) {
                    return o;
                };
                colSubcontratista[6] = col;
 
                var col = colSubcontratista[9];
                col.type = "combo";
                col.multiSelect = true;
                col.itemCheckBox = true;
                col.minListWidth = 100;
                col.data = periodos;
                col.displayKey = "periodo_Ym";
                col.valueKey = "periodo_Ym";
                col.listItemTpl = "";
                col.render = function (o) {
                    return o;
                };
                colSubcontratista[9] = col;

                 periodos = Object.keys(periodos).map(function (key) {
                    return periodos[key];
                });
                // console.log(colSubcontratista);
                //if (values.length > 0) {
                if (hay=='SI') {
                    //subcontratistas = null;
                    subcontratistas = new FancyGrid({
                        renderTo: "recursosSubcontratistas",
                        width: $('#seccion-subcontr').width() - ($('#seccion-subcontr').width() * .00),
                        //height: 640,
                        height: 'fit',
                        theme: {
                            name: "gray",
                        },
                        lang: {
                            paging: {
                                info: registros + ' [0] - [1] '+ dede +' [2]',
                                page: pagina,
                                of: dede + ' [0]'
                            },
                        },      
                        
                         /* Excel */
                        exporter: true,
                        //subTBar: [
                        tbar: [
                         {
                          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: 'subcontratistas',
                              all: true,
                              header: true, 
                              ignoreRender: true
                            });
                            }
                          },
                            /*, {
                          text: 'Export to CSV',
                          handler: function() {
                            grid.exportToCSV({
                              fileName: 'Contrapartes',
                              ignoreRender: true,
                              header: true,
                              all: false
                            });
                          }*/
                        
                        ],
                        columns: colSubcontratista,
                        //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) {                                          
                                    $('#recursosSubcontratistas .fancy').removeClass('fancy-panel-shadow');
                                    $('#recursosSubcontratistas .fancy-bar-button').removeAttr("style");

                                    $('#recursosSubcontratistas .fancy-panel-tbar').css('border-bottom', '0px'); 
                                    $('#recursosSubcontratistas .fancy-button').css('border-bottom', '0px'); 
                                    $('#recursosSubcontratistas .fancy-panel-tbar .fancy-bar-left-scroller').remove(); 
                                    $('#recursosSubcontratistas .fancy-panel-tbar .fancy-bar-right-scroller').remove();     

                                    $('#recursosSubcontratistas .fancy-bar-right-scroller').remove(); 
                                    $('#recursosSubcontratistas .fancy-bar-left-scroller').remove(); 
                                    $('#recursosSubcontratistas .fancy-separator').remove(); 


                                     /*
                                    $('#documentosImperium .fancy-panel-tbar').append("<div style='width:123px;display:inline-block;margin-left: 5px;'><button style='background-color:#20a464;' type = 'button' class= 'form-control exportar-excel-di botones-paginador'><i class='fas fa-file-excel'></i> Exportar a Excel</button ></div >");
                                    $('#documentosImperium .fancy-panel-tbar').append(" <div style='width:123px;display:inline-block;margin-left: 10px;'><button style='background-color:#3498db;' type = 'button' class= ' form-control fancy-filter-off botones-paginador'><i class='fas fa-eye'></i> Mostrar Columnas</button ></div >");
                                        */
                                },scope: {}   
                            }, {
                                cellclick: function (subcontratistas, obj) {
                                    //
                                    if ( obj.columnIndex == 6 ){
                                        // ESTA COLUMNA TIENE LA ACCION DE LOS EMPLEADOS DE LA SUBCONTRATISTA
                                        let sub = obj.data.subcontratista;
                                        $('#frmEmpleadosSub [name="subcontratista"]').val(sub);
                                        if (ajax) {
                                            ajax.abort();
                                        }
                                        //
                                        $.ajax({
                                            method: "post",
                                            url: "/imperium/subcontratista/empleados",
                                            data: $("#frmEmpleadosSub").serialize(),
                                            beforeSend: function(){
                                                $("#recursos-title-sub").html("Recursos de Subcontratistas - Empleados");
                                                $("#recursos-data-sub").html("");
                                            },
                                            success: function(response){
                                                $("#recursos-data-sub").html(response);
                                                $("#modalRecursosSub").modal("show");
                                            },
                                        });
                                        return;
                                    } else if ( obj.columnIndex == 7  ){
                                        let sub = obj.data.subcontratista;
                                        $('#frmVehiculosSub [name="subcontratista"]').val(sub);
                                        //
                                        if (ajax) {
                                            ajax.abort();
                                        }
                                        //
                                        $.ajax({
                                            method: "post",
                                            url: "/imperium/subcontratista/vehiculos",
                                            data: $("#frmVehiculosSub").serialize(),
                                            beforeSend: function () {
                                                $("#recursos-title-sub").html(
                                                    "Recursos de Subcontratistas - Vehículos"
                                                );
                                                $("#recursos-data-sub").html("");
                                            },
                                            success: function (response) {
                                                $("#recursos-data-sub").html(response);
                                                $("#modalRecursosSub").modal("show");
                                            },
                                        });
                                        return;
                                    }
                                    //
                                    var selsubcontratista = subcontratistas.getSelection();
                                    //console.log(selsubcontratista); 
                                    $('#frmRecursosSubcontratista [name="subcontratista"]').val(
                                        selsubcontratista[0].contratista
                                    );
                                    var per_sel = $('#frmRecursosSubcontratista [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-subcontratista",
                                            data: $("#frmRecursosSubcontratista").serialize(),
                                            beforeSend: function () {
                                                $("#recursos-title-sub").html(
                                                    "Datos del subcontratista - Período: " + per_sel
                                                );
                                                $("#recursos-data-sub").html("");
                                            },
                                            success: function (response) {
                                                $('.cerrarmodalContraparte').attr('disabled','disabled');
                                                $("#recursos-data-sub").html(response);
                                                $("#modalRecursosSub").modal("show");
                                                },
                                    });
                                },
                            },
                        ],
                    });
                }
                $('#loading_sub').hide();
                $("#loading-recursos").hide();
                $("#recursosSubcontratistas").show();

 // EVENTO DEL BOTON DE EMPLEADOS QUE TIENE EL SUBCONTRATISTA
                /*$(document).on("click", ".empsub", function () {
                $(".empsub").on("click",function(){
                    var sub = $(this).data("subcontratista");
                    $('#frmEmpleadosSub [name="subcontratista"]').val(sub);
                    if (ajax) {
                        ajax.abort();
                    }
                    //
                    $.ajax({
                        method: "post",
                        url: "/imperium/subcontratista/empleados",
                        data: $("#frmEmpleadosSub").serialize(),
                        beforeSend: function(){
                            $("#recursos-title-sub").html("Recursos de Subcontratistas - Empleados");
                            $("#recursos-data-sub").html("");
                        },
                        success: function(response){
                            $("#recursos-data-sub").html(response);
                            $("#modalRecursosSub").modal("show");
                        },
                    });
                });*/

                // EVENTO DEL BOTON DE VEHICULOS QUE TIENE EL SUBCONTRATISTA
                /*$(document).on("click", ".vehsub", function () {
                $(".vehsub").on('click',function(){
                    var sub = $(this).data("subcontratista");
                    $('#frmVehiculosSub [name="subcontratista"]').val(sub);
                    //
                    if (ajax) {
                        ajax.abort();
                    }
                    //
                    $.ajax({
                        method: "post",
                        url: "/imperium/subcontratista/vehiculos",
                        data: $("#frmVehiculosSub").serialize(),
                        beforeSend: function () {
                            $("#recursos-title-sub").html(
                                "Recursos de Subcontratistas - Vehículos"
                            );
                            $("#recursos-data-sub").html("");
                        },
                        success: function (response) {
                            $("#recursos-data-sub").html(response);
                            $("#modalRecursosSub").modal("show");
                        },
                    });
                });*/                
            },
        });
    }

    $(window).resize(function () {
        if (subcontratistas != null) {
            subcontratistas.setWidth(seccion-subcontr.innerWidth - (seccion-subcontr.innerWidth * .00));
            subcontratistas.setHeight(seccion-subcontr.innerHeight - (seccion-subcontr.innerHeight * .20));
            subcontratistas.update();
        }
    });

     $('#periodo_subcontratista').on('change', function() {
        $('#frmRecursosSubcontratista [name="periodo"]').val($('#periodo_subcontratista :selected').val());
        actualizarFancySubcontratistas();
    });
     
    $('.cerrarmodalRecursosSub').on('click', function() {
        $('#modalRecursosSub').modal('hide');
        $('.cerrarmodalContraparte').removeAttr('disabled');
    });

});
</script>


@else
<div class="row">
    <div class="col-md-12 h4 text-center">@traducir('El contratista no posee subcontratistas registrados','El contratista no posee subcontratistas registrados')</div>
</div>
@endif