import Table from '../../components/table.js';
import ConfirmDeleteModal from '../../components/ConfirmDeleteModal.js';
import Ajax from '../../components/ajax.js';
import { getToken } from '../../common/common.js';

class PlantillasTarifasClienteList {

    constructor() {

        this.domItem = $('.card-body');

        this.csrf_token = getToken();
        this.csrf_hash = $('#mainContainer').find('input[name="' + this.csrf_token + '"]').val();

        this.tablePlantillas = null;
        this.deleteModal = null;
    }

    init() {

        const self = this;

        this.headerSearcher();

        this.deleteModal = new ConfirmDeleteModal('plantillasTarifasCliente');
        this.deleteModal.init();

        this.#initTable();

        // Editar en linea la fila
        this.tablePlantillas.table.on('click', '.btn-edit-' + this.tablePlantillas.getAlias(), function (e) {

            const dataId = $(this).attr('data-id');

            if (!Number.isNaN(Number(dataId))) {
                window.location.href = '/clienteplantillaprecios/edit/' + dataId;
            }
        });


        // Eliminar la fila
        this.tablePlantillas.table.on('click', '.btn-delete-' + this.tablePlantillas.getAlias(), function (e) {
            const row = $(this).closest('tr')[0]._DT_RowIndex;
            const dataId = $(this).attr('data-id');
            self.deleteModal.setData($(this).attr('data-id'));
            self.deleteModal.show(() => {

                if (!Number.isNaN(Number(self.deleteModal.getData()))) {

                    new Ajax(
                        '/clienteplantillaprecios/delete/' + dataId,
                        {

                        },
                        {},
                        (data, textStatus, jqXHR) => {

                            self.tablePlantillas.table.clearPipeline();
                            self.tablePlantillas.table.row($(row)).invalidate().draw();

                            // Se borran las lineas asociadas
                            new Ajax(
                                "/clienteplantillaprecios/update/" + dataId,
                                {
                                    [this.csrf_token]: this.csrf_hash
                                },
                                {},
                                () => { },
                                (error) => {
                                    console.log(error);
                                }).post();

                            popSuccessAlert(data.msg ?? jqXHR.statusText);
                        },
                        (error) => {
                            console.log(error);
                        }

                    ).get();
                    self.deleteModal.hide();
                }
            });
        });
    }

    #initTable() {

        const self = this;

        const columns = [
            { 'data': 'id' },
            { 'data': 'nombre' },

        ];

        const actions = ['edit', 'delete'];

        this.tablePlantillas = new Table(
            $('#tableOfClienteplantillaprecios'),
            'plantillasTarifasCliente',
            '/clienteplantillaprecios/datatable',
            columns,
            []
        );


        this.tablePlantillas.init({
            actions: actions,
            colVisibility: false,
            buttonsExport: true,
        });


        this.tablePlantillas.table.on('init.dt', function () {
            self.tablePlantillas.table.page.len(50).draw();
        });

    }

    headerSearcher() {

        const self = this;

        $('#tableOfClienteplantillaprecios thead tr').clone(false).appendTo('#tableOfClienteplantillaprecios thead');
        $('#tableOfClienteplantillaprecios thead tr:eq(1) th').each(function (i) {

            if (!$(this).hasClass("noFilter")) {

                $(this).html('<input type="text" class="form-control " style="min-width:100px;max-width:500px;font-size:0.8rem !important;"  />');

                $('input', this).on('change clear', function () {
                    if (self.tablePlantillas.table.column(i).search() !== this.value) {
                        self.tablePlantillas.table
                            .column(i)
                            .search(this.value)
                            .draw();
                    }
                });
            }
            else {
                $(this).html('<span></span>');
            }
        });


    }

}

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

    new PlantillasTarifasClienteList().init();
}); 