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 ClienteList {

    constructor() {

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

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

        this.tableClientes = 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.tableClientes.table.on('click', '.btn-edit-' + this.tableClientes.getAlias(), function (e) {

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

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

        // Eliminar la fila
        this.tableClientes.table.on('click', '.btn-delete-' + this.tableClientes.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(
                        '/clientes/cliente/delete/' + dataId,
                        {

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

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

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

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

    #initTable() {

        const self = this;

        const columns = [
            { 'data': 'id' },
            { 'data': 'nombre' },
            { 'data': 'alias' },
            { 'data': 'cif' },
            { 'data': 'email' },
            { 'data': 'comercial' },
            { 'data': 'forma_pago_id' },
            { 'data': 'vencimiento' },
        ];

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

        this.tableClientes = new Table(
            $('#tableOfClientes'),
            'clienteList',
            '/clientes/cliente/datatable',
            columns,
            []
        );


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


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

    }

    headerSearcher() {

        const self = this;

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

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

                let min_width = 100;
                if(i == 0){
                    min_width = 50;
                }

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

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


    }

}

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

    const dropdown = document.querySelector(".dropdown-language");
    const activeItem = dropdown.querySelector(".dropdown-menu .dropdown-item");
    let locale = 'es';
    if (activeItem) {
        locale = activeItem.getAttribute("data-language");
    }

    new Ajax('/translate/getTranslation', { locale: locale, translationFile: ['Clientes', 'FormasPago', 'Users'] }, {},
        function (translations) {
            window.language = JSON.parse(translations);
            new ClienteList().init();
        },
        function (error) {
            console.log("Error getting translations:", error);
        }
    ).post();
});

