

(function () {
    'use strict';

    $(initCustom);

    function initCustom() {

        // custom code

    }

})();

 
var indexRFC = 3;
var indexProcesses = 6;
var indexResponsable = 7;
var indexRerefences = 8;
var indexObservation = 9;
var indexUUID = 10;
var isLatestUpload = false;
var showedCompanies = false;
var blockFXKeys = false;
var isNotValidVersion = false;
var selectedRow = 0;
var isSelectAll = true;
var uuidList = [];
const storageKeyNames = {
    uuids: "uuids",
    initializationFlag: "isInitialized"
};
var companySelection = "";

$('.btn-expand-collapse').click(function (e) {
    $('.navbar-primary').toggleClass('collapsed');
});

////Initialize OnError in JS
window.onerror = function (message, source, lineno, colno, error) {

    const errorMsg = `[JS ERROR] ${message} at :${lineno}:${colno}`;

    var message = {
        providerType: '',
        action: '',
        documentType: '',
        value: errorMsg
    };

    chrome.webview.postMessage(JSON.stringify({
        type: "jsRuntimeError",
        payload: message
    }));
};

//Initialize components
$(document).ready(
    function () {
        //load guid metadata
        //var checkdatatable = document.getElementById("checkAllId");

        //checkdatatable.addEventListener("click", CheckAllTable);

        $.extend($.fn.dataTableExt.oSort, {
            "date-custom-pre": function (a) {

                if (!a || a === '' || a === 'null' || a === null)
                    return Number.NEGATIVE_INFINITY;

                var dateParts = a.split(' ');
                var datePart = dateParts[0].split('/');
                var timePart = dateParts[1].split(':');
                return Date.parse(datePart[2] + '-' + datePart[1] + '-' + datePart[0] + 'T' + timePart[0] + ':' + timePart[1] + ':00');
            },

            "date-custom-asc": function (a, b) {
                return a - b;
            },

            "date-custom-desc": function (a, b) {
                return b - a;
            }
        });
        //load guid metadata

        //shotcuts
        $(window).on("shown.bs.modal", function (event) {
            blockFXKeys = true;
        });

        $(window).on("hidden.bs.modal", function (event) {
            blockFXKeys = false;
        });

        shortcut.add("F3", function () {
            if (blockFXKeys) { return false; }

            if (showedCompanies) {
                return;
            }

            selectAllRecords();
        });

        shortcut.add("F4", function () {
            if (blockFXKeys) { return false; }

            if (showedCompanies) {
                return;
            }

            unselectAllRecords();
        });

        shortcut.add("F5", function () {
            if (blockFXKeys) { return false; }

            if (showedCompanies) {
                return;
            }

            if (!($(".btn-procesos").attr("disabled") === "disabled")) {
                showProcesses();
            }
        });

        shortcut.add("F6", function () {
            if (blockFXKeys) { return false; }

            if (showedCompanies) {
                return;
            }

            if (!($(".btn-responsables").attr("disabled") == "disabled")) {
                showResponsables();
            }
        });

        shortcut.add("F7", function () {
            if (blockFXKeys) { return false; }

            if (showedCompanies) {
                return;
            }

            if (!($(".btn-referencias").attr("disabled") == "disabled")) {
                showReference();
            }
        });

        shortcut.add("F8", function () {
            if (blockFXKeys) { return false; }

            if (showedCompanies) {
                return;
            }

            if (!($(".btn-observaciones").attr("disabled") == "disabled")) {
                showObservations();
            }
        });

        shortcut.add("F9", function () {

        });

        shortcut.add("F10", function () {

        });

        shortcut.add("F11", function () {

        });
        //shotcuts
        //column adjust to modal companies
        $('#companyListModal').on('shown.bs.modal', function () {
            // No se requiere columns.adjust() sin scrollX/scrollY
        });
        //column adjust to modal companies
        isNotValidVersion = false;
       

        $(window).keydown(function (event) {
            if (event.keyCode == 13) {
                event.preventDefault();
                return false;
            }
        });

        $(document).unbind('keydown').bind('keydown', function (event) {
            var doPrevent = false;
            if (event.keyCode === 8) {
                var d = event.srcElement || event.target;
                if ((d.tagName.toUpperCase() === 'INPUT' &&
                    (
                        d.type.toUpperCase() === 'TEXT' ||
                        d.type.toUpperCase() === 'PASSWORD' ||
                        d.type.toUpperCase() === 'FILE' ||
                        d.type.toUpperCase() === 'EMAIL' ||
                        d.type.toUpperCase() === 'SEARCH' ||
                        d.type.toUpperCase() === 'DATE')
                ) ||
                    d.tagName.toUpperCase() === 'TEXTAREA') {
                    doPrevent = d.readOnly || d.disabled;
                }
                else {
                    doPrevent = true;
                }
            }

            if (doPrevent) {
                event.preventDefault();
            }
        });

        $(document).bind("contextmenu", function (e) {
            return false;
        });

       
   
        showedCompanies = true;
        loadingPanel(false);
    


    });

 

var showVersionDialog = function () {
    $(document).unbind("shown.bs.modal");
    bootbox.alert(
        {
            "message": "Para continuar con la carga de los CFDI al ADD es necesario contar con la versión 3.1.0 o posterior, de Herramientas Complementarias (Componentes).",
            "animate": false
        });
}


//Load downloaded sat recepits
var loadDocuments = function (type) {

    if (type == "satemitidos") {
        loadingPanel(true, 'Mostrando documentos emitidos descargados del SAT');
    } else if (type == "satrecibidos") {
        loadingPanel(true, 'Mostrando documentos recibidos descargados del SAT');
    } else if (type == "localemitidos") {
        loadingPanel(true, 'Mostrando documentos locales emitidos');
    } else if (type == "localrecibidos") {
        loadingPanel(true, 'Mostrando documentos locales recibidos');
    } else if (type == "satemitidossat") {
        loadingPanel(true, 'Mostrando documentos emitidos descargados de los servicios del SAT');
    } else if (type == "satrecibidossat") {
        loadingPanel(true, 'Mostrando documentos recibidos descargados de los servicios del SAT');
    }

    // ToDo: Disable buttons that are exclusive for ADD
    $(".btn-acciones-generales, .btn-cargar-add, .btn-exportar").removeAttr("disabled");

    //$("#dateFilters").appendTo($("#mainForm"));
    //$("#dateFilters").hide();
    //$('#example').DataTable().clear().draw();


    setTimeout(
        function () {
            loadingPanel(false);
        }, 1000);

};

let isErrorDialogVisible = false;
var showError = function (error) {

    if (!isErrorDialogVisible) {

        try {

            isErrorDialogVisible = true;
            $(document).unbind("shown.bs.modal");
            bootbox.dialog({
                message: error,
                title: "Ocurrió un error",
                closeButton: true,
                animate: false,
                locale: "es",
                buttons: {
                    cancel: {
                        label: "Cerrar",
                        className: "btn-company",
                        callback: function () {
                            isErrorDialogVisible = false;
                        }
                    }
                },
                onShow: function () {
                    isErrorDialogVisible = true;
                },
                onEscape: function () {
                    isErrorDialogVisible = false;
                },
                onHide: function () {
                    isErrorDialogVisible = false;
                }
            });
        } catch (e) {
            isErrorDialogVisible = false;
        }
    }
};

//function fAlCrearFila(row, data, index) {
//    row.id = data[0];

//    if (loadType.indexOf("emitido") > 0) {
//        //$(row.childNodes[indexRFC]).attr("style", "background-color: #fdfdfd !important;");
//        $(row.childNodes[indexRFC + 1]).addClass("cellSelection");

//        $(row.childNodes[indexProcesses]).addClass("hideCell");
//        $(row.childNodes[indexResponsable]).addClass("hideCell");
//    }
//    else if (loadType.indexOf("recibido") > 0) {
//        //$(row.childNodes[indexRFC + 1]).attr("style", "background-color: #fcfcfc !important;");
//        $(row.childNodes[indexRFC]).addClass("cellSelection");
//    }
//}

//Funtion to set a color to a row
var selectedRows = {};

//Funtion to enable y disable scroll
var preventScroll = function (e) {
    e.preventDefault();
};

var disableScroll = function () {
    window.addEventListener('scroll', preventScroll, { passive: false });
    window.addEventListener('wheel', preventScroll, { passive: false });
    window.addEventListener('touchmove', preventScroll, { passive: false });
};

var enableScroll = function () {
    window.removeEventListener('scroll', preventScroll);
    window.removeEventListener('wheel', preventScroll);
    window.removeEventListener('touchmove', preventScroll);
};


//Show a loading panel
var loadingPanel = function (show, text) {
     
    if (show) {
        addClassLoaderAlt();
        $("#loader_alt_panel").show();
        $('#loaderAltText').text(text);
        disableScroll();
    }
    else {
        removeClassLoaderAlt();
        $("#loader_alt_panel").hide();
        enableScroll();
    }
}

var addClassLoaderAlt = function () {
    document.body.classList.add('loader-alt-active');
    document.querySelector('.loader-alt-overlay').style.display = 'block';
    document.querySelector('.loader-alt').style.display = 'flex';

    setTimeout(() => {
        document.querySelector('.loader-alt-overlay').classList.add('show');
        document.querySelector('.loader-alt').classList.add('show');
    }, 10);
}

var removeClassLoaderAlt = function () {
    document.querySelector('.loader-alt-overlay').classList.remove('show');
    document.querySelector('.loader-alt').classList.remove('show');

    setTimeout(() => {
        document.body.classList.remove('loader-alt-active');
        document.querySelector('.loader-alt-overlay').style.display = 'none';
        document.querySelector('.loader-alt').style.display = 'none';
    }, 300);
}

//Show exit confirm
var showExitConfirm = function () {

    //Add Exit ID to primary button
    $(document).unbind("shown.bs.modal");
    $(document).on("shown.bs.modal", function (event) { $("div .modal-footer .btn-primary").attr("id", "Exit"); });

    //Use bootbox 
    bootbox.dialog({
        id: "exitDialog",
        onEscape: function () { },
        animate: false,
        message: "¿Está seguro de que desea salir de la aplicación?",
        title: "Salir de la aplicación",
        buttons: {
            exit: { id: "Exit", name: "Exit", label: "Salir", className: "btn-primary", callback: function () { } },
            cancel: { label: "Cancelar", className: "btn-primary", callback: function () { } }
        }
    });
}

 
var showAbout = function () {

    var XMLVersion = 'Version("6.7.0")';
    var versionNumber = XMLVersion.match(/"([^"]+)"/)[1];
    var yearNow = new Date().getFullYear();
    //Quit any attribute for primary button
    $(document).unbind("shown.bs.modal");
    $(document).on("shown.bs.modal", function (event) { $("div .modal-footer .btn-primary").removeAttr("id"); });

    bootbox.dialog({
        id: "aboutDialog",
        animate: false,
        onEscape: function () { },
        message: "<p>Acerca de</p>" +
            "<p class=\"TextModalConfi\">Nombre de la aplicación:</br>CONTPAQi XML en línea+&reg;" +
            "<br>" +
            "Versión: " + versionNumber +  "Service Pack 1" +
            "<br>" +
            "Todos los derechos reservados 1984 - " + yearNow +
            "" + "<br><a href='#' class='aboutLink' id='About+https://servicios.contpaqi.com/App/About/About.aspx?License= ' data-documenttype='https://servicios.contpaqi.com/App/About/About.aspx?License='>Ver información de la licencia</a>" +
            "" + "<br><br><a href='#' class='aboutLink' id='About+https://www.contpaqi.com/aviso-de-privacidad-desktop' data-documenttype='https://www.contpaqi.com/aviso-de-privacidad-desktop'>Aviso de privacidad</a>" +
            "" + "<br><a href='#' class='aboutLink' id='About+https://www.contpaqi.com/licencia-desktop" + "' data-documenttype='https://www.contpaqi.com/licencia-desktop'>Licencia de uso</a></p>",


        buttons: {
            btnAbout: {
                id: "btnAbout", name: "btnAbout", label: "Aceptar", className: "btn-company", callback: function () { }
            }
        }
    });
}


var setLoadAllToADD = function () {
    $($('#example').dataTable().fnGetNodes()).find(".alt-checkbox").addClass("checked");
}

var setLoadSelectedToADD = function () {
    var selectedRows = $($('#example').dataTable().fnGetNodes()).filter(".row-selected-grid");
    $.each(selectedRows, function (index, row) {
        $(row).find(".alt-checkbox").addClass("checked");
    });
}

var setUnloadAllToADD = function () {
    $($('#example').dataTable().fnGetNodes()).find(".alt-checkbox").removeClass("checked");
}
 

function fEliminaFilas() {
    for (i = 0, seleccionadas = lFilasDePagina.length; i < seleccionadas; i++) {
        lTabla.fnDeleteRow("#" + lFilasDePagina[i].getAttribute("id"));
    }
}

 



var exportSelected = function (isSuccess, fileName) {
    loadingPanel(false);
    $(document).unbind("shown.bs.modal");
    $(document).on("shown.bs.modal", function (ev) {
        if (isSuccess) {
            $("div .modal-footer .btnshow").attr("id", "OpenExcel-" + fileName);
        }
    });

    if (isSuccess) {
        // Mostrar modal de éxito
        bootbox.dialog({
            message: ("<div class=\"row\"> <br/><br/><div class=\"col-1\">  </div><div class=\"col-11\"> <p>Exportación exitosa</p> <p class=\"TextModalConfi\">Los registros se han exportado correctamente en el directorio de la aplicación.<br>" + "<a style='text-decoration:none'>" + fileName + "</a></p></div></div>"),
            animate: false,
            onEscape: function () { },
            buttons: {
                success: {
                    label: "Cerrar", className: "btn-Acciones", callback: function () { }
                },
                openExcel: {
                    label: "Abrir archivo", className: "btn-company btnshow", callback: function () {
                        var message = {
                            providerType: "AbrirArchivo",
                            action: "menuClick",
                            documentType: fileName,
                            value: ''
                        };


                        chrome.webview.postMessage(JSON.stringify({
                            type: "WebViewMessage",
                            payload: message
                        }));

                    }
                }
            }
        });
    } else {
        // Mostrar modal de error
        bootbox.dialog({
            message: ("<div class=\"row\"> <br/><br/><div class=\"col-1\">  </div><div class=\"col-11\"> <p>Error al realizar la exportación.</p><p class=\"TextModalConfi\">Por favor, intente nuevamente más tarde.</p></div></div>"),
            animate: false,
            onEscape: function () { },
            buttons: {
                close: {
                    label: "Cerrar", className: "btn-Acciones", callback: function () { }
                }
            }
        });
    }
};



function encode_utf8(s) {
    return unescape(encodeURIComponent(s));
}

 


var getRFC = function (row) {
    if (loadType.indexOf('emitido') > 0) {
        return $(row.children[indexRFC + 1]).find(".RFCReceptor").text();
    } else if (loadType.indexOf('recibido') > 0) {
        return $(row.children[indexRFC]).find(".RFC").text();
    }
}


 
var tabletopobj = $('#tabletop').DataTable({
    dom: "<'row'<'col-sm-12'tr>>" +
        "<'row table-footer'<'col-lg-2'l><'col-lg-8'p><'col-lg-12'i>>",
    "lengthMenu": [[3, 5], [3, 5]],
    "pageLength": 3,
    "serverside": false,
    "autoWidth": false,
    columns: [
        { "data": "ID", "width": "80px" },
        {
            "data": "Fecha",
            "orderable": true,
            type: "date-custom", // Use the custom sorting type

        },
        {
            "data": "Tipo_de_Descarga",
            "orderable": true,
        },
        {
            "data": "Rangos_de_fecha",
            "orderable": true,
            "type": "daterange-custom", // Use the custom sorting type

        },
        {
            "data": "Activa",
            "orderable": true,
            render: function (data, type, row) {
                var clase = '';
                var spanSpinner = '';

                if (data == "INICIO" || row.Progreso == "METADATA" || row.Progreso == "CFDI") {
                    clase = 'EstatusYellow';
                    if (row.Tiene_Metadata === true) {
                        clase = 'EstatusGreen';
                    }
                     
                } else if (row.Progreso == "COMPLETADO") {
                    clase = 'EstatusGreen';
                }
                else if (row.Progreso == "CANCELADO" || row.Progreso == "ERROR") {
                    clase = 'EstatusRed'
                }
                else {
                    clase = 'EstatusYellow';
                    if (row.Tiene_Metadata === true) {
                        clase = 'EstatusGreen';
                    }
                  
                }

                if (row.Progreso != "COMPLETADO" && row.Progreso != "CANCELADO" && row.Progreso != "ERROR")
                    spanSpinner = '<span class="spinner-border spinner-border-sm spinner-custom-small " role="status" aria-hidden="true"></span>&nbsp;';

                return '<div class="' + clase + '" style="pointer-events: none;">' + spanSpinner + data + '</div>';
            }
        },
        {
            "data": "Cancel",
            "orderable": false,
            "searchable": "false",
            "width": "80px",
            render: function (data, type, row) {
                var disabled = row.Cancel ? 'disabled' : '';
                var html = '<div style="text-align: center;pointer-events: none;">' +
                    '<button type="button" title="Cancelar" ' +
                    (disabled ?
                        'disabled style="pointer-events: fill !important;cursor: not-allowed !important;"' :
                        'style="pointer-events: fill !important;"') +
                    ' data-id="' + row.ID + '" ' +
                    ' class="transparent-button cancelRequest-button  ' + disabled + '">' +
                    '<img src="content300/img/block.png" />' +
                    '</button>' +
                    '</div>';
                return html;
            }
        }
    ],
    language: {
        // Make sure the URL is correct and the file exists
        'url': 'content/js/dataTables.Spanish.js'
    },
    "rowCallback": function (row, d) {
        $('td:eq(0)', row).attr({ 'data-providertype': "BaseLoadListService", 'data-documenttype': d.ID });
        $('td:eq(1)', row).attr({ 'data-providertype': "BaseLoadListService", 'data-documenttype': d.ID });
        $('td:eq(2)', row).attr({ 'data-providertype': "BaseLoadListService", 'data-documenttype': d.ID });
        $('td:eq(3)', row).attr({ 'data-providertype': "BaseLoadListService", 'data-documenttype': d.ID });
        $('td:eq(4)', row).attr({ 'data-providertype': "BaseLoadListService", 'data-documenttype': d.ID });
        $('td:eq(5)', row).attr({ 'data-providertype': "BaseLoadListService", 'data-documenttype': d.ID });
        $(row).attr({ 'style': "cursor:pointer", 'id': "Rw-" + d.ID });
        $(row).addClass("tabletop-tr-hover");
    },
    order: [[0, "desc"]]
});


var viewportHeight = $(window).height();
//********************************************************** data - table **************************************//
// Variables para gestionar el ordenamiento de columnas en la tabla de detalles (DetailTable).
var columndetailTable = 1; // Identificador de la columna por la cual se ordena la tabla de detalles (por defecto, columna 1).
var isAscendingdetailTable = "desc"; // Dirección del ordenamiento en la tabla de detalles: "asc" para ascendente, "desc" para descendente.
var detailPageNumber = 1; // Número de página actual para la tabla de detalles (DetailTable).
let typingTimer;
const doneTypingInterval = 500; // Tiempo en milisegundos

var tablecompaniesobj = $("#companyTable").DataTable({
    dom: "<'row'<'col-sm-12'tr>>" +
        "<'row table-footer'<'col-lg-2'l><'col-lg-8'p><'col-lg-12'i>>",

    language: {
        // Make sure the URL is correct and the file exists
        'url': 'content/js/dataTables.Spanish.js'
    },
    "autoWidth": false,
    "lengthMenu": [[4, 5, 7, 10], [4, 5, 7, 10]],
    "pageLength": 4,
    columns: [
        {
            "data": "Favorite",
            orderable: false,
            class: "Cell0",
            render: function (data, type, row) {
                let isStarred = data ? "active" : ""
                let starredBtn = '<button type = "button" id = "favorite-' + row.Empresas + '-btn" class="favorite-btn ' + isStarred +
                    '" data-providertype="CompanyFavoriteService"  data-documenttype=' + row.Empresas + '>' +
                    '<i class=" fas fa-star ' + isStarred + '" data-providertype="CompanyFavoriteService"  data-documenttype="' + row.Empresas + '"></i></button>';
                return starredBtn;
            }
        },
        {
            "data": "Nombre",
            orderable: false,
            class: "ellipsis Cell1",
            render: function (data, type, row) {
                let dslid = row.DSLID ? '<div class="text-companies">' + row.DSLID + '</div>' : '';
                return '<div class="centered-container"><div class="text-companies"><b style="color:blue;font-size:16px;">' + row.RFC + '</b></div><div class="text-companies">' + data + '</div>' + dslid + '</div>';
            },
        },
        {
            "data": "ActualizadoAl",
            orderable: false,
            class: "Cell2",
            render: function (data, type, row) {

                return '<div class="centered-container">' + data + '</div>';
            },
        },
        /*{
            "data": "Comprobantes",
            orderable: false,
            class: "Cell3",
            render: function (data, type, row) {

                return '<div class="centered-container">' + data + '</div>';
            },
        },*/
        {
            "data": "Estado",
            orderable: false,
            class: "Cell4",
            render: function (data, type, row) {
                var checkedAttribute = data === true ? "checked" : "";
                var checkbox = `
                    <div class="custom-control custom-switch">
                        <input ${checkedAttribute} 
                               type="checkbox" 
                               class="custom-control-input company-toggle" 
                                data-providertype="CompaniesEnable"
                                data-documenttype="${row.Empresas}"
                               id="check-${row.Empresas}">
                        <label class="custom-control-label" for="check-${row.Empresas}"></label>
                    </div>`;
                return checkbox;
            }
        },
        {
            "data": "FielEstatus",
            orderable: false,
            class: "Cell5",
            render: function (data, type, row) {

                return '<div class="centered-container">' + data + '</div>';
            },
        },
        {
            "data": "Acciones",
            class: "CellAcciones",
            orderable: false,
        },
    ],
    "order": [],
});

$('#companyTable tbody').on('click', '.company-toggle', function () {
    var row = tablecompaniesobj.row($(this).closest('tr')).data();

    if (row) {
        showconfirmmodal(
            this,                        // checkbox
            row.Empresas,                // guid
            decodeHtmlEntities(row.Nombre), // nombre limpio
            row.DSLID,                   // HaveAdd
            row.FielActiva               // HaveFiel
        );
    }
});

 
function decodeHtmlEntities(str) {
    var txt = document.createElement("textarea");
    txt.innerHTML = str;
    return txt.value;
}


function showconfirmmodal(checkbox, guid, nombre, HaveAdd, HaveFiel) {
    try {
        var nombreLimpio = (typeof decodeHtmlEntities === 'function') ? decodeHtmlEntities(nombre) : String(nombre || '');

        var haveFielStr = (HaveFiel == null) ? '' : String(HaveFiel).toLowerCase();
        var isFielActiva = (haveFielStr === 'true' || haveFielStr === '1' || HaveFiel === true || HaveFiel === 1);

        var hasAdd = !(HaveAdd == null || HaveAdd === '' || HaveAdd === 'null' || HaveAdd === false);

        localStorage.setItem("checkboxvalue", checkbox.checked);
        localStorage.setItem("checkboxid", checkbox.id);

        if (hasAdd) {
            $("#companyguidmodal").html(
                'Esta acción cambiará el estado de la empresa <b>' + nombreLimpio +
                '</b> a "Inactiva", lo que significa que no se agendarán más descargas automáticas y ' +
                'para tener los CFDIs actualizados deberá activarse la empresa de nuevo.'
            );
            $("#confirmtitle").html(
                'La empresa permanecerá activa en el ADD y no se eliminarán los archivos ya descargados. ¿Desea continuar?'
            );
            $("#titleconfirmmodal").text("Desactivar empresa");
        } else {
            $("#companyguidmodal").html(
                'Esta acción eliminará la empresa <b>' + nombreLimpio +
                '</b> y no podrá recuperarla, mas no se eliminarán los archivos ya descargados. ¿Desea continuar?'
            );
            $("#confirmtitle").text("");
            $("#titleconfirmmodal").text("Eliminar empresa");
        }

        if (isFielActiva) {
            $("#PasswordForm").show();
        } else {
            $("#PasswordForm").hide();
        }

        if (!checkbox.checked) {
            $('#passwordInputconfirm').val("");
            $('#companyListModal').modal('hide'); // por si hay otro modal abierto
            $("#confirmModal").modal('show');
            $('#passwordInputconfirm').val("").focus();
            var $btn = $('button[name="deletebtnconfirm"]');
            $btn.prop("disabled", false);
            $btn.attr('data-providertype', 'CompaniesDelete');
            $btn.attr('data-documenttype', guid);
            $btn.attr('data-checked', checkbox.checked);
        }


    } catch (err) {
        // Si algo falla (p.ej. tipos raros), lo verás y no bloquea el resto
        alert('Error en showconfirmmodal: ' + err.message + '\nHaveFiel: ' + JSON.stringify(HaveFiel));
        console.error(err);
    }
}


if ($('#data-table').DataTable()) {
    $('#data-table').DataTable().destroy();
} 

var tabledetailsobj = $('#data-table').DataTable({
    dom: "<'row'<'col-sm-12'tr>>" +
        "<'row table-footer'<'col-lg-2'l><'col-lg-8'p><'col-lg-12'i>>",
    "lengthMenu": [[10, 25, 50, 100, 250, 500, 1000], [10, 25, 50, 100, 250, 500, 1000]],
    "pageLength": 100,
    "paging": false, // Desactiva la paginación de DataTables
    "searching": false, // Desactiva la búsqueda de DataTables
    //"ordering": true, // Desactiva el ordenamiento de columnas
    "processing": true,
    "deferRender": true,
    "language":
    {
        "url": "content/js/dataTables.Spanish.js"
    },
    columns: [
        {
            name: '', "orderable": false, class: "",
            data: function (d) {
                if (d.Checked == "True") {
                    return '<span><div class="checkbox c-checkbox">' +
                        '<label>' +
                        '<input type="checkbox" checked onclick="handleClick(this);">' +
                        '<span class="fa fa-check"></span>' +
                        '</label>' +
                        '</div></span>';
                }
                else {
                    return '<div class="checkbox c-checkbox">' +
                        '<label>' +
                        '<input type="checkbox"  onclick="handleClick(this);">' +
                        '<span class="fa fa-check"></span>' +
                        '</label>' +
                        '</div>';
                }
            }
        },
        { "name": "Fecha_emision", type: "date-custom", "orderable": true, "searchable": true, data: function (d) { return '<span>' + d.Fecha_emision + '</span>' }, class: "ellipsis CellFecha" },
        {
            "name": 'Estado', "orderable": true,
            data: function (d) {
                if (d.Estado.toUpperCase() == "VIGENTE") {
                    return '<span class="EstatusGreen">' + d.Estado + '</span>'
                }
                else {
                    return '<span class="EstatusCancelCFDI">' + d.Estado + '</span>'
                }


            }
            , class: "ellipsis"
        },
        {
            "name": "Fecha_Cancelacion", type: "date-custom", "orderable": true, "searchable": true, class: "ellipsis CellFecha",
            data: function (d) {
                if (d.Fecha_Cancelacion != null) {
                    return '<span>' + d.Fecha_Cancelacion + '</span>'
                }
                else {
                    return "";
                }
            }
        },
        { "name": 'Origen', "orderable": true, data: function (d) { return '<span title="' + d.Origen + '">' + d.Origen + '</span>' }, class: "ellipsis" },
        { "name": 'Tipo', "orderable": true, data: function (d) { return '<span title="' + d.Tipo + '">' + d.Tipo + '</span>' }, class: "ellipsis" },
        { "name": 'RFC', "orderable": true, data: function (d) { return '<span title="' + d.RFC + '">' + d.RFC + '</span>' }, class: "ellipsis" },
        { "name": 'Total', "orderable": true, data: function (d) { return '<span title="' + d.Total + '">' + d.Total + '</span>' }, class: "ellipsis" },
        { "name": 'UUID', "orderable": true, data: function (d) { return '<span title="' + d.UUID + '">' + d.UUID + '</span>' }, class: "ellipsis" },
        {
            "name": "Descargado",
            "orderable": true,
            "data": function (d) {
                var statusText = d.Descargado ? d.Descargado.toUpperCase() : "";
                var colorClass = (statusText === "DESCARGADO" || statusText === "CARGADO AL ADD" || statusText === "SOLO ACUSE")
                    ? "EstatusGreen"
                    : "EstatusYellow";

                return '<span class="' + colorClass + '">' + (d.Descargado || "Sin información") + '</span>';
            },
            "class": "ellipsis"
        },
        { "name": '', "orderable": false, data: function (d) { return '' }, class: "details-control" }

    ],
    "columnDefs": [
        { "width": "12%", "targets": 8 },
        { "width": "4%", "targets": 10 },
        { "width": "2%", "targets": 0 }
    ],
    order: []

});

$(document).ready(function () {
    let pageSizeSelector = $('#pageSizeSelector_detailTable');
    let lengthMenu = tabledetailsobj.settings().init().lengthMenu[0]; // Obtener los valores del menú de longitudes
    let pageLength = tabledetailsobj.settings().init().pageLength; // Obtener el valor inicial

    for (var i = 0; i < lengthMenu.length; i++) {
        var value = lengthMenu[i];
        var option = $('<option>', {
            value: value,
            text: value
        });

        // Verificar si el valor coincide con pageLength y marcarlo como seleccionado
        if (value === pageLength) {
            option.attr('selected', 'selected');
        }

        pageSizeSelector.append(option);
    }


});

var setValueAtSameRFC = function (type, rfcs, value) {
    //processes
    //responsable
    //reference
    //observations|

    var rfcsLen = Object.keys(rfcs).length;

    if (rfcsLen > 0) {
        $("#data-table").DataTable().rows({ filter: "applied" }).every(function () {
            var localRow = this;
            var receipt = localRow.data();
            //Change internal data

            if (loadType.indexOf("emitido") > 0) {
                if (rfcs.indexOf(receipt.RFCReceptor) >= 0)
                    receipt[type] = value;
            } else if (loadType.indexOf('recibido') > 0) {
                if (rfcs.indexOf(receipt.RFC) >= 0)
                    receipt[type] = value;
            }

            if (localRow != null)
                localRow.child(formatDetailRow(localRow.data()));//.draw();
        });


    }
};

//Function that selects all the record, even when they not visible
var selectAllRecords = function () {
    var rows = $('#data-Table').dataTable().fnGetNodes();

    $.each($("tbody .c-checkbox input[type=checkbox]"), function (index, row) {
        $(this).prop("checked", true);
    });

    $("#idGeneralActions", ".btn-procesos, .btn-responsables, .btn-referencias, .btn-observaciones").removeAttr("disabled");
};

 

var showExportToExcelChunck = function () {

    if ($("#data-table").DataTable().rows().count() <= 0) {
        bootbox.dialog({
            message: "Por favor seleccione al menos un registro",
            title: "Error",
            onEscape: function () { },
            animate: false,
            buttons: {
                success: {
                    label: "Aceptar",
                    className: "btn-primary",
                    callback: function () {
                    }
                },

            }
        });
        return false;
    }

    $(document).unbind("shown.bs.modal");

    $(document).on("shown.bs.modal", function (ev) { $("div .modal-footer .btnExportToExcelChunk").attr("id", "ExportMetadataToExcelChunk"); });

    bootbox.dialog({
        id: "exportDialog",
        animate: false,
        onEscape: function () { },
        message: ("<div class=\"row\">" +
            "<br/><br/>" +
            "<div class=\"col-1\"> </div>" +
            "<div class=\"col-11\">" +
            "<p>Exportar a Excel</p>" +
            "<p class=\"TextModalConfi\">" +
            "¿Desea exportar a Excel los registros seleccionados?" +
            "</p ></div ></div > "),
        buttons: {
            cancel: {
                label: "Cancelar",
                className: "btn-Acciones",
                callback: function () { }
            },
            btnExport: {
                id: "btnExport", name: "btnExport", label: "Exportar", className: "btn-company btnExportToExcelChunk",
                callback: function () {
                }
            }
        }
    });
};

var hideExportToExcelChunck = function () {
    $("#exportDialog").hide();
    bootbox.hideAll();
    //loadingPanel(true, "Exportando registros seleccionados. Espere un momento.");
}

//Show about dialog clasic
var showExport = function (opt) {
    var table = $("#data-table").DataTable();
    var checkedRows = table.rows({ search: 'applied', order: 'applied' }).nodes().toArray().filter(function (row) {
        return $(row).find('input[type="checkbox"]:checked').length > 0;
    });

    // Extract data from checked rows
    var checkedData = checkedRows.map(function (row) {
        var rowData = table.row(row).data();
        return rowData;
    });

    /*let dt = $('#data-table').DataTable().rows({ search: 'applied', order: 'applied' }).data().toArray();*/
    let dt = checkedData;
    if ($("#data-table").DataTable().rows().count() <= 0) {
        bootbox.dialog({
            message: "Por favor seleccione al menos un registro",
            title: "Error",
            onEscape: function () { },
            animate: false,
            buttons: {
                success: {
                    label: "Aceptar",
                    className: "btn-primary",
                    callback: function () {

                    }
                },

            }
        });
        return false;
    }
    bootbox.dialog({
        id: "exportDialog",
        animate: false,
        onEscape: function () { },
        message: ("<div class=\"row\">" +
            "<br/><br/>" +
            "<div class=\"col-1\"> </div>" +
            "<div class=\"col-11\">" +
            "<p>Exportar a Excel</p>" +
            "<p class=\"TextModalConfi\">" +
            (opt === 1 ? "¿Desea exportar a Excel los registros seleccionados?" : "¿Desea exportar a Excel todos los registros?") +
            "</p ></div ></div > "),
        buttons: {
            cancel: {
                label: "Cancelar",
                className: "btn-Acciones",
                callback: function () {

                }
            },
            btnExport: {
                id: "btnExport", name: "btnExport", label: "Exportar", className: "btn-company",
                callback: function () {
                    loadingPanel(true, "Exportando registros seleccionados");
                    setTimeout(function () {

                        chrome.webview.postMessage(JSON.stringify({
                            type: "Export",
                            payload: getFiltersData()
                        }));


                    }, 100); // Pequeño delay para dejar que se renderice el loader
                }
            }
        }
    });
};

var cleanMessage = function () {
    var data = $("#data-table").DataTable().rows().data();
    if (data.length === 0) {
        $('#lbl_Doctos_Exists').text('');
    }
}

 


function initializeChecks() {
    isSelectAll = true;
    uuidList = [];
    datatable.rows().every(function () {
        var row = $(this.node());
        var checkbox = row.find('input[type="checkbox"]');
        var rowData = this.data();

        checkbox.prop('checked', isSelectAll);

        rowData.Checked = isSelectAll;
    });

    datatable.draw(false);
}

function initializeDatatableDetails(data, id, TotalRecords, pageSize) {
    try {
        if (!$.fn.DataTable) return;

        tabledetailsobj.clear();
        var dataobj = (typeof data === "string") ? JSON.parse(data) : data;
        fillDetails(tabledetailsobj, dataobj, id);

        if (typeof detailPageNumber === "undefined" || detailPageNumber < 1) {
            detailPageNumber = 1;
        }

        var totalPages = Math.max(Math.ceil(TotalRecords / pageSize), 1);

        if (detailPageNumber > totalPages) {
            detailPageNumber = 1;
            $('#checkAllId').prop('checked', true).trigger('change');
            notifyFiltersChange();
        }

        var pageNumbersContainer = $("#pageNumbers_detailTable");
        pageNumbersContainer.empty();

        // Agregamos o quitamos la clase 'disabled' en lugar de usar prop('disabled')
        if (detailPageNumber <= 1) {
            $("#detailPreviousPage").addClass("disabled");
        } else {
            $("#detailPreviousPage").removeClass("disabled");
        }

        if (detailPageNumber >= totalPages) {
            $("#detailNextPage").addClass("disabled");
        } else {
            $("#detailNextPage").removeClass("disabled");
        }

        // Primera página
        if (detailPageNumber > 4) {
            var firstPageButton = $('<span>', {
                class: 'page-button detailTable_button',
                text: 1,
                id: 'page-button-1'
            });

            pageNumbersContainer.append(firstPageButton);
            pageNumbersContainer.append('<span>...</span>');
        }

        var pagesVisible = 4;
        var startPage = Math.max(detailPageNumber - Math.floor(pagesVisible / 2), 1);
        var endPage = Math.min(startPage + pagesVisible - 1, totalPages);

        if (endPage - startPage < pagesVisible - 1) {
            startPage = Math.max(endPage - pagesVisible + 1, 1);
        }

        // Botones de paginación intermedios
        for (var i = startPage; i <= endPage; i++) {
            var activeClass = (i === detailPageNumber) ? ' active' : '';

            var pageButton = $('<span>', {
                class: 'page-button detailTable_button' + activeClass,
                text: i,
                id: 'page-button-' + i
            });

            pageNumbersContainer.append(pageButton);
        }

        // Última página
        if (endPage < totalPages - 1) {
            pageNumbersContainer.append('<span>...</span>');

            var lastPageButton = $('<span>', {
                class: 'page-button detailTable_button',
                text: totalPages,
                id: 'page-button-' + totalPages
            });

            pageNumbersContainer.append(lastPageButton);
        }


        // Eventos de paginación
        $(".detailTable_button").on("click", function () {
            var page = parseInt($(this).text(), 10);
            detailPageNumber = page;
            notifyFiltersChange();

        });

        $("#detailPreviousPage").off("click").on("click", function () {
            if (detailPageNumber > 1) {
                detailPageNumber--;
                notifyFiltersChange();
            }
        });

        $("#detailNextPage").off("click").on("click", function () {
            if (detailPageNumber < totalPages) {
                detailPageNumber++;
                notifyFiltersChange();
            }
        });

        var showingStart = 0, showingEnd = 0, message = "Mostrando registros del 0 al 0 de un total de 0 registros.";

        if (typeof detailPageNumber === "number" && typeof pageSize === "number" && typeof TotalRecords === "number" && TotalRecords != 0) {

            showingStart = ((detailPageNumber - 1) * pageSize) + 1;
            showingEnd = Math.min(detailPageNumber * pageSize, TotalRecords);
            message = "Mostrando registros del " + showingStart + " al " + showingEnd + " de un total de " + TotalRecords + " registros.";
        }

        $("#message_detailTable").text(message);
    } catch (e) {
        alert("Error en initializeDatatableDetails: " + e.message);
    }
}
function getFiltersData() {
    var tabletop = $('#tabletop').DataTable();

    var rowData = null;
    var $highlightedRow = $('#tabletop tbody tr.highlight');
    if ($highlightedRow.length > 0) {
        rowData = tabletop.row($highlightedRow).data();
    }

    return {
        ID: rowData ? rowData.ID : null,
        filterText: $("#globalFilter").val(),
        fechaInicio: $("#date-range").val(),
        fechaFin: $("#date-range").val(),
        tipoDocumento: $("#dropdownFilter").val(),
        pageSize: $("#pageSizeSelector_detailTable").val() || 100,
        pageNumber: detailPageNumber || 1,
        sortField: columndetailTable || 1,
        sortOrder: isAscendingdetailTable,
        isSelectAll: isSelectAll,
        uuidExceptions: uuidList
    };
}

function notifyFiltersChange() {
    chrome.webview.postMessage(JSON.stringify({
        type: "Filtros",
        payload: getFiltersData()
    }));
}

$(document).ready(function () {
    let typingTimer;
    const doneTypingInterval = 500; // Tiempo de espera después de que el usuario deje de escribir



    // Evento para globalFilter con debounce
    $("#globalFilter").on("keyup", function () {
        clearTimeout(typingTimer);
        typingTimer = setTimeout(notifyFiltersChange, doneTypingInterval);
    });

    // Eventos para los demás filtros
    $("#dropdownFilter, #pageSizeSelector_detailTable").on("change", notifyFiltersChange);


});



$('#data-table tbody').on('click', 'tr td.details-control', function () {
    const rowSelect = $('#data-table').DataTable().row(this);
    let rownode = rowSelect.node();
    const rowData = $('#data-table').DataTable().row(this).data();

    if (rowSelect.child.isShown()) {
        $(rownode).removeClass('details')
        rowSelect.child.hide();
    }
    else {
        $(rownode).addClass('details');
        rowSelect.child(formatDetailRow(rowData)).show();
    }
}
);
//******************************************************* end data - table *********************************************************** */

$('#searchInputCompanies').on('keyup input', function () {

    tablecompaniesobj.search(this.value).draw();
});


function addRowToTable(data) {
    $('#passwordInputconfirm').val('');
    $('#confirmModal').modal('hide');
    $('#companyPropsModal').modal('hide');
    $('#companyListModal').modal('show');

    // Guardar estado actual antes de cualquier cambio
    var currentState = {
        page: tablecompaniesobj.page.info().page,
        search: $('#searchInputCompanies').val(),
        order: tablecompaniesobj.order(),
        length: tablecompaniesobj.page.len(),
        totalRecords: tablecompaniesobj.rows().count()
    };

    // Limpiar búsqueda si existe (opcional, depende de tu necesidad)
    $('#searchInputCompanies').val('');
    tablecompaniesobj.search("");

    // Procesar los datos
    var dataobj = (typeof data === "string") ? JSON.parse(data) : data;
    var counter = dataobj.length;

    // Determinar si es actualización o nuevos registros
    var existingIds = new Set();
    tablecompaniesobj.rows().every(function () {
        var rowData = this.data();
        if (rowData.id || rowData.CompanyGuid || rowData.Id) {
            // Usar el identificador que tenga tu tabla
            var id = rowData.id || rowData.CompanyGuid || rowData.Id;
            existingIds.add(id.toString());
        }
    });

    // Verificar si hay IDs nuevos
    var hasNewRecords = false;
    $.each(dataobj, function (index, item) {
        var itemId = item.id || item.CompanyGuid || item.Id;
        if (itemId && !existingIds.has(itemId.toString())) {
            hasNewRecords = true;
            return false; // break
        }
    });

    // Limpiar tabla
    tablecompaniesobj.clear();

    // Agregar todas las filas
    $.each(dataobj, function (index, row) {
        var rowNode = tablecompaniesobj.row.add(row).node();
        $(rowNode).addClass('deferred');
    });

    $("[id='totalComp']").text(counter);

    // Decidir comportamiento basado en si hay registros nuevos
    if (hasNewRecords) {
        // Si hay registros nuevos, ir a la PRIMERA página
        tablecompaniesobj.draw();
    
    } else {
        // Si es solo actualización, mantener la página actual
        tablecompaniesobj.draw(false);

        // Intentar restaurar la página original si es válida
        if (currentState.page < tablecompaniesobj.page.info().pages) {
            tablecompaniesobj.page(currentState.page).draw(false);
        }
    }

    // Restaurar ordenamiento si se desea
    if (currentState.order && currentState.order.length) {
        tablecompaniesobj.order(currentState.order).draw(false);
    }
}

function evCompaniestUpdate(document) {
    try {


        var jDoc = (typeof document === "string") ? JSON.parse(document) : document;

        tablecompaniesobj.rows().every(function (rowIdx) {
            var d = this.data();
            if (d.Empresas == jDoc.CompanyGuid) {
                d.Comprobantes = jDoc.lastRequestOnProcess;
                tablecompaniesobj.row(rowIdx).data(d).draw(false);
            }
        });
    } catch (e) {
        alert("Error al actualizar tabla de empresas: " + e.message);
    }

}
function addRowToDataTable(jsonString) {

    try {
        var data = (typeof jsonString === "string") ? JSON.parse(jsonString) : jsonString;

        // Get a reference to the DataTable instance
        let table = $('#tabletop').DataTable(); // Replace 'example' with your table ID

        var ids = [];

        // Iterate over each row in the table
        table.rows().every(function () {
            var rowData = this.data();
            var id = rowData.ID;
            ids.push(id);
        });

        if (ids.indexOf(data.ID) < 0) {
            table.row.add(data).draw();
            table.order([[0, 'desc']]).draw(false);
            trySelectFirstRow();
        }
    } catch (e) {
        alert("Error en addRowToDataTable: " + e.message);
    }
}
function evTabletoptUpdate(document) {

    var jDoc = (typeof document === "string") ? JSON.parse(document) : document;
    tabletopobj.rows().every(function (rowIdx) {
        var d = this.data();
        if (d.Empresas == jDoc.CompanyGuid) {
            d.Comprobantes = jDoc.lastRequestOnProcess;
            tablecompaniesobj.row(rowIdx).data(d).draw(false);

        }
    });

}

function ClearDetails(optionalParameter) {

    if (tabledetailsobj) {

        tabledetailsobj.clear().draw();

        $("#message_detailTable").text("Mostrando registros del 0 al 0 de un total de 0 registros.");

        var pageNumbersContainer = $("#pageNumbers_detailTable");
        pageNumbersContainer.empty();

        $("#detailPreviousPage").addClass("disabled");
        $("#detailNextPage").addClass("disabled");

        var firstPageButton = $('<span>', {
            class: 'page-button detailTable_button active',
            text: 1,
            id: 'page-button-1'
        });

        pageNumbersContainer.append(firstPageButton);
    }

    $('#tabletop tbody tr').removeClass('highlight');

}

function cleantable() {
    $("#data-table").on('draw.dt', function () {
        $('#data-table .dataTables_empty').html('Por favor dar doble clic sobre la descarga para ver detalles.');
    });
    if (tabledetailsobj) {
        tabledetailsobj.clear().draw();
    }
}


function initializeDatatable(data, ignoretrySelectFirstRow = false) {

    try {
        var tabletop = $('#tabletop').DataTable();

        var rowData = null;
        var $highlightedRow = $('#tabletop tbody tr.highlight');
        if ($highlightedRow.length > 0) {
            rowData = tabletop.row($highlightedRow).data();
        }

        $("#data-table").on('draw.dt', function () {
            $('#data-table .dataTables_empty').html('Ningún dato disponible en esta tabla.');
        });

        ClearDetails();
        tabletopobj.clear().draw();

        var dataobj = (typeof data === "string") ? JSON.parse(data) : data;
        $.each(dataobj, function (index, row) {
            var rowNode = tabletopobj.row.add(row).node();
            $(rowNode).addClass('deferred');
        });

        tabletopobj.rows(dataobj).draw();
        tabletopobj.order([[0, 'desc']]).draw(false);

        $('#tabletop').on('click', '.cancelRequest-button:not(.disabled)', function () {
            var id = $(this).data('id');
            showconfirmmodalCancel(id);
        });

        // Intentar la primera llamada
        if (ignoretrySelectFirstRow) {

            let id_active = rowData ? rowData.ID : null

            if (id_active != null) HighLightTable(id_active);
        }
        else {
            trySelectFirstRow();
        }
           
    }
    catch (e) {
        alert("Error en initializeDatatable: " + e.message);
    }
}

// Función para manejar el intento de llamada a external
function trySelectFirstRow() {

    var $firstRow = $(tabletopobj.table().body()).find('tr:first');
    var rowData = tabletopobj.row($firstRow).data();

    if (rowData && rowData.ID) {

        HighLightTable(rowData.ID);
        detailPageNumber = 1;

        // Short-circuit: si no tiene metadata, enviar flag para evitar roundtrip
        var hasMetadata = !!rowData.Tiene_Metadata;
        chrome.webview.postMessage(JSON.stringify({
            type: "WebViewMessage",
            payload: {
                providerType: "BaseLoadListService",
                action: "select",
                documentType: rowData.ID,
                hasMetadata: hasMetadata
            }
        }));
    }
}

function HighLightTable(id) {
    var tabletop = $('#tabletop').DataTable();

    // Validar ID activo para restablecer los uuid marcados y/o desmarcados 
    var rowActive = null;
    var $highlightedRow = $('#tabletop tbody tr.highlight');
    if ($highlightedRow.length > 0) rowActive = tabletop.row($highlightedRow).data();

    var rowIDActive = rowActive ? rowActive.ID : null;

    if (rowIDActive != null) {
        //alert(rowIDActive + " VS " + id);
        if (rowIDActive != id) {
            setTimeout(function () {
                $('#checkAllId').prop('checked', true).trigger('change');
                $('#checkAllId').triggerHandler('change'); 
            }, 300);
        }
    }

    // Remover highlight
    $('#tabletop tbody tr').removeClass('highlight');

    // Add the "highlighted" class to rows where the ID is greater than 1
    tabletop.rows().every(function () {
        var rowData = this.data();

        // Example: Add a class to rows where the ID is greater than 1
        if (rowData["ID"] == id) {
            // Select the corresponding tr element and add the class
            $(this.node()).addClass('highlight');
        }
        else {
            $(this.node()).removeClass('highlight');
        }
    });

}

function fillDetails(table, data, id) {
    setTimeout(
        function () {
            table.clear();
            table.rows.add(data).draw(false);
            //table.draw();

            HighLightTable(id);
        }, 100);
}


function evUpdateDownloadRecord(download) {

    try {
        var jDownload = (typeof download === "string") ? JSON.parse(download) : download;
        var table = $('#tabletop').DataTable();
        var rowIndex = -1;
        var existingTs = 0;

        table.rows().every(function (rowIdx) {
            var datos = this.data();
            if (datos.ID === jDownload.ID) {
                datos.Cancel = jDownload.Cancel;
                existingTs = datos.Ts || 0;
                rowIndex = rowIdx;
                return false; // Break the loop
            }
            return true;
        });

        // Descartar updates obsoletos: si la fila existente tiene Ts mayor, ignorar
        if (rowIndex !== -1 && jDownload.Ts && existingTs && jDownload.Ts < existingTs)
            return;

        if (rowIndex !== -1) {
            table.row(rowIndex).data(jDownload).draw(false);
        } else {
            addRowToDataTable(download);
        }


    } catch (e) {
        alert("Error en evUpdateDownloadRecord: " + e.message);
    }
}
function evDocumentUpdate(document, descarga) {

    try {
        var jDoc = (typeof document === "string") ? JSON.parse(document) : document;
        var dataTable = $('#data-table').DataTable();

        dataTable.rows().every(function () {
            var d = this.data();
            if (d.UUID == jDoc.Uuid) {
                d.Descargado = jDoc.EsEmitidos
                    ? descarga
                    : (jDoc.Fecha_Cancelacion != null ? "NO DISPONIBLE" : descarga);
                this.invalidate(); // Marca la fila como actualizada
            }
        });


    } catch (e) {
        alert("Error en evDocumentUpdate: " + e.message);
    }
}
function evDownloadError(download, package, message) {

    var jDownload = (typeof download === "string") ? JSON.parse(download) : download;
    var jPackage = (typeof package === "string") ? JSON.parse(package) : package;
    var table = $('#tabletop').DataTable();
    var rId = undefined;
    table.rows().every(function () {
        var d = this.data();
        if (d.ID == jDownload.Id) {
            d.Status = jDownload.EstatusDescarga;
            d.Mensaje = message;
            this.invalidate();
            rId = d.IDM
        }
    });

    table.draw();
    if (rId != undefined) {
        $("#Rw-" + rId).click();
    }
}

function evUpdateCancel() {

    var dataTable = $('#data-table').DataTable();
    if (dataTable.rows().count() <= 0) {
        return false;
    }
    dataTable.rows().every(function () {
        var d = this.data();
        if (d.Descargado != "NO DISPONIBLE") {
            d.Descargado = "INTERRUMPIDO"
            this.invalidate();
        }
    });
    dataTable.draw();
}




//Custom column data type
jQuery.extend(jQuery.fn.dataTableExt.oSort, {
    "date-custom-pre": function (a) {

        if (!a || a === '' || a === 'null' || a === null)
            return Number.NEGATIVE_INFINITY;

        var dateParts = a.split(' ');
        var date = dateParts[0].split('/');
        var time = dateParts[1].split(':');
        return new Date(date[2], date[1] - 1, date[0], time[0], time[1]).getTime();
    },

    "date-custom-asc": function (a, b) {
        return a - b;
    },

    "date-custom-desc": function (a, b) {
        return b - a;
    }
});


jQuery.extend(jQuery.fn.dataTableExt.oSort, {
    "daterange-custom-pre": function (a) {
        var dateRanges = a.split(' - ');
        var startDateParts = dateRanges[0].split('/');
        var endDateParts = dateRanges[1].split('/');

        var startDate = new Date(startDateParts[2], startDateParts[1] - 1, startDateParts[0]);
        var endDate = new Date(endDateParts[2], endDateParts[1] - 1, endDateParts[0]);

        return startDate.getTime();
    },

    "daterange-custom-asc": function (a, b) {
        return a - b;
    },

    "daterange-custom-desc": function (a, b) {
        return b - a;
    }
});

// end of Custom column data type
function parseDate(dateString) {
    var parts = dateString.split(" ");
    var dateParts = parts[0].split("/");
    var timeParts = parts[1].split(":");
    return new Date(dateParts[2], dateParts[1] - 1, dateParts[0], timeParts[0], timeParts[1]);
}
function changeDateFormat(datestr) {
    const parts = datestr.split('/');
    const day = parts[0];
    const month = parts[1];
    const year = parts[2];
    return new Date(month + "/" + day + "/" + year)
}

function handleClick(cbForm) {
    var tr = $(cbForm).closest('tr');
    var row = $("#data-table").DataTable().row(tr);

    var data = row.data();
    data.Checked = cbForm.checked;
    addExtraParameter(data.UUID, data.Checked);
}

function addExtraParameter(Uuid, Checked) {
    if (Uuid == null) return;

    const uuidListIndex = uuidList.indexOf(Uuid);

    if (isSelectAll) {
        // Todos están seleccionados, guardamos los que el usuario quita
        if (!Checked) {
            if (uuidListIndex < 0) {
                uuidList.push(Uuid);
            }
        }
        else {
            uuidList.splice(uuidListIndex, 1);
        }
    } else {
        // Nada está seleccionado, guardamos los que el usuario agrega
        if (Checked) {
            if (uuidListIndex < 0) {
                uuidList.push(Uuid);
            }
        }
        else {
            uuidList.splice(uuidListIndex, 1);
        }
    }

}

function getUuids() {
    if (uuidList && uuidList.length > 0)
        return JSON.stringify(uuidList);
    else
        return "";
}

function extraParameterUpdate(document, NuuidList) {

    var Jdoc = (typeof document === "string") ? JSON.parse(document) : document;

    var dataTable = $('#data-table').DataTable();
    dataTable.rows().every(function () {
        var d = this.data();
        if (NuuidList.indexOf(d.UUID) >= 0) {
            d.Reference = Jdoc.Referencia;
            d.Observations = Jdoc.Observaciones;
            if (d.Origen === "Recibido") {
                d.Process = Jdoc.Proceso;
                d.Responsable = Jdoc.Responsable;
            }
        }
    });
    // After drawing the table, show the updated values 
    dataTable.rows().every(function () {
        var d = this.data();
        if (NuuidList.indexOf(d.UUID) >= 0) {
            $(this.node()).addClass('details');
            var childRow = this.child(formatDetailRow(d));
            childRow.show();
        }
    });
}




function CheckAllTable() {

    //var checkbox = document.getElementById("checkAllId");
    //var datatable = $('#data-table').DataTable();

    //if (datatable.rows().count() === 0) return;
    //isSelectAll = checkbox.checked;

    //datatable.rows().every(function () {
    //    var checkbox = $(this.node()).find('input[type="checkbox"]');
    //    checkbox.prop('checked', isSelectAll);
    //});

    //datatable.rows().every(function () {
    //    var row = this.data();
    //    addExtraParameter(row.UUID, checkbox.checked);
    //})
};


function initializeRquestFlag(booleanValue) {
    let element = document.getElementById('initFlag');

    if (!element) {
        let invisibleTextbox = $('<input>').attr({
            type: 'text',
            style: '',
            id: 'initFlag'
        }).val(booleanValue);
        $('body').append(invisibleTextbox);
        element = document.getElementById('initFlag');
    }

    element.textContent = booleanValue.toString();
}



function formatDetailRow(d) {
    const html = '<div class="row" style="width:99%;">' +
        '<div class="col-3 px-5">' +
        '<p class="text-purple m-0 _600">Proceso</p>' +
        '<small class="text-muted">' + (d.Process == null || d.Process == "" ? "- - -" : d.Process) + '</small>' +
        '</div>' +
        '<div class="col-3 px-5">' +
        '<p class="text-purple m-0 _600">Responsable</p>' +
        '<small class="text-muted">' + (d.Responsable == null || d.Responsable == "" ? "- - -" : d.Responsable) + '</small>' +
        '</div>' +
        '<div class="col-3 px-5">' +
        '<p class="text-purple m-0 _600">Referencia</p>' +
        '<small class="text-muted">' + (d.Reference == null || d.Reference == "" ? "- - -" : d.Reference) + '</small>' +
        '</div>' +
        '<div class="col-3 px-5">' +
        '<p class="text-purple m-0 _600">Observaciones</p>' +
        '<small class="text-muted">' + (d.Observations == null || d.Observations == "" ? "- - -" : d.Observations) + '</small>' +
        '</div>' +
        '</div>';

    return html;
}


$('#clear-filters').on('click', function () {
    tabledetailsobj.search('').draw();

    // Additionally clear individual column filters (if needed)
    tabledetailsobj.columns().search('').draw();
});

$('#dropdownFilterCompanies').on('change', function () {
    tablecompaniesobj.draw();


});

$.fn.dataTable.ext.search.push(
    function (settings, data, dataIndex) {
        if (settings.nTable.id !== 'companyTable') {
            return true;
        }
        // Get the selected value from the select element
        var selectedValue = $('#dropdownFilterCompanies').val();

        // Get the checkbox status for the row
        var isChecked = $(tablecompaniesobj.row(dataIndex).node()).find('.custom-control-input').prop('checked');

        var rowData = tablecompaniesobj.row(dataIndex).data();
        var FielActiva = rowData.FielActiva;

        // Check the selected value and filter accordingly
        if (selectedValue === 'active') {
            return (isChecked && FielActiva)
        }
        else if (selectedValue === 'checked') {
            // Return true to include the row in the filtered results if the checkbox is checked
            return isChecked;
        } else if (selectedValue === 'unchecked') {
            // Return true to include the row in the filtered results if the checkbox is unchecked
            return !isChecked;
        } else if (selectedValue === 'Empresas con FIEL') {
            // Return true to include the row in the filtered results if the 'FielActiva' value is 'true'
            return FielActiva;
        } else if (selectedValue === 'Empresas sin FIEL') {
            // Return true to include the row in the filtered results if the 'FielActiva' value is 'false'
            return !FielActiva;
        } else {
            // Return true to include all rows if the selected value is not 'checked' or 'unchecked'
            return true;
        }
    }
);

function filterTableByCheckbox(status) {
    var table = $('#myDataTable').DataTable();

    table.column(4).search("").draw(); // Clear any previous filters

    if (status !== "") {
        table.column(4).search(
            'div:has(input[type="checkbox"]:checked)',
            true,
            false
        ).draw();
    }
}


function setInputFile(fieldId, filepath, rfc, company) {

    const fieldToUpdate = $("#" + fieldId);
    const rfcField = $("#rfc");
    const companyField = $("#companyName")
    const razonsocialField = $("#razonsocial")

    if (fieldToUpdate) {
        fieldToUpdate.val(filepath);
        clearFieldError(fieldToUpdate);
    }

    if (rfc.length > 0 && rfcField) {
        rfcField.val(rfc);
    }

    if (company && company.length > 0 && $('#configsection').css('display') == 'none') {
        companyField.val(company);
        clearFieldError(companyField);
    }
    if (company && company.length > 0) {
        razonsocialField.val(company);
    }
}
function setPathSave(path) {
    const folderpath = $("#filesavepath");
    folderpath.val(path);
    clearFieldError(folderpath);
}

function showmodal() {
    localStorage.setItem("fromRoute", "MainWindow");
    $('#myModal').modal('handleUpdate');
    $('#companyPropsModal').modal('show');

}

function ADDCompanies(companies, creationFlag) {


    var isCreating = creationFlag === true || creationFlag === 'true';


    var numberOfOptions = $('#companyADD option').length; // Replace with your actual ID
    if (!isCreating) {

        var element = $('#configsection');
        element.css('display', '');

        $("#companyConfiguracion").css('display', '');
        $("#companyCreation").css('display', 'none');
        const spans = document.querySelectorAll(".span-required");
        for (let i = 0; i < spans.length; i++) {
            spans[i].classList.add('hidden');
        }
    }

    var optionsData = (typeof companies === "string") ? JSON.parse(companies) : companies;
    var selectElement = document.getElementById("companyADD");
    if (numberOfOptions == 0) {
        $.each(optionsData, function (key, value) {
            var optionElement = document.createElement("option");
            optionElement.value = value.Id;
            optionElement.text = value.Name;
            selectElement.add(optionElement);
        });
    }
    companySelection = $("#companyADD option:selected").text();
}


var selectElement = document.getElementById('companyADD');
var inputElement = document.getElementById('guidADD');

selectElement.addEventListener('change', function () {

    // Set the value of the input to the selected option's value
    if (selectElement.value == "0") {
        inputElement.value = "";
        return
    }
    inputElement.value = selectElement.value;

});

function emptyFieldError(cert, key, password, companyName, filesavepath, checkrecibidos, checkemitidos) {

    if (!cert || cert.length < 1) {
        $("#cer").addClass("is-invalid").removeClass("is-expired");
        $("#cer").closest(".input-group").next(".invalid-feedback").show();
        $("#cer").closest(".input-group").nextAll(".expired-feedback , .is-fiel-config-feedback, .is-CerAndKey-valid-feedback").hide();
    } else {
        $("#cer").removeClass("is-invalid is-expired");
        $("#cer").closest(".input-group").nextAll(".invalid-feedback, .expired-feedback  , .is-fiel-config-feedback, .is-CerAndKey-valid-feedback").hide();
    }

    if (!key || key.length < 1) {
        $("#key").removeClass("is-invalid is-expired");
        $("#key").addClass("is-invalid");
        $("#key").closest(".input-group").next(".is-fiel-config-feedback").hide();
        $("#key").closest(".input-group").nextAll(".invalid-feedback ").show();
    } else {
        $("#key").removeClass("is-invalid is-expired");
        $("#key").closest(".input-group").nextAll(".invalid-feedback, .is-fiel-config-feedback").hide();
    }

    if (!password || password.length < 1) {
        $("#password").addClass("is-invalid").removeClass("is-expired");
        $("#password").closest(".input-group").next(".invalid-feedback").show();
        $("#password").closest(".input-group").nextAll(".password-feedback, .isfiel-feedback").hide();
    } else {
        $("#password").removeClass("is-invalid is-expired");
        $("#password").closest(".input-group").nextAll(".invalid-feedback, .password-feedback, .isfiel-feedback").hide();
    }

    if (!companyName || companyName.length < 1) {
        $("#companyName").addClass("is-invalid").removeClass("is-expired");
        $("#companyName").closest(".input-group").next(".invalid-feedback").show();
    } else {
        $("#companyName").removeClass("is-invalid");
        $("#companyName").closest(".input-group").nextAll(".invalid-feedback, .duped-feedback").hide();
    }

    if (!filesavepath || filesavepath.length < 1) {
        $("#filesavepath").addClass("is-invalid");
        $("#filesavepath").closest(".input-group").next(".invalid-feedback").show();
    }

    if (checkemitidos == false && checkrecibidos == false) {
        $("#checks").next(".invalid-feedback").show();
    }
}
function loadCompanie(params) {

    var companiedata = (typeof params === "string") ? JSON.parse(params) : params;

    $("#cer").val(companiedata.cerpath);
    $("#key").val(companiedata.keypath);

    $("#password").val(companiedata.password);

    if (companiedata.password && companiedata.password !== "") {
        $("#password").css({
            "border-top-right-radius": "10px",
            "border-bottom-right-radius": "10px"
        });
        $("#btnshowPass").hide();
        $("#showPass").css('pointer-events', 'none');
    }

    $("#rfc").val(companiedata.RFC);
    $("#companyName").val(companiedata.companiename);
    $("#razonsocial").val(companiedata.razonsocial);

    $("#checkautomaticdownload").prop("checked", companiedata.activacionautomatico);
    $("#checkrecibidos").prop("checked", companiedata.esrecibido);
    $("#checkemitidos").prop("checked", companiedata.esemitidos);

    $("#filesavepath").val(companiedata.cfdipath);
    if (companiedata.addcompanie != "") {
        $("#companyADD").val(companiedata.addcompanie);
        $("#guidADD").val(companiedata.addcompanie);

    }
    else {
        $("#companyADD").val(new UUID.toString());
    }
}

function checkedAnyCheckboxForm(nameInput, checked) {
    if ($(nameInput).length > 0) {
        $(nameInput).prop("checked", checked);
    }
}

function checkerror(validation) {
    $("#checks").next(".invalid-feedback").hide();
    $("#filesavepath").removeClass("is-invalid");
    $("#filesavepath").closest(".input-group").next(".invalid-feedback").hide();

}
function expirationCert() {
    $("#cer").removeClass("is-invalid");
    $("#cer").addClass("is-expired");
    $("#cer").closest(".input-group").next(".invalid-feedback").hide();
    $("#cer").closest(".input-group").next(".isfiel-feedback").hide();
    $("#cer").closest(".input-group").next(".is-fiel-config-feedback").hide();
    $("#cer").closest(".input-group").next(".is-CerAndKey-valid-feedback").hide();
    $("#cer").closest(".input-group").nextAll(".expired-feedback").show();
}

function notMachingKeyAndCerError() {
    $("#cer").removeClass("is-invalid");
    $("#cer").addClass("is-expired");
    $("#cer").closest(".input-group").next(".invalid-feedback").hide();
    $("#cer").closest(".input-group").next(".isfiel-feedback").hide();
    $("#cer").closest(".input-group").next(".is-fiel-config-feedback").hide();
    $("#cer").closest(".input-group").next(".expired-feedback").hide();
    $("#cer").closest(".input-group").nextAll(".is-CerAndKey-valid-feedback").show();
}

function passwordError() {
    $("#pasword").removeClass("is-invalid");
    $("#password").addClass("is-expired");
    $("#pasword").next(".invalid-feedback").hide();
    $("#password").closest(".input-group").nextAll(".password-feedback").show();

}

function dupedError() {
    $("#companyName").removeClass("is-invalid");
    $("#companyName").addClass("is-expired");
    $("#companyName").closest(".input-group").next(".invalid-feedback").hide();
    $("#companyName").closest(".input-group").nextAll(".duped-feedback").show();
}
function notFielError() {
    $("#cer").removeClass("is-invalid");
    $("#cer").addClass("is-expired");
    $("#cer").closest(".input-group").next(".invalid-feedback").hide();
    $("#cer").closest(".input-group").next(".password-feedback").hide();
    $("#cer").closest(".input-group").next("..is-fiel-config-feedback").hide();
    $("#cer").closest(".input-group").next(".is-CerAndKey-valid-feedback").hide();
    $("#cer").closest(".input-group").nextAll(".isfiel-feedback").show();
}

function disableControls() {
    $("#mnuManagerrfc").addClass("disabled");
    $("#mnuDescargar").addClass("disabled");
    $("#mnuCancelados").addClass("disabled");
    $("#mnuvisor").addClass("disabled");
    tabletopobj.clear().draw();
    tabledetailsobj.clear().draw();
}

function showError(message) {
    $("#errorMessage").text(message);
    $("#errorModal").modal('show');
}

function closeModalConfirm() {
    var state = localStorage.getItem("checkboxvalue");
    var idcheck = localStorage.getItem("checkboxid");
    $('#' + idcheck).prop("checked", state);
    $('#companyListModal').modal('show');
    $("#confirmModal").modal('hide');
}
function closeModalConfirmCancel() {
    $("#confirmModalCancel").modal('hide');
}



function showconfirmmodal(checkbox, guid, nombre, HaveAdd, HaveFiel) {
    try {
        // (1) Normaliza/decodifica valores
        var nombreLimpio = (typeof decodeHtmlEntities === 'function') ? decodeHtmlEntities(nombre) : String(nombre || '');

        // HaveFiel puede ser: true/false, "true"/"false", "1"/"0", 1/0, null/undefined
        var haveFielStr = (HaveFiel == null) ? '' : String(HaveFiel).toLowerCase();
        var isFielActiva = (haveFielStr === 'true' || haveFielStr === '1' || HaveFiel === true || HaveFiel === 1);

        // HaveAdd (DSLID) puede venir null, "", "null"
        var hasAdd = !(HaveAdd == null || HaveAdd === '' || HaveAdd === 'null' || HaveAdd === false);

        // (2) Guarda estado del checkbox
        localStorage.setItem("checkboxvalue", checkbox.checked);
        localStorage.setItem("checkboxid", checkbox.id);

        // (3) Mensajes según ADD
        if (hasAdd) {
            $("#companyguidmodal").html(
                'Esta acción cambiará el estado de la empresa <b>' + nombreLimpio +
                '</b> a "Inactiva", lo que significa que no se agendarán más descargas automáticas y ' +
                'para tener los CFDIs actualizados deberá activarse la empresa de nuevo.'
            );
            $("#confirmtitle").html(
                'La empresa permanecerá activa en el ADD y no se eliminarán los archivos ya descargados. ¿Desea continuar?'
            );
            $("#titleconfirmmodal").text("Desactivar empresa");
        } else {
            $("#companyguidmodal").html(
                'Esta acción eliminará la empresa <b>' + nombreLimpio +
                '</b> y no podrá recuperarla, mas no se eliminarán los archivos ya descargados. ¿Desea continuar?'
            );
            $("#confirmtitle").text("");
            $("#titleconfirmmodal").text("Eliminar empresa");
        }

        // (4) Mostrar/ocultar password por FIEL
        if (isFielActiva) {
            $("#PasswordForm").show();
        } else {
            $("#PasswordForm").hide();
        }

        // (5) Mostrar modal (solo al desactivar) — si quieres mostrar SIEMPRE, quita el if
        if (!checkbox.checked) {
            $('#passwordInputconfirm').val("");
            $('#companyListModal').modal('hide'); // por si hay otro modal abierto
            $("#confirmModal").modal('show');
            $('#passwordInputconfirm').val("").focus();

            var $btn = $('button[name="deletebtnconfirm"]');
            $btn.attr('data-providertype', 'CompaniesDelete');
            $btn.attr('data-documenttype', guid);
            $btn.attr('data-checked', checkbox.checked);
        }

        // Debug opcional:
        // console.log({ guid, nombreLimpio, HaveAdd, hasAdd, HaveFiel, isFielActiva, checked: checkbox.checked });

    } catch (err) {
        // Si algo falla (p.ej. tipos raros), lo verás y no bloquea el resto
        alert('Error en showconfirmmodal: ' + err.message + '\nHaveFiel: ' + JSON.stringify(HaveFiel));
        console.error(err);
    }
}
function showconfirmmodalCancel(id) {
    $("#confirmModalCancel").modal('show');
    $('button[name="deletebtnconfirmCancel"]').attr('data-providertype', 'DisableProcess');
    $('button[name="deletebtnconfirmCancel"]').attr('data-documenttype', id);
}
function clearErrors() {
    $("#cer").removeClass("is-invalid is-expired");
    $("#cer").closest(".input-group").nextAll(".invalid-feedback, .expired-feedback, .is-path-valid-feedback , .is-fiel-config-feedback, .is-CerAndKey-valid-feedback").hide();
    $("#key").removeClass("is-invalid is-expired");
    $("#key").closest(".input-group").nextAll(".invalid-feedback, .is-path-valid-feedback , .is-fiel-config-feedback").hide()
    $("#companyName").removeClass("is-invalid is-expired");
    $("#companyName").closest(".input-group").nextAll(".invalid-feedback, .duped-feedback").hide()
    $("#password").removeClass("is-invalid is-expired");
    $("#password").closest(".input-group").nextAll(".invalid-feedback, .password-feedback, .isfiel-feedback , .is-fiel-config-feedback").hide();
}
function invalidPath() {
    $("#cer").removeClass("is-invalid");
    $("#cer").addClass("is-expired");
    $("#cer").closest(".input-group").next(".expired-feedback, .isfiel-feedback, .invalid-feedback, .is-CerAndKey-valid-feedback").hide();
    $("#cer").closest(".input-group").nextAll(".is-path-valid-feedback").show();
    $("#key").removeClass("is-invalid");
    $("#key").addClass("is-expired");
    $("#key").closest(".input-group").next(".invalid-feedback , .is-fiel-config-feedback").hide();
    $("#key").closest(".input-group").nextAll(".is-path-valid-feedback").show();

}


function requiredSpansShow() {
    const spans = document.querySelectorAll(".span-required");
    for (let i = 0; i < spans.length; i++) {
        spans[i].classList.remove('hidden');
    }
}


function toggleModal() {
    var modal = document.getElementById('companyListModal');

    // Check if the modal is currently visible
    return getComputedStyle(modal).display !== 'none';

}

function closeSnackbar() {
    var x = document.getElementById("snackbar");
    x.className = x.className.replace("show", "");
}
function showsnackbar(text, type, time) {
    // Type values: [success, error, warning, default]

    var x = document.getElementById("snackbar");

    if (time == undefined)
        time = 5000;

    x.className = "show " + (type || "default");

    $("#snacktext").text(text);

    setTimeout(function () {
        x.className = x.className.replace("show", "");
    }, time);
}

function showPass() {

    if ($("#password").attr("type") == "password") {
        $("#password").attr("type", "text");
    } else {
        $("#password").attr("type", "password");
    }
    $("#showPass i").toggle();

}

function clearDropdown() {
    $("#companyADD").empty();
}

function checkstate(id) {
    var miBoton = document.getElementById(id);
    if (miBoton) {
        return !miBoton.disabled;
    }
    return false; // Aseguramos retorno válido siempre
}

function CompanyGuid(guid) {
    localStorage.setItem("CompanyGuid", guid);
}

function getCompanyGuid() {

    let localCompanyGuid = localStorage.getItem("CompanyGuid");

    if (localCompanyGuid == null || localCompanyGuid.trim() === "") localCompanyGuid = "00000000-0000-0000-0000-000000000000"

    return localCompanyGuid;
}

$("#companyADD").on('change', function () {
    if ($("#GuidADD")) {
        companySelection = this.options[this.selectedIndex].text;
    }
});

function getCompanySelecction() {
    if (companySelection.length < 1) {
        companySelection = $("#companyADD option:selected").text();
    }

    return companySelection;
}

function companiesToAdd(data) {
    showADDModal();

    const companies = (typeof data === "string") ? JSON.parse(data) : data;
    const container = $("<div>");
    const selectAllCheckbox = $("#addSelectAll");
    companies.forEach(function (company) {
        const companyDiv = $("<div>").addClass(["row", "justify-content-center", "mb-2"]);

        const checkbox = $("<input>")
            .attr({ type: "checkbox", id: company })
            .addClass("col")
            .appendTo(companyDiv);

        $("<label>")
            .text(company)
            .attr("for", checkbox.attr("id"))
            .addClass(["label-modal", "col"])
            .appendTo(companyDiv);


        if (container.children().length > 10) {
            container.addClass("has-scrollbar");
        }

        checkbox.on("change", function () {
            const hasUnchecked = container.find("input[type='checkbox']").not("#selectAll").is(":not(:checked)");

            if (selectAllCheckbox.prop("checked") !== !hasUnchecked) {
                selectAllCheckbox.prop("checked", !hasUnchecked);
            }
        });
        container.append(companyDiv);
    });

    const modal = $("#addModal");
    $("#companiesToAdd").empty();
    $("#companiesToAdd").append(container);
}

$("#addSelectAll").on("change", function (event) {
    const isChecked = $(this).is(":checked");
    const companyCheckboxes = $("#companiesToAdd input[type='checkbox']")
    if (companyCheckboxes) {
        companyCheckboxes.prop("checked", isChecked);
    }
});

function toggleClass(id) {
    $("#favorite-" + id + "-btn").toggleClass('active');
}



let previousValue = $('#date-range').val();
$(function () {
    $('#date-range').daterangepicker({
        autoUpdateInput: false,
        autoApply: true,
        singleDatePicker: false,
        locale: {
            cancelLabel: 'Borrar',
            format: 'DD/MM/YYYY'
        }
    });

    $('#date-range').on('apply.daterangepicker', function (ev, picker) {
        $(this).val(picker.startDate.format('DD/MM/YYYY') + ' - ' + picker.endDate.format('DD/MM/YYYY'));
        previousValue = $('#date-range').val();
        notifyFiltersChange();
    });

    $('#date-range').on('cancel.daterangepicker', function (ev, picker) {
        $(this).val('');
        previousValue = $('#date-range').val();
        notifyFiltersChange();
    });

    $('#daterange').daterangepicker({
        locale: { cancelLabel: 'Borrar' }
    });
    $('#daterange').daterangepicker({
        locale: { applyLabel: 'Aceptar' }
    });

    $('#daterange').on('cancel.daterangepicker', function (ev, picker) {
        //do something, like clearing an input
        $('#daterange').val('');
        previousValue = $('#date-range').val();
        notifyFiltersChange();
    });

    $('#date-range').on('change paste', function () {

        var currentValue = $(this).val();

        var dateRangePattern = /^\d{1,2}\/\d{1,2}\/\d{4}\s*-\s*\d{1,2}\/\d{1,2}\/\d{4}$/;

        // Si está vacío, limpiar el daterangepicker
        if (currentValue === '') {
            $(this).data('daterangepicker').setStartDate(moment());
            $(this).data('daterangepicker').setEndDate(moment());
            $(this).data('daterangepicker').updateView();
        }

        // Si no está vacío Y no tiene formato correcto, salir
        if (currentValue !== '' && !dateRangePattern.test(currentValue)) return;

        // Validar y formatear fechas
        var parts = currentValue.split(' - ');
        var start = moment(parts[0], 'DD/MM/YYYY');
        var end = moment(parts[1], 'DD/MM/YYYY');

        if (!start.isValid() || !end.isValid() || start.isAfter(end)) return;

        previousValue = $(this).val(start.format('DD/MM/YYYY') + ' - ' + end.format('DD/MM/YYYY')).val();

        notifyFiltersChange();
    });

    $('#date-range').on('input', function () {

        var currentValue = $(this).val();

        // Solo permitir números (0-9), espacios y guión medio (-)
        var allowedPattern = /^[0-9\s\-\/]*$/;

        if (!allowedPattern.test(currentValue)) {
            $(this).val(currentValue.slice(0, -1));
            return;
        }

        if (currentValue === '') {
            $(this).data('daterangepicker').setStartDate(moment());
            $(this).data('daterangepicker').setEndDate(moment());
            $(this).data('daterangepicker').updateView();
        }
    });
});
// Guarda el valor inicial del input

$('#date-range').on('input', function () {
    if (previousValue && !$(this).val()) {

        notifyFiltersChange();
    }
    previousValue = $(this).val(); // Actualiza el valor previo
});

$(document).on('change', '#checkAllId', function () {
    handleGlobalCheckbox(this.checked);
});

// 2. Función para manejar el cambio
function handleGlobalCheckbox(isChecked) {
    isSelectAll = isChecked;
    uuidList = [];
    const datatable = $('#data-table').DataTable();
    if (datatable.rows().count() == 0) return;
    datatable.rows().every(function () {
        const rowData = this.data();
        const rowCheckbox = $(this.node()).find('input[type="checkbox"]');
        let rowCheckState = isChecked;
        rowCheckbox.prop('checked', rowCheckState).trigger('change');
    });
}

$(document).ready(function () {
    // Aplica las clases de DataTables a tu select personalizado
    $('#pageSizeSelector_detailTable').addClass('custom-select form-control form-control-sm');
});

// Ordenar la tabla por la segunda columna (Fecha emisión) en orden descendente al cargarla
$("#data-table thead th").eq(1).addClass('descending').removeClass('sorting').addClass('sorting_desc');

// Aplica el ordenamiento personalizado a los encabezados de columna
$("#data-table thead th").not(':first').on('click', function () {
    let column = Number($(this).index()); // Asegura que sea número

    const sortableColumns = [1, 2, 3, 4, 5, 6, 7, 8, 9];

    if (sortableColumns.indexOf(column) !== -1) {

        columndetailTable = column

        const isAscending = $(this).hasClass('ascending');

        // Remueve las clases de todos los encabezados
        $("#data-table thead th").removeClass('ascending descending sorting_asc sorting_desc').addClass('sorting');

        // Alterna entre ascendente y descendente
        if (isAscending) {
            $(this).addClass('descending').removeClass('sorting').addClass('sorting_desc');
            isAscendingdetailTable = "desc";
        } else {
            $(this).addClass('ascending').removeClass('sorting').addClass('sorting_asc');
            isAscendingdetailTable = "asc";
        }
        notifyFiltersChange();



    }
});


 

function getCompanyFormData() {
    function getValue(id) {
        var el = document.getElementById(id);
        return el ? (el.value || '') : '';
    }

    function getChecked(id) {
        var el = document.getElementById(id);
        return el ? el.checked : false;
    }

    var configSection = document.getElementById("configsection");
    var configPanelHidden = false;

    if (configSection && configSection.style && configSection.style.display === "none") {
        configPanelHidden = true;
    }

    var data = {
        cer: getValue('cer'),
        key: getValue('key'),
        password: getValue('password'),
        rfc: getValue('rfc'),
        razonSocial: getValue('razonsocial'),
        companyName: getValue('companyName'),
        companyADD: getValue('companyADD'),
        guidADD: getValue('guidADD'),
        checkAutomaticDownload: getChecked('checkautomaticdownload'),
        checkEmitidos: getChecked('checkemitidos'),
        checkRecibidos: getChecked('checkrecibidos'),
        fileSavePath: getValue('filesavepath'),
        configPanelHidden: configPanelHidden,
        companyGuid: (typeof getCompanyGuid === 'function') ? getCompanyGuid() : '00000000-0000-0000-0000-000000000000',
        companySelecction: (typeof getCompanySelecction === 'function') ? getCompanySelecction() : '',
        windowRoute: (typeof getWindowRoute === 'function') ? getWindowRoute() : ''
    };

    return JSON.stringify(data);
}

function getFielInputData(fileType) {
    function getValue(id) {
        var el = document.getElementById(id);
        return el ? (el.value ? el.value.trim() : '') : '';
    }

    function isConfigSectionHidden() {
        var config = document.getElementById("configsection");
        if (!config) return true;
        var display = window.getComputedStyle(config).display;
        return display === "none";
    }

    var inputValue = getValue(fileType);
    var rfc = getValue("rfc");
    var configPanelHidden = isConfigSectionHidden();

    var result = {
        fileType: fileType,
        inputValue: inputValue,
        rfc: rfc,
        configPanelHidden: configPanelHidden
    };

    return JSON.stringify(result);
}


document.addEventListener('DOMContentLoaded', function () {

    function setupMenu(menuItemId, providerType, action, documentType, value) {
        var menuItem = document.getElementById(menuItemId);
        if (!menuItem) return;

        var targetElement = menuItem; // ← corregido: acepta cualquier tipo de elemento clickeable

        targetElement.addEventListener('click', function (e) {
            e.preventDefault();
            e.stopPropagation();

            postWebViewMessage({
                providerType: providerType,
                action: action,
                documentType: documentType || targetElement.getAttribute('data-documenttype') || null,
                value: value || targetElement.getAttribute('data-value') || null
            });
        });
    }

    function postWebViewMessage(options) {
        var message = {
            providerType: options.providerType,
            action: options.action
        };

        if (options.documentType !== null) message.documentType = options.documentType;
        if (options.value !== null) message.value = options.value;
        if (options.hasMetadata !== undefined) message.hasMetadata = options.hasMetadata;

        if (window.chrome && window.chrome.webview && typeof chrome.webview.postMessage === "function") {
            chrome.webview.postMessage(JSON.stringify({
                type: "WebViewMessage",
                payload: message
            }));

        } else {
            console.error("WebView no está disponible");
        }
    }



    $('#tabletop').on('click', 'tr', function (e) {



        var rowData = tabletopobj.row(this).data();
        if (rowData) {
            detailPageNumber = 1;
            postWebViewMessage({
                providerType: "BaseLoadListService",
                action: "rowClick",
                documentType: rowData.ID // O el campo que necesites enviar
            });
        }

    });

    $(document).on('click', '#companyTable [data-providertype="CompanyFavoriteService"]', function (e) {
        e.preventDefault();
        e.stopPropagation();

        var $element = $(this);
        var isActive = $element.hasClass('active');
        var newState = !isActive;

        $element.toggleClass('active', newState);
        if ($element.is('i')) {
            $element.closest('.favorite-btn').toggleClass('active', newState);
        }



        postWebViewMessage({
            providerType: "CompanyFavoriteService",
            action: "toggleFavorite",
            documentType: $element.data('documenttype'),
            value: newState
        });
    });

    $(document).on('click', '#companyTable [data-providertype="CompaniesEnable"]', function (e) {

        var $checkbox = $(this);
        var isChecked = $checkbox.is(':checked');

        if (isChecked) {
            postWebViewMessage({
                providerType: "CompaniesEnable",
                action: "toggleEstatus",
                documentType: $checkbox.data('documenttype'),
                value: true
            });
        }
    });


    $(document).on('click', '#companyTable [data-providertype="ManageDownloaderProvider"]', function (e) {
        e.preventDefault();
        e.stopPropagation();

        var $element = $(this);
        if ($element.is(':disabled')) return;

        postWebViewMessage({
            providerType: "ManageDownloaderProvider",
            action: "downloadRequest",
            documentType: $element.data('documenttype') || null,
            value: $element.data('value') || null
        });
    });


    $(document).on('click', '#companyTable [data-providertype="CompanySelectionProvider"]', function (e) {
        e.preventDefault();
        e.stopPropagation();

        var $element = $(this);
        if ($element.is(':disabled')) return;

        postWebViewMessage({
            providerType: "CompanySelection",
            action: "rowClick",
            documentType: $element.data('documenttype')
        });
    });

    $(document).on('click', '.cancelRequest-button', function () {
        var documentId = $(this).data('id'); // este es el row.ID

        // Asignar ese ID al botón "Aceptar" del modal
        $('button[name="deletebtnconfirmCancel"]').attr('data-documenttype', documentId);


    });

    $(document).on('click', '.aboutLink', function (e) {
        e.preventDefault();
        e.stopPropagation();

        var documentType = $(this).data('documenttype');

        postWebViewMessage({
            providerType: "About",   // ← esto actúa como menuItemId
            action: "menuClick",
            documentType: documentType
        });
    });

    $(document).on('click', 'button[name="deletebtnconfirm"]', function (e) {

        var $btn = $(this);

        try {
            e.preventDefault();
            e.stopPropagation();

            // Evitar más clics
            if ($btn.prop("disabled")) return;

            $btn.prop("disabled", true);

            var providerType = $btn.attr('data-providertype');
            var documentType = $btn.attr('data-documenttype');

            var checked = $btn.attr('data-checked');
            var password = $('#passwordInputconfirm').val() || '';

            // Enviar al WebView
            postWebViewMessage({
                providerType: providerType,
                action: "menuClick",
                documentType: documentType,
                value: JSON.stringify({
                    checked: checked,
                    password: password
                })
            });
        }
        catch
        {

        }
        finally {
            setTimeout(() => {
                $btn.prop("disabled", false);
            }, 400);
        }
    });


    // Menús y botones
    setupMenu('mnuEmpresas', 'CompaniesListLoad', 'menuClick', '', '');
    setupMenu('mnuDescargar', 'ManageDownloaderProvider', 'menuClick', '', '');
    setupMenu('mnuCancelados', 'ManageDownloaderProvider', 'menuClick', '', '');
    setupMenu('mnuvisor', 'ManageVisorProvider', 'menuClick', '', '');
    setupMenu('mnuManagerrfc', 'CompanyConfigurationManagerService', 'menuClick', '', '');
    setupMenu('mnuNuevaEmpresa', 'CompanyCreationModalService', 'menuClick', '', '');
    setupMenu('mnuActualizarNuevaEmpresa', 'UpdateCompanyCreationModalService', 'menuClick', '', '');
    setupMenu('ayudaControl', 'Ayuda', 'menuClick', '', '');
    setupMenu('exitControl', 'Exit', 'menuClick', '', '');
    setupMenu('CompanyCreationAcept', 'CompanyCreationService', 'menuClick', '', '');
    setupMenu('UpdateCompanyCreation', 'UpdateCompanyCreationModalService', 'menuClick', '', '');
    setupMenu('CompanyCreationModal', 'CompanyCreationModalService', 'menuClick', '', '');
    setupMenu('deletebtnconfirmCancel', 'DisableProcess', 'menuClick', '', '');
    setupMenu('RefreshServiciosSAT', 'RefreshRequestListService', 'menuClick', '', '');
    setupMenu('mnuFilePopupCer', 'FilePopupManagerService', 'menuClick', '', '');
    setupMenu('mnuFilePopupKey', 'FilePopupManagerService', 'menuClick', '', '');
    setupMenu('mnuFolderPopup', 'FolderPopupManagerService', 'menuClick', '', '');
    setupMenu('btnExtraParameter', 'ExtraParameterHandler', 'menuClick', '', '');



});


function initializePage(data) {
    const { guidCompany, companyName, rfc, hasAdd, acceso } = (typeof data === "string") ? JSON.parse(data) : data;

    const visible = acceso !== 2;
    document.getElementById("mnuEmpresas").style.display = visible ? "" : "none";
    document.getElementById("automaticas").style.display = visible ? "" : "none";
    if (!visible) {
         
        document.getElementById("EmpresasADD").style.display = "none";
    }
   
    // Visor ADD
    if (hasAdd === true || hasAdd === "true") {
        document.getElementById("mnuvisor").removeAttribute("class");
    } else {
        const visor = document.getElementById("mnuvisor");
        visor.removeAttribute("rel");
        visor.removeAttribute("href");
    }

    // Company GUID en atributos
    if (guidCompany && guidCompany !== "00000000-0000-0000-0000-000000000000") {
        document.getElementById("mnuDescargar").removeAttribute("class");
        document.getElementById("mnuCancelados").removeAttribute("class");
        document.getElementById("mnuManagerrfc").removeAttribute("class");

        const elements = ["mnuCancelados","mnuDescargar", "mnuManagerrfc", "mnuvisor", "CompanyCreationAcept", "btnExtraParameter"];

        elements.forEach(id => {
            const el = document.getElementById(id);
            if (el) {
                el.setAttribute("data-documenttype", guidCompany);
            }
        });
    }

    // Mostrar datos de empresa
    document.getElementById("lblCompany").innerText = companyName;
    document.getElementById("lblCompany").setAttribute("title", companyName);
    document.getElementById("RfcTitle").innerText = rfc;
    $('#companyListModal').modal('hide');
}
function getSelectedUuidsInfo() {
    var result = {
        uuids: (typeof uuidList !== 'undefined' && uuidList.length > 0) ? uuidList : [],
        isSelectAll: (typeof isSelectAll !== 'undefined') ? isSelectAll : false
    };
    return JSON.stringify(result);
}