// 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/listReporte_financiero_Contratos',
    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.Clasificación}</td>
            <td>${op.Departamento}</td>
            <td>${op.DepartamentClass}</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.FacturadoIVAMXN}</td>
            <td>${op.ListaDeFacturas}</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: 'Reporte_Financiero_Contratos' // Aquí se define el nombre
            }],
            scrollX: true,
            autoWidth: true,
            ordering: false,
            fixedHeader: true,
            searching: true,
            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();

});
