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

class ClienteFacturacion {
    constructor() {

        this.bsRangePickerRange = $('#' + 'fechaFactura');
        this.clienteId = $('#clienteForm').attr('data-cliente');
    }

    init() {

        const self = this;

        // select button with data-bs-target="#facturacion"
        $(document).on('click', '.facturacion-btn', function (e) {
            e.preventDefault();
            $('#tableOfFacturasCliente').DataTable().columns.adjust().draw();
            $(this).tab('show');
        });

        $('#tableOfFacturasCliente').on('click', '.btn-edit', function (e) {
            window.location.href = '/facturas/edit/' + $(this).attr('data-id');
        });

        const lastColNr = $('#tableOfFacturasCliente').find("tr:first th").length - 1;

        let datatableColumns = [];

        datatableColumns = [
            { 'data': 'numero' },
            { 'data': 'fecha_factura_at', searchable: false },
            { 'data': 'total', render: (d) => `<span class="autonumeric">${d}</span>` },
            { 'data': 'estado' },
            { 'data': 'estado_pago' },
            { 'data': 'action' }
        ];

        $('#tableOfFacturasCliente').DataTable({
            processing: true,
            serverSide: true,
            autoWidth: true,
            responsive: true,
            scrollX: true,
            orderCellsTop: true,
            lengthMenu: [5, 10, 25, 50, 75, 100, 250, 500, 1000, 2500],
            pageLength: 250,
            "dom": 'lBrtip',
            order: [[0, 'asc']],
            language: {
                url: "/themes/vuexy/vendor/libs/datatables-sk/plugins/i18n/es-ES.json"
            },
            ajax: {
                url: '/facturas/datatable',
                type: 'GET',
                data: function (d) {
                    d.cliente_id = self.clienteId;
                    d.fecha_factura = self.getDate();
                }
            },
            columnDefs: [
                {
                    orderable: false,
                    searchable: false,
                    targets: [lastColNr]
                },
            ],
            columns: datatableColumns,
        });

        $(document).on("keyup", ".factura-filter", (event) => {
            //console.log(this.datatablePlanningRot.column($(event.currentTarget).attr("name")))
            let columnName = $(event.currentTarget).attr("name");
            let columnIndex = $('#tableOfFacturasCliente').DataTable().columns().eq(0).filter(function (index) {
                return $('#tableOfFacturasCliente').DataTable().column(index).dataSrc() === columnName;
            })[0];
            $('#tableOfFacturasCliente').DataTable().column(columnIndex).search($(event.currentTarget).val()).draw()
        })

        $(document).on("change", ".factura-filter-select", (event) => {
            let columnName = $(event.currentTarget).attr("name");
            let columnIndex = $('#tableOfFacturasCliente').DataTable().columns().eq(0).filter(function (index) {
                return $('#tableOfFacturasCliente').DataTable().column(index).dataSrc() === columnName;
            })[0];
            $('#tableOfFacturasCliente').DataTable().column(columnIndex).search($(event.currentTarget).val()).draw();
        });


        this.bsRangePickerRange.daterangepicker({
            ranges: {
                [window.language.datePicker.hoy]: [moment(), moment()],
                [window.language.datePicker.ayer]: [moment().subtract(1, 'days'), moment().subtract(1, 'days')],
                [window.language.datePicker.ultimos7]: [moment().subtract(6, 'days'), moment()],
                [window.language.datePicker.ultimos30]: [moment().subtract(29, 'days'), moment()],
                [window.language.datePicker.esteMes]: [moment().startOf('month'), moment().endOf('month')],
                [window.language.datePicker.ultimoMes]: [moment().subtract(1, 'month').startOf('month'), moment().subtract(1, 'month').endOf('month')]
            },
            opens: 'right',
            language: window.language.datePickerLocale,
            "locale": {
                "customRangeLabel": window.language.datePicker.rangoPersonalizado,
                "format": "YYYY-MM-DD",
                "separator": " ",
                "applyLabel": window.language.datePicker.aplicar,
                "cancelLabel": window.language.datePicker.limpiar,

            },
            "alwaysShowCalendars": true,
            autoUpdateInput: false,

        });

        this.bsRangePickerRange.on('apply.daterangepicker', function(ev, picker) {

            $(this).val(picker.startDate.format('DD/MM/YYYY') + ' ' + picker.endDate.format('DD/MM/YYYY'));
            let table = $('#tableOfFacturasCliente').DataTable();
            table.column(2).draw();
        });
    
        this.bsRangePickerRange.on('cancel.daterangepicker', function(ev, picker) {
            $(this).val('');
            $('#tableOfFacturasCliente').DataTable().column(2).search('').draw();
        });

        new Ajax('/facturas/getdatoscliente/'+ this.clienteId, 
            {}, 
            {},
            function (response) {
                AutoNumeric.getAutoNumericElement('#acumuladoFacturacion').set(response.total_facturacion);
                AutoNumeric.getAutoNumericElement('#totalPendientePago').set(response.total_pendiente);
            },
            function (error) {
                console.log("Error data:", error);
            }).get();
    }

    getDate() {

        let picker = this.bsRangePickerRange.data('daterangepicker');

        if (!picker || !picker.startDate || !picker.endDate || $('#fechaFactura').val() == '') {
            return '';
        }

        let startDate = picker.startDate.format('YYYY-MM-DD');
        let endDate = picker.endDate.format('YYYY-MM-DD');

        return startDate + "|" + endDate;

    }

    


}

export default ClienteFacturacion;