// Optimized JavaScript Code
/**
 * DMbreakers.js - Gestión de catálogo de breakers
 * Ruta: src\static\js\SupYCtrol\GSYC\GSyCReporte_financiero_OV.js
 */

// =====================================
// Configuración y Variables Globales
// =====================================
const CONFIG = {
    API_URL: '/SYS/GSYC/listReporte_financiero_OV',
    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.Company}</td>
            <td>${op.OV}</td>
            <td>${op.FechaOV}</td>
            <td>${op.OrderCode}</td>
            <td>${op.División}</td>
            <td>${op.Clasificación}</td>
            <td>${op.Departamento}</td>
            <td>${op.DepartamentClass}</td>
            <td>${op.Vendedor}</td>
            <td>${op.CustNum}</td>
            <td>${op.CustID}</td>
            <td>${op.Cliente}</td>
            <td>${op.TotalLines}</td>
            <td>${op.EstatusOV}</td>
            <td>${op.Importe}</td>
            <td>${op.Descuento}</td>
            <td>${op.Misc}</td>
            <td>${op.Subtotal}</td>
            <td>${op.Impuesto}</td>
            <td>${op.Redondeo}</td>
            <td>${op.Total_de_la_Orden}</td>
            <td>${op.Moneda}</td>
            <td>${op.Cambio}</td>
            <td>${op.ImporteMXN}</td>
            <td>${op.DescuentoMXN}</td>
            <td>${op.MiscMXN}</td>
            <td>${op.SubtotalMXN}</td>
            <td>${op.ImpuestoMXN}</td>
            <td>${op.RedondeoMXN}</td>
            <td>${op.Total_de_la_Orden_MXN}</td>
            <td>${op.Terminos_OV}</td>
            <td>${op.Dias_de_pago_OV}</td>
            <td>${op.Comentario_de_OV}</td>
            <td>${op.TipoDeVenta}</td>
            <td>${op.Facturado}</td>
            <td>${op.FacturadoIVA}</td>
            <td>${op.FacturadoMXN}</td>
            <td>${op.FacturadoIVAMXN}</td>
            <td>${op.ListaDeFacturas}</td>
            <td>${op.FechaUltimaFactura}</td>
            <td>${op.Facturacion_Manual}</td>
            <td>${op.Comentario_de_correccion}</td>
            <td>${op.Por_Facturar}</td>
            <td>${op.porcentage}</td>
            <td>${op.Revisión}</td>
            <td>${op.AllProjectID}</td>
            <td>${op.Columna1}</td>
            <td>${op.JobNumsInProject}</td>
            <td>${op.Material}</td>
            <td>${op.Labor}</td>
            <td>${op.Burden}</td>
            <td>${op.Subcontract}</td>
            <td>${op.MtlBur}</td>
            <td>${op.TotalCostPrj}</td>
            <td>${op.JobNumsDirectOV}</td>
            <td>${op.MaterialDir}</td>
            <td>${op.LaborDir}</td>
            <td>${op.BurdenDir}</td>
            <td>${op.SubcontractDir}</td>
            <td>${op.MtlBurDir}</td>
            <td>${op.TotalCostDir}</td>
            <td>${op.TotalCost}</td>
            <td>${op.Utilidad}</td>
            <td>${op.porcentage2}</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_OV' // 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();

});
