// Optimized JavaScript Code
/**
 * DMbreakers.js - Gestión de catálogo de breakers
 * Ruta: src/static/js/Ventas/VentasEUA/DataMaster/DMbreakers.js
 */

// =====================================
// Configuración y Variables Globales
// =====================================
const CONFIG = {
    API_URL: '/SYS/GSYC/Table/listTable1',
    TABLA_ID: 'Table1',
    MONEDA: {
        estilo: 'currency',
        moneda: 'MXN',
        locale: 'es-MX'
    }
};

// =====================================
// Gestión del Indicador de Carga
// =====================================
const LoadingManager = {
    element: document.getElementById("loading-indicator"),
    
    show() {
        if (this.element) this.element.style.display = "block";
    },
    
    hide() {
        if (this.element) this.element.style.display = "none";
    }
};

document.addEventListener("DOMContentLoaded", () => {
    const Table1Instance = new Table1();

    document.getElementById("TableBody").addEventListener("click", function(e) {
        if (e.target.classList.contains("ocultar-btn")) {
            Table1Instance.handleDelete(e);
        }
    });
});

// =====================================
// Gestión de la Tabla de Breakers
// =====================================
class Table1 {

    constructor() {
        this.table = null;
        this.initializeTable();
    }

    async initializeTable() {
        LoadingManager.show();
        try {
            const data = await this.fetchBreakersData();
            this.renderTableData(data);
            this.initializeDataTable();
            this.setupEventListeners();
        } catch (error) {
            console.error("Error al inicializar la tabla:", error);
        } finally {
            LoadingManager.hide();
        }
    }

    async fetchBreakersData() {
        const response = await fetch(CONFIG.API_URL);
        const data = await response.json();
        console.log(data); // Verifica que los datos de precios estén presentes
        return data;
    }
    renderTableData(data) {
        const tableBody = document.getElementById("TableBody");
        tableBody.innerHTML = data.map(op => this.createTableRow(op)).join('');
    }

    createTableRow(op) {
       
       
        return `
            <tr>
                <td>${op.ContractNum}</td>
                <td>${op.EntryDate}</td>
                <td>${op.EntryPerson}</td>
                <td>${op.Folio}</td>
                <td>${op.ContractCode}</td>
                <td>${op.Division}</td>
                <td>${op.Departamento}</td>
                <td>${op.ContractDescription}</td>
                <td>${op.CustNum}</td>
                <td>${op.CustID}</td>
                <td>${op.Cliente}</td>
                <td>${op.Importe}</td>
                <td>${op.ImporteMXN}</td>
                <td>${op.CurrencyCode}</td>
                <td>${op.ExchangeRate}</td>
                <td>${op.Duration}</td>
                <td>${op.Modifier}</td>
                <td>${op.ActiveDate}</td>
                <td>${op.ExpireDate}</td>
                <td>${op.ContractComment}</td>
                <td>${op.InvoiceComment}</td>
                <td>${op.TipoDeContrato}</td>
                <td>${op.Facturado}</td>
                <td>${op.FacturadoIVA}</td>
                <td>${op.FacturadoMXN}</td>
                <td>${op.FacturadoIVAMXN}</td>
                <td>${op.ListaDeFacturas}</td>
                <td>${op.PorFacturar}</td>
                <td>${op.Revisión}</td>
                <td>${op.RevisiónRenovacion}</td>
                <td>${op.Renovación_si_no}</td>
                <td>${op.Consideración}</td>
                <td>${op.Comentario}</td>
                <td>${op.Pronostico}</td>
                <td>${op.FechadeCobro}</td>
            </tr>
        `;
    }


  
    initializeDataTable() {
        if ($.fn.DataTable.isDataTable("#" + CONFIG.TABLA_ID)) {
            $('#' + CONFIG.TABLA_ID).DataTable().destroy();
        }

        this.table = $('#' + CONFIG.TABLA_ID).DataTable({
            dom: '<"d-flex justify-content-between align-items-center mb-2" Bf>rtip',
            buttons: [{
                extend: 'excel',
                text: '<i class="fas fa-file-excel"></i> Excel',
                className: 'btn btn-success dm-btn-xs dm-custom-excel-button',
                filename: 'Flujo_de_Contratos' // Aquí se define el nombre
            }],
            scrollX: true,
            autoWidth: true,
            ordering: false,
            fixedHeader: true,
            searching: true,
            columnDefs: [
                { targets: 0, width: "15%" },
                { targets: 1, width: "40%" },
                { targets: 2, width: "15%" },
                { targets: 3, width: "30%" },
                {
                    targets: 0,
                    className: 'text-center',
                },
                {
                    targets: 1,
                    className: 'text-left',
                },
                {
                    targets: 2,
                    className: 'text-center',
                    render: function(data, type, row) {
                        if (type === 'display' || type === 'filter') {
                            // Verificar si el dato es un número válido
                            const number = parseFloat(data);
                            if (!isNaN(number)) {
                                return new Intl.NumberFormat('es-MX', {
                                    style: 'currency',
                                    currency: 'MXN'
                                }).format(number);
                            } else {
                                return data; // Devolver el dato original si no es un número válido
                            }
                        }
                        return data;
                    }
                },

                {
                    targets: 3,
                    className: 'text-center',
                },
                
                {
                    targets: 4,
                    className: 'text-center',
                },
            ],
            language: {
                search: "Buscar:",
                lengthMenu: "Mostrar _MENU_ registros por página",
                info: "Mostrando _START_ a _END_ de _TOTAL_ registros",
                infoEmpty: "Mostrando 0 a 0 de 0 registros",
                paginate: {
                    first: "Primero",
                    last: "Último",
                    next: "Siguiente",
                    previous: "Anterior"
                }
            }
        });
    }

    setupEventListeners() {
        // Filtros de columna
        $('.column-filter').on('keyup change', (e) => {
            const columnIndex = $(e.target).data('column');
            this.table.column(columnIndex).search(e.target.value).draw();
        });

    }

  

}




// =====================================
// Inicialización
// =====================================
document.addEventListener("DOMContentLoaded", () => {
    new Table1();

});
