@extends('header_nuevo_generico')
@section('main')
<style>
     .red {
            background-color: #E46B67;
        }
     .marron {
            background-color: #b59493;
        }
        
</style>
<div class="container-fluid " style="margin-top:10%;">
    <div class="row justify-content-between my-3">
        @if ($status == 'PENDIENTES')
            <div class="col-md-4 h3">Documentos pendientes de verificar</div>
            <div class="col-md-6 text-end">
                <button type="button" class="btn btn-fidelitas btn-sm btnpendientes" ><i class="fa fa-pause"></i>  Documentos pendientes</button>
                <button type="button" class="btn btn-success btn-sm" onclick="modalDefechas($(this));" data-estado ="VERIFICADOS"><i class="fa fa-check"></i>  Documentos verificados</button>
                <button type="button" class="btn btn-danger btn-sm" onclick="modalDefechas($(this));" data-estado ="RECHAZADOS"><i class="fa fa-times"></i>  Documentos rechazados</button>
            </div>
        @elseif ($status == 'VERIFICADOS')
            <div class="col-md-4 h3">Documentación verificada</div>
            <div class="col-md-6">
                <button type="button" class="btn btn-fidelitas btn-sm btnpendientes" ><i class="fa fa-pause"></i>  Documentos pendientes</button>
                <button type="button" class="btn btn-success btn-sm" onclick="modalDefechas($(this));" data-estado ="VERIFICADOS"><i class="fa fa-check"></i>  Documentos verificados</button>
                <button type="button" class="btn btn-danger btn-sm" onclick="modalDefechas($(this));"  data-estado ="RECHAZADOS"><i class="fa fa-times"></i>  Documentos rechazados</button>
            </div>
        @else
            <div class="col-md-4 h3">Documentación rechazada</div>
            <div class="col-md-6">
                <button type="button" class="btn btn-fidelitas btn-sm btnpendientes" ><i class="fa fa-pause"></i>  Documentos pendientes</button>
                <button type="button" class="btn btn-success btn-sm " onclick="modalDefechas($(this));" data-estado ="VERIFICADOS"><i class="fa fa-check"></i>  Documentos verificados</button>
                <button type="button" class="btn btn-danger btn-sm" onclick="modalDefechas($(this));"  data-estado ="RECHAZADOS"><i class="fa fa-times"></i>  Documentos rechazados</button>
            </div>
        @endif
    </div>
</div>
<div class="row" style="margin:1px;">
    <div class="col-md-12">
        <div id="loading" class="row" style="display:block;">
            <div class="col-md-1 col-md-offset-5"><img src="/images/loading.gif" class="img img-responsive" /></div>
        </div>
        <div id="tablaDocs" style="display:none;"></div>
    </div>
</div>

<div id="modalDocumento" class="modal fade"  aria-hidden="true" data-backdrop="static">
    <div class="modal-dialog modal-xl" style="min-width:95vw">
        <div class="modal-content">
            <div class="modal-header">
                <h3 class="modal-title" id="modal-title"></h3>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>

            <div class="modal-body" id="modal-body"></div>
        </div>
    </div>
</div>

<div id="modalConfirm" class="modal fade modal-confirm"  aria-hidden="true" data-backdrop="static">
    <div class="modal-dialog modal-xl" id="modal-confirm">
        <div class="modal-content">
            <div class="modal-header">
                <h3 class="modal-title" id="confirm-title">Confirmar operación</h3>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body" id="confirm-body"></div>
        </div>
    </div>
</div>

<div id="modalPdf" class="modal fade modal-pdf"  aria-hidden="true" data-backdrop="static">
    <div class="modal-dialog modal-lg" id="modal-pdf">
        <div class="modal-content">
            <div class="modal-header">
                <h3 class="modal-title" id="pdf-title">Documento anterior</h3>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body" id="pdf-body" style="height: 670px;"></div> 
            <div class="modal-body" id="pdf-pie"></div>
        </div>
    </div>
</div>

<form id="frmVerifDocumentos" name="frmVerifDocumentos" method="post" action="/DocumentosImperirum/documentos-verificados">
    {{csrf_field()}}
    <input type="hidden" name="doc_id" value="">
    <input type="hidden" name="doc_version" value="">
    <input type="hidden" name="desde_fecha" value="@if(isset($fecha_desde)){{$fecha_desde}}@endIf">
    <input type="hidden" name="cliente_busqueda" value="@if(isset($busqueda_cliente)){{$busqueda_cliente}}@endIf">
    <input type="hidden" name="fecha_vigencia" value="">
    <input type="hidden" name="status" value="{{$status}}">
</form>

<!-- Modal -->
<div class="modal fade" id="verificados_modal" tabindex="-1" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
            <h5 class="modal-title" id="verificados_modal_Label"></h5>
            <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div class="modal-body">
        <div class="row justify-content-center">
            <div class="mb-3 row">
                <label for="fecha_inicio_documentos" class="col-sm-2 col-form-label" id="subini">Fecha de inicio</label>
                <div class="col-sm-10">
                <input id="fecha_inicio_documentos" type="text" class="form-control" name="fecha_inicio_documentos" required="yes">
                </div>
            </div>

            <div class="mb-3 row">
                <label for="select_cliente_imperium" class="col-sm-2 col-form-label" id="subfin">Cliente</label>
                <div class="col-sm-10">
                    <select name="select_cliente_imperium" id="select_cliente_imperium" class="form-control">
                        <option value ="seleccione" selected>--Seleccione un cliente--</option>
                        @foreach($clientesImperium as $cliente)
                            <option value="{{$cliente->cliente}}">{{$cliente->nombre_cliente}}</option>
                        @endforeach
                    </select>	
                </div>
            </div>
            <div id="alerta_fechas_documentos" class="alert alert-danger d-none" role="alert">
            </div>
        </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cerrar</button>
        <button type="button" id ="busquedaDocumentosEStado" class="btn btn-success" onclick="submitTabla()" disabled>Enviar</button>
      </div>
    </div>
  </div>
</div>

<style>
    .container {
        min-width:90%
    }
</style>
@endsection

@section('funcionesJS')
<!-- use the latest version -->
<link rel="stylesheet" href="/Libreria_CA/monthpicker/monthpicker.css">
<script src="/Libreria_CA/monthpicker/monthpicker.js"></script>

<script src="/Libreria_CA/Js/xlsx.js?v=1"></script>
<script src="/Libreria_CA/Js/FileSaver.js?v=1"></script>
<script src="/js/general.js"></script>
<!--  -->
<script>
    $(document).ready(function() {     
        $('.btnpendientes').on('click',function() {
            location.href = '/DocumentosImperirum/verificacion-documentos-Imperium'
        });
         //configuracion del month picker
         var spanishLanguage = {
        Jan: 'Ene',
        Feb: 'Feb',
        Mar: 'Mar',
        Apr: 'Abr',
        May: 'May',
        Jun: 'Jun',
        Jul: 'Jul',
        Aug: 'Agos',
        Sep: 'Sept',
        Oct: 'Oct',
        Nov: 'Nov',
        Dec: 'Dic',
        months: ['Ene', 'Feb', 'Mar', 'Abr', 'May', 'Jun', 'Jul', 'Agos', 'Sept', 'Oct', 'Nov', 'Dic'],
        SelectMonth: 'Seleccionar mes',
        SelectYear: 'Seleccionar año',
        titleButtonShow: 'Mostrar mes',
        titleButtonPrev: 'Mes anterior',
        titleButtonNext: 'Siguiente mes'
        };
        $('#fecha_inicio_documentos').MonthPicker({ 
            ShowIcon: false ,
            i18n: spanishLanguage,
            OnAfterChooseMonth: function() { 
                var selectedDate = $(this).val();
                var selectedYear = new Date(selectedDate).getFullYear();
                var selectedMonth = (new Date(selectedDate).getUTCMonth() + 1).toString().padStart(2, '0');
                var dateCurrent = new Date().getFullYear()
                var monthCurrent = (new Date().getUTCMonth() + 1).toString().padStart(2, '0')
                if((parseInt(dateCurrent) - parseInt(selectedYear)) > 5){
                    $("#alerta_fechas_documentos").removeClass('d-none')
                    $("#alerta_fechas_documentos").text('El año elegido no debe ser 6 años menor al año actual')
                    setTimeout(() => {
                        $("#alerta_fechas_documentos").addClass('d-none')
                        $('#fecha_inicio_documentos').val('')
                        $("#alerta_fechas_documentos").text('')
                    }, 2000);
                }else if(parseInt(selectedYear) > parseInt(dateCurrent)){
                    $("#alerta_fechas_documentos").removeClass('d-none')
                    $("#alerta_fechas_documentos").text('El año elegido no debe ser mayor al año actual')
                    setTimeout(() => {
                        $("#alerta_fechas_documentos").addClass('d-none')
                        $("#alerta_fechas_documentos").text('')
                        $('#fecha_inicio_documentos').val('')

                    }, 2000);
                }
                else if(parseInt(selectedMonth) > parseInt(monthCurrent)){
                    $("#alerta_fechas_documentos").removeClass('d-none')
                    $("#alerta_fechas_documentos").text('El mes elegido no debe ser mayor al actual')
                    setTimeout(() => {
                        $("#alerta_fechas_documentos").addClass('d-none')
                        $("#alerta_fechas_documentos").text('')
                        $('#fecha_inicio_documentos').val('')
                    }, 2000);
                }
            } 
            });
             var prueba;


            $('.btnpendientes').on('click',function() {
                location.href = '/DocumentosImperirum/verificacion-documentos-Imperium'
            });
            var estado = $('#frmVerifDocumentos [name="status"]').val();

        $.ajax({
                method : 'post',
                url : '/Imperium/documentos/verificacion-documentos-data',
                data : $('#frmVerifDocumentos').serialize(),
                dataType : 'json',
                beforeSend : function() {
                    $('#loading').show();
                    $('#tablaDocs').hide();
                }, 
                success : function(response) {
                    var docs = response.docs;

                    //let etiquetas = ['NO', 'SI', 'PARCIAL ACTUALIZADO', 'REAPERTURA POR ALTA',];

                    let etiquetas = {!! json_encode(App\Custom\Misc::etiquetas()) !!}
                    $.each(docs, function(i, el) {
                        docs[i].periodo_my = el.periodo.substring(4,6) + '-' + el.periodo.substring(0,4);
                        docs[i].nombre_contratista = (el.contratista == el.contratista_1) ? null : el.nombre_contratista;
                        docs[i].ci_killer = (el.ci_killer == 1) ? 'SI' : 'NO';
                        docs[i].aprobacion_parcial = etiquetas[el.estado];
                    });
                    var periodos = response.periodos;
                    var secciones = response.secciones;
                    var acceso = response.acceso;
                    var parcial = response.parcial;
                    var servicios = response.servicios;
                    var clientes = response.clientes;
                    var complejidad = response.complejidad;
                    var familias = response.familias;
                    var gridDocs;
                    var columns = [
                        {type:'string',title:'A.Parcial', index:'aprobacion_parcial', width:60,align:'center',cellAlign:'center',resizable:false,sortable:false,filter: {header:true}},

                        {type:'date',title:'F. Toler.',index:'tolerancia_verif',width:80,align:'center',cellAlign:'center',resizable:true,sortable:true,format : {read:'Y-m-d', write: 'd/m/y'}},

                        {type:'string',title:'Compl',index:'codigo_complejidad',width:70,align:'center',cellAlign:'center',resizable:false,sortable:true,filter: {header:true}},

                        {type:'string',title:'Acceso',index:'ci_killer', width:60,align:'center',cellAlign:'center',resizable:false,sortable:false,filter: {header:true}},

                        {type:'string',title:'Cliente',index:'nombre_cliente',width:200,align:'center',cellAlign:'left',resizable:true,sortable:true,filter: {header:true}},

                        { 

                            type : 'string' , title : 'Período' , width:60,
                            index : 'periodo_my' , cellAlign : 'center', 
                            sortable : true , resizable : true ,  align : 'center', filter: {header:true},
                            sorter : function (dir, a, b) {
                                if ($.trim(a) !== '') {
                                    a = a.substr(3,4) + a.substr(0,2); 
                                }
                                if ($.trim(b) !== '') {
                                    b = b.substr(3,4) + b.substr(0,2);
                                }

                                switch (dir) {
                                    case 'asc':
                                        if ($.trim(a) === '') {
                                            a = '>'.repeat(10);
                                        }
                                        if ($.trim(b) === '') {
                                            b = '>'.repeat(10);
                                        }
                                        return (a > b) ? 1 : -1;
                                    case 'desc':
                                        return (b > a) ? 1 : -1;

                                }
                                return;
                            }
                        },

                        {type:'string',title:'Contratista',index:'contratista',width:250,align:'center',cellAlign:'left',resizable:true,sortable:true,filter: {header:true}},

                        {type:'string',title:'Identificacion', /*hidden:true,*/index:'numero_1',align:'center',cellAlign:'center',resizable:true,sortable:true,filter: {header:true}},
                        
                        {type:'string',title:'Familia',index:'nombre_familia',width:100,align:'center',cellAlign:'center',resizable:true,sortable:true,filter: {header:true}},

                        {type:'string',title:'Documento',index:'nombre_tipo_doc',width:250,align:'center',cellAlign:'left',resizable:true,sortable:true,filter: {header:true}},

                        {type:'string',title:'Subcontratista',index:'subcontratista',width:200,align:'center',cellAlign:'left',resizable:true,sortable:true,filter: {header:true}},

                        {type:'string',title:'Empleado', index:'empleado',width:200,align:'center',cellAlign:'left',resizable:true,sortable:true,filter: {header:true}},

                        {type:'string',title:'CUIL', /*hidden:true,*/ index:'numero_e',align:'center',cellAlign:'center',resizable:true,sortable:true,filter: {header:true}},

                        {type:'string',title:'Vehículo', index:'vehiculo',width:200,align:'center',cellAlign:'left',resizable:true,sortable:true,filter: {header:true}},

                        {type:'string',title:'Dominio',  /*hidden:true,*/ index:'dominio',align:'center',cellAlign:'center',resizable:true,sortable:true,filter: {header:true}},
                        
                        {type:'date',title:'Plazo carga',index:'fecha_tolerancia',width:80,align:'center',cellAlign:'center',resizable:true,sortable:true, format : {read:'Y-m-d', write: 'd/m/y'} },
                        
                        {type:'string',title:'Servicio',index:'servicio',width:80, align:'center',cellAlign:'left',resizable:true,sortable:true,filter: {header:true}},
                        
                        {type:'number',title:'id',index:'doc_id',/*hidden:true,*/align:'center',cellAlign:'center',resizable:true,sortable:true},

                        {type:'string',title:'Sección',index:'nombre_seccion',width:80,align:'center',cellAlign:'center',resizable:true,sortable:true,filter: {header:true}},

                        {type:'number',title:'Días carga',index:'difCarga',width:80,align:'center',cellAlign:'center',resizable:true,sortable:true,filter: {header:true},render: function(o) {
                            var dias = parseInt(o.value);
                            if(dias > 90){
                                    o.cls = 'red';
                                //o.style['background-color'] = 'rgba(228, 107, 103, 0.4)';
                                }
                            return o;
                        }},
                        {
                            index : 'demoraCarga',
                            title : "Demora Carga",
                            type : 'combo',
                            itemCheckBox: true,
                            multiSelect: true,
                            minListWidth: 300,
                            width:150,align:'center',cellAlign:'center',resizable:true,sortable:true,
                            data : [
                                'EN PLAZO',
                                'MENOS 30 DIAS',
                                'ENTRE 30 y 60 DIAS',
                                'ENTRE 60 y 90 DIAS',
                                'ENTRE 90 y 120 DIAS',
                                'ENTRE 120 y 150 DIAS',
                                'ENTRE 150 y 180 DIAS',
                                'MAS 180 DIAS',
                                'SIN FECHA'
                            ],
                            filter : {
                                header : true,
                                emptyText: ""                        
                            }
                        },
                        {type:'number',title:'Días verif',index:'difVerif',width:80,align:'center',cellAlign:'center',resizable:true,sortable:true,filter: {header:true}, render: function(o) {
                            var dias = parseInt(o.value);
                            if(dias > 60){
                                    o.cls = 'marron';
                                //o.style['background-color'] = 'rgba(228, 107, 103, 0.4)';
                                }
                            return o;
                            }
                        },
                        /*{type:'string',title:'Compl.',index:'codigo_complejidad', width:60,align:'center',cellAlign:'center',resizable:true,sortable:true,filter: {header:true}}, */
                    ];
                    
                    if($('#frmVerifDocumentos [name="status"]').val() !== 'PENDIENTES') {
                        var col = columns[19];
                        col.hidden = true; 
                        columns[19] = col;
                        var col = columns[20];
                        col.hidden = true; 
                        columns[20] = col;
                        var col = columns[21];
                        col.hidden = true; 
                        columns[21] = col;
                    }
                    var col = columns[16];
                    col.type = 'combo';
                    col.multiSelect = true;
                    col.itemCheckBox = true;
                    col.minListWidth = 100;
                    col.data = servicios;
                    col.displayKey = 'servicio';
                    col.valueKey = 'servicio';
                    col.render = function (o) {
                        o.value = $.trim(o.value);
                        return o;
                    }
                    columns[16] = col;
                    var col = columns[4];
                    col.type = 'combo';
                    col.multiSelect = true;
                    col.itemCheckBox = true;
                    col.minListWidth = 100;
                    col.data = clientes;
                    col.displayKey = 'nombre_cliente';
                    col.valueKey = 'nombre_cliente';
                    col.render = function (o) {
                        o.value = $.trim(o.value);
                        return o;
                    }
                    columns[4] = col;
                    var col = columns[8];
                    col.type = 'combo';
                    col.multiSelect = true;
                    col.itemCheckBox = true;
                    col.minListWidth = 300;
                    col.data = familias;
                    col.displayKey = 'nombre_familia';
                    col.valueKey = 'nombre_familia';
                    col.render = function (o) {
                        o.value = $.trim(o.value);
                        return o;
                    }
                    columns[8] = col;
                    var col = columns[18];
                    col.type = 'combo';
                    col.multiSelect = true;
					col.itemCheckBox = true;
					col.minListWidth = 100;
					col.data = secciones;
					col.displayKey = 'nombre_seccion';
					col.valueKey = 'nombre_seccion';
					col.render = function (o) {
						o.value = $.trim(o.value);
						return o;
			        }
                    columns[18] = col;
                    var col = columns[5];
                    col.type = 'combo';
                    col.multiSelect = true;
					col.itemCheckBox = true;
					col.minListWidth = 100;
					col.data = periodos;
					col.displayKey = 'periodo_my';
					col.valueKey = 'periodo';
					col.render = function (o) {
						o.value = $.trim(o.value);
						return o;
					}
                    columns[5] = col;

                    /* CODIGO DE COMPLEJIDAD */

                    var col = columns[2];
                    col.type = 'combo';
                    col.multiSelect = true;
					col.itemCheckBox = true;
					col.minListWidth = 100;
					col.data = complejidad;
					col.displayKey = 'codigo_complejidad';
					col.valueKey = 'codigo_complejidad';
					col.render = function (o) {
						o.value = $.trim(o.value);
						return o;
					}
                    columns[2] = col;
                    var col = columns[3];
                    col.type = 'combo';
                    col.multiSelect = true;
					col.itemCheckBox = true;
					col.minListWidth = 100;
					col.data = acceso;
					col.displayKey = 'acceso';
					col.valueKey = 'acceso';
					col.render = function (o) {
						o.value = $.trim(o.value);
						return o;
					}
                    columns[3] = col;
                    if (estado=='PENDIENTES') {
                        var col = columns[0];
                        col.type = 'combo';
                        col.multiSelect = true;
                        col.itemCheckBox = true;
                        col.resizable = true;
                        col.minListWidth = 100;
                        col.data = parcial;
                        col.displayKey = 'parcial';
                        col.valueKey = 'parcial';
                        col.render = function (o) {
                            o.value = $.trim(o.value);
                            return o;
                        }
                        columns[0] = col;
                    } else {
                        var col = columns[0];
                        //col.hidden = true; 
                        columns[0] = col;
                    }

                    if (docs.length > 0) {

					    gridDocs = new FancyGrid({
                            exporter: true,
                            id: 'documento-fancy',
                            renderTo : 'tablaDocs',
                            cellStylingCls: ['red','marron'],
                            height: 700,
                            cellHeight: 42,
                            theme: {
                                name: 'default',
                            },
                            lang: {
                                paging: {
                                    info: 'Documentos [0] - [1] de [2]',
                                    page: 'Página',
                                    of: 'de [0]'
                                },
                            },
                            selModel: { type : 'rows', memory : true },
                            paging : true,
                            paging : {
                                pageSize: 20,
                                pageSizeData: [10,20,50],
                                barType: 'tbar'
                            },
                            subTBar: [{
                                    text: 'Exportar a excel',
                                    type: 'button',
                                    pressed: true,
                                    enableToggle: false,
                                    handler: function(){
                                    gridDocs.exportToExcel({
                                        fileName: 'Documentos',
                                        all: true,
                                        header: true, 
                                    });
                                }
                            }],
                            data: docs,
                            columns: columns,
                            events: [{cellclick : function(grid, obj) {
                                selection = grid.getSelection();
                                var rec = selection[0];
                                grid.clearSelection(); //Para que no quede seleccionado el registro y pintado de otro color
                                $('#frmVerifDocumentos [name="doc_id"]').val(rec.doc_id);
                                $("#modalDocumento").modal("show");
                                $('#modal-title').html(rec.nombre_tipo_doc);
                                $.ajax({
                                    method : 'post',
                                    url : '/DocumentosImperirum/verificacion-documentos-doc',
                                    data : $('#frmVerifDocumentos').serialize(),
                                    beforeSend : function() {
                                        $('#modal-body').html('');
                                    },
                                    success : function(response) {
                                        $('#modal-body').html(response);
                                    }
                                });
                            }
                        }]
                    });
                } else {
                    $('#tablaDocs').html("<div class='text-center'><b> No se encuentra información </b></div>");
                }
                $('#loading').hide();
                $('#tablaDocs').show();
            }
        });
     $(document).on('click', '.replicar_nomina', function(e) {
         e.preventDefault();
            var fecha = $(this).data('ultima');
            var actual = $(this).data('actual');
            var fecha_my = $(this).data('ultima-my');
            var actual_my = $(this).data('actual-my');
            var contratista = $(this).data('contratista');
            var docid = $(this).data('docId');

         
            if (confirm('Confirma replicar la nómina del ' + fecha_my + ' en ' + actual_my))
            {
                $.ajax({
                method: 'post',
                url: '/documentos/replicar-nomina',
                data : { '_token' : '{{csrf_token()}}' , 'contratista' : contratista, 'periodo_de' : fecha, 'periodo_a' : actual },
                //dataType: 'json',
                beforeSend:function() {
                },
                success : function() {
                             
                    $.ajax({
                        method : 'post',
                        url : '/documentos/verificacion-documentos-doc',
                        data : $('#frmVerifDocumentos').serialize(),
                        beforeSend : function() {
                            $('#modal-body').html('');
                        },
                        success : function(response) {
                            var demo = Fancy.getWidget("documento-fancy");
                            demo.update();
                            $('#modal-body').html(response)
                        }
                    }); 


                }
            });
            }
        });


        $(document).on('click', '.actualizarVigencia, .actualizarVigenciaReemp', function() {
            var fld = $(this).hasClass('actualizarVigenciaReemp') ? 'fecha_vigencia_reemp' : 'fecha_vigencia';
            if($('#' + fld).val() != '') {
                $('#frmVerifDocumentos [name="fecha_vigencia"]').val($('#' + fld).val());
                $('#frmVerifDocumentos [name="doc_version"]').val($(this).data('docVersion'));
                $.ajax({
                    method: 'post',
                    url: '/documentos/actualizar-fecha-vigencia',
                    data: $('#frmVerifDocumentos').serialize(),
                    dataType: 'json',
                    beforeSend: function() {
                        $(this).prop('disabled', true);
                        if (fld == 'fecha_vigencia')
                        {
                            $('.actualizarVigencia').prop('disabled', true);
                        }
                        else 
                        {
                            $('.actualizarVigenciaReemp').prop('disabled', true);
                        }

                    },
                    success: function(response) {
                        alert(response.message);
                        if (fld == 'fecha_vigencia')

                        {
                            alert('aca'); 
                            $('.actualizarVigencia').prop('disabled', true);
                            $('.aprobardoc').prop('disabled', false);
                            $('.parcialdoc').prop('disabled', false);
                            $('.parcialdoc_modified').prop('disabled', false);
                        }
                        else 
                        {
                            alert('aca reem'); 

                            $('.actualizarVigenciaReemp').prop('disabled', true);
                            $('.aprobardocreemp').prop('disabled', false);
                            $('.parcialdocreemp').prop('disabled', false);
                            $('.parcialdocreemp_modified').prop('disabled', false);
                        }
                    }
                });
            } else { 
                alert ("No completó la fecha de vigencia a actualizar.")
            }
        });

        $(document).on('submit', '#frmVerificarDoc', function(e) {
            //Lo encontré. (1)
            e.preventDefault();
            $.ajax({
                method: 'post',
                url: '/documentos/verificar-documento',
                data: $(this).serialize(),
                dataType: 'json',
                beforeSend: function() {
                    $('.btnverificardoc1').prop('disabled', true);
                    $('.btnverificardoc2').prop('disabled', true);
                    $('#verificarDocLoading').show();
                    $('#verificarMsgResult').html('');
                    $('#verificarDocMessage').hide();
                },
                success: function(response) {
                    if (response.result == 0) {
                        $('#verificarMsgResult').removeClass('btn-danger');
                        $('#verificarMsgResult').addClass('btn-success');
                    } else {
                        $('#verificarMsgResult').removeClass('btn-succes');
                        $('#verificarMsgResult').addClass('btn-danger');
                    }
                    $('#verificarMsgResult').html(response.message);
                    $('#verificarDocLoading').hide();
                    $('#verificarDocMessage').show();
                    setTimeout(function() {
                        $('.btnverificardoc1').prop('disabled', false);
                        $('.btnverificardoc2').prop('disabled', false);
                        $('.close-modal').trigger('click');
                    }, 2500);

                    // Refresh del modal del documento

                    $.ajax({
                        method : 'post',
                        url : '/documentos/verificacion-documentos-doc',
                        data : $('#frmVerifDocumentos').serialize(),
                        beforeSend : function() {
                            $('#modal-body').html('');
                        },
                        success : function(response) {
                            var demo = Fancy.getWidget("documento-fancy");
                            var seleccion = demo.getSelection()[0];
                            var iden = demo.getSelection()[0].id;
                            demo.removeRowById(iden);
                            demo.update();
                            $('#modal-body').html(response)
                        }
                    });
                }
            });
        });

        $(document).on('submit', '#frmRechazarDoc', function(e) {
            e.preventDefault();
            $.ajax({
                method: 'post',
                url: '/documentos/rechazar-documento',
                data: $(this).serialize(),
                dataType: 'json',
                beforeSend: function() {
                    $('.btnrechazardoc1').prop('disabled', true);
                    $('.btnrechazardoc2').prop('disabled', true);
                    $('#rechazarDocLoading').show();
                    $('#rechazarMsgResult').html('');
                    $('#rechazarDocMessage').hide();
                },
                success: function(response) {
                    if (response.result == 0) {
                        $('#rechazarMsgResult').removeClass('btn-danger');
                        $('#rechazarMsgResult').addClass('btn-success');
                    } else {
                        $('#rechazarMsgResult').removeClass('btn-succes');
                        $('#rechazarMsgResult').addClass('btn-danger');
                    }
                    $('#rechazarMsgResult').html(response.message);
                    $('#rechazarDocLoading').hide();
                    $('#rechazarDocMessage').show();
                    setTimeout(function() {
                        $('.btnrechazardoc1').prop('disabled', false);
                        $('.btnrechazardoc2').prop('disabled', false);
                        
                        if (response.result != 2) {
                            $('.close-modal').trigger('click');
                        } else {
                            $('#rechazarDocMessage').hide();
                        }
                    }, 2500);

                    // Refresh del modal del documento

                    $.ajax({
                        method : 'post',
                        url : '/documentos/verificacion-documentos-doc',
                        data : $('#frmVerifDocumentos').serialize(),
                        beforeSend : function() {
                            $('#modal-body').html('');
                        },
                        success : function(response) {
                            var demo = Fancy.getWidget("documento-fancy");
                            if( demo.getSelection().length > 0 ){
                                var id_fila = demo.getSelection()[0].id;
                                demo.removeRowById(id_fila);
                            }
                            demo.update();
                            $('#modal-body').html(response)
                        }
                    });
                }
            });            
        });

        $(document).on('submit', '#frmVerificarDocParcial', function(e) {
            e.preventDefault();
            $.ajax({
                method: 'post',
                url: '/documentos/verificar-documento-parcial',
                data: $(this).serialize(),
                dataType: 'json',
                beforeSend: function() {
                    $('.btnverificardocparcial1').prop('disabled', true);
                    $('.btnverificardocparcial2').prop('disabled', true);
                    $('#verificarDocParcialLoading').show();
                    $('#verificarParcialMsgResult').html('');
                    $('#verificarDocParcialMessage').hide();
                },
                success: function(response) {
                    if (response.result == 0) {
                        $('#verificarParcialMsgResult').removeClass('btn-danger');
                        $('#verificarParcialMsgResult').addClass('btn-success');
                    }
                    else {
                        $('#verificarParcialMsgResult').removeClass('btn-succes');
                        $('#verificarParcialMsgResult').addClass('btn-danger');
                    }
                    $('#verificarParcialMsgResult').html(response.message);
                    $('#verificarDocParcialLoading').hide();
                    $('#verificarDocParcialMessage').show();
                    setTimeout(function() {
                        $('.btnverificardocparcial1').prop('disabled', false);
                        $('.btnverificardocparcial2').prop('disabled', false);
                        if (response.result != 2) {
                            $('.close-modal').trigger('click');
                        } else {
                            $('#verificarDocParcialMessage').hide();
                        }
                    }, 2500);

                    // Refresh del modal del documento

                    $.ajax({
                        method : 'post',
                        url : '/documentos/verificacion-documentos-doc',
                        data : $('#frmVerifDocumentos').serialize(),
                        beforeSend : function() {
                            $('#modal-body').html('');
                        },
                        success : function(response) {
                            $('#modal-body').html(response);
                        }
                    });
                }
            });
        });

        $(document).on('submit', '#frmUndoVerificarDoc', function(e) {
            e.preventDefault();
            $.ajax({
                method: 'post',
                url: '/documentos/undo-verificar-documento',
                data: $(this).serialize(),
                dataType: 'json',
                beforeSend: function() {
                    $('.btnundoverificardoc1').prop('disabled', true);
                    $('.btnundoverificardoc2').prop('disabled', true);
                    $('#undoVerificarDocLoading').show();
                    $('#undoVerificarMsgResult').html('');
                    $('#undoVerificarDocMessage').hide();
                },
                success: function(response) {
                    if (response.result == 0) {
                        $('#undoVerificarMsgResult').removeClass('btn-danger');
                        $('#undoVerificarMsgResult').addClass('btn-success');
                    } else {
                        $('#undoVerificarMsgResult').removeClass('btn-succes');
                        $('#undoVerificarMsgResult').addClass('btn-danger');
                    }
                    $('#undoVerificarMsgResult').html(response.message);
                    $('#undoVerificarDocLoading').hide();
                    $('#undoVerificarDocMessage').show();
                    setTimeout(function() {
                        $('.btnundoverificardoc1').prop('disabled', false);
                        $('.btnundoverificardoc2').prop('disabled', false);
                        if (response.result != 2) {
                            $('.close-modal').trigger('click');
                        } else {
                            $('#undoVerificarDocMessage').hide();
                        }
                    }, 2500);

                    // Refresh del modal del documento

                    $.ajax({
                        method : 'post',
                        url : '/documentos/verificacion-documentos-doc',
                        data : $('#frmVerifDocumentos').serialize(),
                        beforeSend : function() {
                            $('#modal-body').html('');
                        },
                        success : function(response) {
                            $('#modal-body').html(response);
                        }
                    });
                }
            });
        });

        $(document).on('submit', '#frmUndoRechazarDoc', function(e) {
            e.preventDefault();
            $.ajax({
                method: 'post',
                url: '/documentos/undo-rechazar-documento',
                data: $(this).serialize(),
                dataType: 'json',
                beforeSend: function() {
                    $('.btnundorechazardoc1').prop('disabled', true);
                    $('.btnundorechazardoc2').prop('disabled', true);
                    $('#undoRechazarDocLoading').show();
                    $('#undoRechazarMsgResult').html('');
                    $('#undoRechazarDocMessage').hide();
                },
                success: function(response) {
                    if (response.result == 0) {
                        $('#undoRechazarMsgResult').removeClass('btn-danger');
                        $('#undoRechazarMsgResult').addClass('btn-success');
                    } else {
                        $('#undoRechazarMsgResult').removeClass('btn-succes');
                        $('#undoRechazarMsgResult').addClass('btn-danger');
                    }
                    $('#undoRechazarMsgResult').html(response.message);
                    $('#undoRechazarDocLoading').hide();
                    $('#undoRechazarDocMessage').show();
                    setTimeout(function() {
                        $('.btnundorechazardoc1').prop('disabled', false);
                        $('.btnundorechazardoc2').prop('disabled', false);
                        if (response.result != 2) {
                            $('.close-modal').trigger('click');
                        } else {
                            $('#undoRechazarDocMessage').hide();
                        }
                    }, 2500);

                    // Refresh del modal del documento

                    $.ajax({
                        method : 'post',
                        url : '/documentos/verificacion-documentos-doc',
                        data : $('#frmVerifDocumentos').serialize(),
                        beforeSend : function() {
                            $('#modal-body').html('');
                        },
                        success : function(response) {
                            $('#modal-body').html(response)
                        }
                    });
                }
            });
        });
    });
    //función para levantar el modal, configuro los tipos de documentos para la ruta en el método de acción y el estado
    function modalDefechas(elemento) {
            var fechaHoy = new Date();
            var anioFechaUno = fechaHoy.getFullYear();
            var mesFechaUno = (fechaHoy.getMonth()+1).toString().padStart(2, '0');
            var fechaviejaUno = `${anioFechaUno}-${mesFechaUno}`
            $('input[name="fecha_inicio_documentos"]').val(fechaviejaUno) 
            // 
            $('input[name="cliente_busqueda"]').val('')
            $('input[name="desde_fecha"]').val('')
            $("#alerta_fechas_documentos").addClass("d-none")
            let estado;
            if(elemento.data("estado") == "RECHAZADOS"){
                $('#frmVerifDocumentos').prop('action', '/DocumentosImperirum/documentos-rechazados');
                $('#frmVerifDocumentos [name="status"]').val(elemento.data("estado"));
                estado = elemento.data("estado")
            }else if(elemento.data("estado") == "VERIFICADOS"){
                $('#frmVerifDocumentos').prop('action', '/DocumentosImperirum/documentos-verificados');
                $('#frmVerifDocumentos [name="status"]').val('VERIFICADOS');
                estado = elemento.data("estado")
            }
            $('#verificados_modal').modal("show");
            $('#verificados_modal_Label').text(`Documentos ${estado}`)
            $('#subini').text(`Período de documentos`)
            $("#busquedaDocumentosEStado").prop("disabled",true)
            seleccionCliente()
    }
    //seteo las fechas y el coloco el submit para el evento de regenerar la tabla funcy
    function submitTabla() {
        if($('input[name="fecha_inicio_documentos"]').val() === ""){
            $('input[name="fecha_inicio_documentos"]').val('') 
            //$('input[name="fecha_fin_documentos"]').val('')
            $("#alerta_fechas_documentos").removeClass("d-none") 
            $("#alerta_fechas_documentos").text("")
            $("#alerta_fechas_documentos").text("No se puede enviar datos vacios") 
            setTimeout(() => {
                $("#alerta_fechas_documentos").addClass("d-none")  
            }, 1000);
        }else{
            $('input[name="desde_fecha"]').val($("#fecha_inicio_documentos").val())
            $('#frmVerifDocumentos').submit();
        }
    }
    function seleccionCliente(){
        $("#select_cliente_imperium").on("change", function (e) {
            e.preventDefault();
            if(e.target.value === "seleccione"){
               $("#busquedaDocumentosEStado").prop("disabled",true)
               $('input[name="cliente_busqueda"]').val('')
            }else{
                $("#busquedaDocumentosEStado").prop("disabled",false)
                $('input[name="cliente_busqueda"]').val(e.target.value)
            }
        })
    }
</script>
@endsection