// 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/listTable2',
    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.OrderNum	}</td>
            <td>${op.Departamento	}</td>
            <td>${op.Vendedor	}</td>
            <td>${op.Name	}</td>
            <td>${op.TotalLines	}</td>
            <td>${op.OrderLine	}</td>
            <td>${op.PartNum	}</td>
            <td>${op.LineDesc	}</td>
            <td>${op.Capacidad	}</td>
            <td>${op.Voltaje	}</td>
            <td>${op.Tipo	}</td>
            <td>${op.RevisionNum	}</td>
            <td>${op.ProdCode	}</td>
            <td>${op.DecriptionProd	}</td>
            <td>${op.Caseta	}</td>
            <td>${op.Tanque	}</td>
            <td>${op.OrderDate	}</td>
            <td>${op.NeedByDate	}</td>
            <td>${op.LiberacionCXP	}</td>
            <td>${op.OrderNumAndLine	}</td>
            <td>${op.ProjectID	}</td>
            <td>${op.JobNum2	}</td>
            <td>${op.Revision_OV	}</td>
            <td>${op.Revision_Project	}</td>
            <td>${op.Revision_Job	}</td>
            <td>${op.FechaVentas	}</td>
            <td>${op.ComentarioSyC	}</td>
            <td>${op.Chk	}</td>
            <td>${op.FechaSyC	}</td>
            <td>${op.FechaSimulaciones	}</td>
            <td>${op.ConsideradaPreasignacion	}</td>
            <td>${op.ConsideradaMateriales	}</td>
            <td>${op.FechaProducción	}</td>
            <td>${op.ComentarioProducción	}</td>
            <td>${op.AvanceProducción	}</td>
            <td>${op.FechaPlaneación	}</td>
            <td>${op.EstadoFecha	}</td>
            <td>${op.ComentarioPlaneación	}</td>
            <td>${op.FechaMG	}</td>
            <td>${op.FechaMat	}</td>
            <td>${op.AvanceDeSurtimiento	}</td>
            <td>${op.MaterialSinSurtir	}</td>
            <td>${op.AvisoDeTerminacion	}</td>
            <td>${op.TerminadoConFaltante	}</td>
            <td>${op.FechaActualización	}</td>
            <td>${op.MaterialFaltante	}</td>
            <td>${op.ValidaciónFisica	}</td>
            <td>${op.ResultadoValidación	}</td>
            <td>${op.FechaDeCierre	}</td>
            <td>${op.ComentarioCalidad	}</td>
            <td>${op.InsumosDemandados	}</td>
            <td>${op.InsumosEmitidos	}</td>
            <td>${op.AvaceDeEmisiones	}</td>
            <td>${op.FechaDeTermino	}</td>
            <td>${op.AvanceManufacturaSyC	}</td>
            <td>${op.AvanceEnsambleSyC	}</td>
            <td>${op.ComentarioSupervisión	}</td>
            <td>${op.EnFilaPruebasSyC	}</td>
            <td>${op.PendientesCalidSyC	}</td>
            <td>${op.PartNum_M	}</td>
            <td>${op.Description_M	}</td>
            <td>${op.PartClass_M	}</td>
            <td>${op.RefCategory_M	}</td>
            <td>${op.QtyPer_M	}</td>
            <td>${op.IssuedQty_M	}</td>
            <td>${op.Demandado_M	}</td>
            <td>${op.OnhandQty_M	}</td>
            <td>${op.Preasignado_M	}</td>
            <td>${op.NoSerie_M	}</td>
            <td>${op.Faltante_M	}</td>
            <td>${op.En_PO_M	}</td>
            <td>${op.NoPO_M	}</td>
            <td>${op.EnRequisicion_M	}</td>
            <td>${op.NoRequisicion_M	}</td>
            <td>${op.Alternativa_M	}</td>
            <td>${op.En_PO_Altern_M	}</td>
            <td>${op.NoPO_Alern_M	}</td>
            <td>${op.Req_M	}</td>
            <td>${op.Comment_M	}</td>
            <td>${op.FechaReq_M	}</td>
            <td>${op.PO_M	}</td>
            <td>${op.Cantidad_Pedida_M	}</td>
            <td>${op.Estatus_M	}</td>
            <td>${op.Fecha_Llegada_M	}</td>
            <td>${op.PartNum_G	}</td>
            <td>${op.Description_G	}</td>
            <td>${op.PartClass_G	}</td>
            <td>${op.RefCategory_G	}</td>
            <td>${op.QtyPer_G	}</td>
            <td>${op.IssuedQty_G	}</td>
            <td>${op.Demandado_G	}</td>
            <td>${op.OnhandQty_G	}</td>
            <td>${op.Preasignado_G	}</td>
            <td>${op.NoSerie_G	}</td>
            <td>${op.Faltante_G	}</td>
            <td>${op.En_PO_G	}</td>
            <td>${op.NoPO_G	}</td>
            <td>${op.EnRequisicion_G	}</td>
            <td>${op.NoRequisicion_G	}</td>
            <td>${op.Alternativa_G	}</td>
            <td>${op.En_PO_Altern_G	}</td>
            <td>${op.NoPO_Alern_G	}</td>
            <td>${op.Req_G	}</td>
            <td>${op.Comment_G	}</td>
            <td>${op.FechaReq_G	}</td>
            <td>${op.PO_G	}</td>
            <td>${op.Cantidad_Pedida_G	}</td>
            <td>${op.Estatus_G	}</td>
            <td>${op.Fecha_Llegada_G	}</td>
            <td>${op.PartNum_T	}</td>
            <td>${op.Description_T	}</td>
            <td>${op.PartClass_T	}</td>
            <td>${op.RefCategory_T	}</td>
            <td>${op.QtyPer_T	}</td>
            <td>${op.IssuedQty_T	}</td>
            <td>${op.OnhandQty_T	}</td>
            <td>${op.PartNum_R	}</td>
            <td>${op.Description_R	}</td>
            <td>${op.PartClass_R	}</td>
            <td>${op.RefCategory_R	}</td>
            <td>${op.QtyPer_R	}</td>
            <td>${op.IssuedQty_R	}</td>
            <td>${op.OnhandQty_R	}</td>
            <td>${op.ComentarioLINE	}</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: 'Score' // 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();

});
