import Ajax from "../../components/ajax.js"

class Pedidos {

    constructor() {

        this.total_ejemplares = 0;
        this.total_facturado = 0;

        this.tableFacturas = $('#tableOfFacturas').DataTable();
        this.tablePedidos = $('#tableOfLineasPedido').DataTable();
        this.btnAddFactura = $('#add-factura');
    }

    init() {

        if (this.btnAddFactura) {
            this.tableFacturas.on('draw', function () {
                this.total_facturado = 0;
                for (let i = 0; i < this.tableFacturas.rows().count(); i++) {
                    this.total_facturado += parseFloat(this.tableFacturas.row(i).data().ejemplares);
                }
                this.checkAddFactura();
            }.bind(this));

            this.tablePedidos.on('draw', function () {
                this.total_ejemplares = 0;
                for (let i = 0; i < this.tablePedidos.rows().count(); i++) {
                    this.total_ejemplares += parseInt(this.tablePedidos.row(i).data().unidades);
                }
                this.checkAddFactura();
            }.bind(this));

            this.btnAddFactura.on('click', this.addFacturaAction.bind(this));
        }
    }

    addFacturaAction() {

        Swal.fire({
            title: 'Seleccione serie de facturación',
            html: `<div class="row">
                    <div class="col-12">
                        <select id="select-serie" class="form-control select2bs serie-facturacion-select" style="width: 100%;"></select>
                    </div>
                </div>`,
            showCancelButton: true,
            cancelButtonText: 'Cancelar',
            showDenyButton: false,
            confirmButtonText: 'Ok',
            showDenyButton: false,
            buttonsStyling: false,
            customClass: {
                confirmButton: 'btn btn-primary',
                cancelButton: 'btn btn-danger'
            },
            didOpen: function () {
                $('.serie-facturacion-select').select2({
                    allowClear: false,
                    minimumResultsForSearch: -1,
                    //dropdownParent: $('#swal2-html-container'),
                    ajax: {
                        url: '/configuracion/series-facturas/menuitemsFacturas',
                        type: 'post',
                        dataType: 'json',

                        data: function (params) {
                            return {
                                id: 'id',
                                text: 'nombre',
                                searchTerm: params.term,

                            };
                        },
                        delay: 60,
                        processResults: function (response) {
                            return {
                                results: response.menu
                            };
                        },
                        cache: true
                    }
                });
            },
            preConfirm: () => {
                return $('#select-serie').val();
            }
        }).then(result => {
            if (result.isConfirmed) {
                if (result.value != null && result.value != '' && result.value != 0) {
                    let id = window.location.pathname.split('/').pop();
                    const ajax = new Ajax(`/pedidos/insertfactura`,
                        {
                            pedido_id: id,
                            serie_id: result.value,

                        },
                        null,
                        () => {
                            this.tableFacturas.clearPipeline().draw();
                        },
                        (error) => {
                            console.log("Error:", error);
                        }
                    )
                    ajax.post();
                }
            }
        });
    }

    checkAddFactura() {

        if (this.total_facturado == this.total_ejemplares) {
            this.btnAddFactura.addClass('d-none');
        }
        else {
            this.btnAddFactura.removeClass('d-none');
        }
    };
}

$(document).ready(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: ['Presupuestos', 'PresupuestosDirecciones'] }, {},
        function (translations) {
            window.language = JSON.parse(translations);
            new PresupuestoAdminEdit().init();
        },
        function (error) {
            console.log("Error getting translations:", error);
        }
    ).post();*/

    new Pedidos().init();
});

export default Pedidos;