import Table from '../../components/table.js';
import Ajax from '../../components/ajax.js';



class Ticket {

    constructor() {

        // check if url includes "add"
        this.action = 'list';
        if (window.location.href.includes("add"))
            this.action = "add";
        else if (window.location.href.includes("edit"))
            this.action = "edit";

        this.table = null;

        this.init();
    }


    init() {

        if (this.action == "edit") {

            $('.gallery-img').on('click', function () {
                let imageUrl = $(this).data('src'); // Obtiene la URL de la imagen
                $('#modalImage').attr('src', imageUrl); // Cambia la imagen en el modal
                $('#imageModal').modal('show'); // Muestra el modal
            });

        }
        else if (this.action == "list") {
            this.#initDatatable();
        }
    }

    #initDatatable() {

        const self = this;

        self.#headerSearcher();

        const actions = ['view'];

        let columns = [];
        if (window.userType == 1) {
            columns = [
                { 'data': 'id' },
                {
                    'data': 'categoria_id',
                    render: function (data, type, row) {
                        return window.language.Tickets[row.categoria];
                    }
                },
                {
                    'data': 'seccion_id',
                    render: function (data, type, row) {
                        return window.language.Tickets[row.seccion];
                    }
                },
                {
                    'data': 'estado_id',
                    render: function (data, type, row) {
                        return window.language.Tickets[row.estado];
                    }
                },
                {
                    'data': 'prioridad',
                    render: function (data, type, row) {
                        return window.language.Tickets[data];
                    },
                },
                { 'data': 'titulo' },
                {
                    'data': 'usuario_id',
                    render: function (data, type, row) {
                        return row.usuario;
                    },
                },
                {
                    'data': 'user_soporte_id',
                    render: function (data, type, row) {
                        return row.user_soporte;
                    },
                },
                { 'data': 'created_at' },
            ];
        }
        else {
            columns = [
                { 'data': 'id' },
                {
                    'data': 'categoria_id',
                    render: function (data, type, row) {
                        return window.language.Tickets[row.categoria];
                    }
                },
                {
                    'data': 'seccion_id',
                    render: function (data, type, row) {
                        return window.language.Tickets[row.seccion];
                    }
                },
                {
                    'data': 'estado_id',
                    render: function (data, type, row) {
                        return window.language.Tickets[row.estado];
                    }
                },
                { 'data': 'titulo' },
                { 'data': 'created_at' },
            ];
        }


        this.table = new Table(
            $('#tableOfTickets'),
            'tickets',
            '/soporte/ticketlist',
            columns,
        );


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

        this.table.table.on('init.dt', function () {

            self.table.table.page.len(100).draw();
            self.table.table.draw();

        });

        this.table.setEditCallback(function (id) {
            window.location.href = '/soporte/edit/' + id;
        })
    }

    #headerSearcher() {
        const self = this;

        $('#tableOfTickets thead tr.search-header').remove();
        let searchRow = $('#tableOfTickets thead tr').first().clone(true);
        searchRow.addClass('search-header').appendTo('#tableOfTickets thead');

        $('#tableOfTickets thead tr:eq(1) th').each(function (i) {
            if (!$(this).hasClass("noFilter")) {
                var title = $(this).text();
                if (title == window.language.Tickets.fechaCreacion) {

                    $(this).html('<input id="bs-rangepicker-range" type="text" class="form-control " style="min-width:100px;max-width:120px;font-size:0.8rem !important;"  />');
                    var bsRangePickerRange = $('#bs-rangepicker-range')
                    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: $('html').attr('lang'),
                        "locale": {
                            "customRangeLabel": window.language.datePicker.personalizar,
                            "format": "YYYY-MM-DD",
                            "separator": " ",
                            "applyLabel": window.language.datePicker.aplicar,
                            "cancelLabel": window.language.datePicker.limpiar,

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

                    });

                    bsRangePickerRange.on('apply.daterangepicker', function (ev, picker) {
                        $(this).val(picker.startDate.format('YYYY-MM-DD') + ' ' + picker.endDate.format('YYYY-MM-DD'));
                        self.table.table
                            .column(i)
                            .search(this.value)
                            .draw();
                    });

                    bsRangePickerRange.on('cancel.daterangepicker', function (ev, picker) {
                        $(this).val('');
                        self.table.table
                            .column(i)
                            .search(this.value)
                            .draw();
                    });

                }
                else if (title == window.language.Tickets.tipo) {
                    // Agregar un selector en la tercera columna
                    $(this).html('<select class="form-control" style="min-width:100px;max-width:120px;font-size:0.8rem !important;"></select>');

                    // Agregar opciones al selector
                    var selectorTipo = $('select', this);
                    selectorTipo.append('<option value="">Todos</option>'); // Opción vacía
                    selectorTipo.append('<option value="errores">' + window.language.Tickets.errores + '</option>');
                    selectorTipo.append('<option value="consultas">' + window.language.Tickets.consultas + '</option>');
                    selectorTipo.append('<option value="sugerencias">' + window.language.Tickets.sugerencias + '</option>');

                    selectorTipo.on('change', function () {
                        var val = $.fn.dataTable.util.escapeRegex(
                            $(this).val()
                        );
                        self.table.table.column(i).search(val).draw();
                    });
                }

                else if (title == window.language.Tickets.seccion) {
                    // Agregar un selector en la tercera columna
                    $(this).html('<select class="form-control" style="min-width:100px;max-width:120px;font-size:0.8rem !important;"></select>');

                    // Agregar opciones al selector
                    var selectorSeccion = $('select', this);
                    selectorSeccion.append('<option value="">Todos</option>'); // Opción vacía
                    selectorSeccion.append('<option value="presupuestos">' + window.language.Tickets.presupuestos + '</option>');
                    selectorSeccion.append('<option value="pedidos">' + window.language.Tickets.pedidos + '</option>');
                    selectorSeccion.append('<option value="facturacion">' + window.language.Tickets.facturacion + '</option>');
                    selectorSeccion.append('<option value="logistica">' + window.language.Tickets.logistica + '</option>');
                    selectorSeccion.append('<option value="configuracion">' + window.language.Tickets.configuracion + '</option>');
                    selectorSeccion.append('<option value="general">' + window.language.Tickets.general + '</option>');

                    selectorSeccion.on('change', function () {
                        var val = $.fn.dataTable.util.escapeRegex(
                            $(this).val()
                        );
                        self.table.table.column(i).search(val).draw();
                    });
                }
                else if (title == window.language.Tickets.estado) {
                    // Agregar un selector en la tercera columna
                    $(this).html('<select class="form-control" style="min-width:100px;max-width:120px;font-size:0.8rem !important;"></select>');

                    // Agregar opciones al selector
                    var selectorEstado = $('select', this);
                    selectorEstado.append('<option value="">Todos</option>'); // Opción vacía
                    selectorEstado.append('<option value="abierto">' + window.language.Tickets.abierto + '</option>');
                    selectorEstado.append('<option value="en_proceso">' + window.language.Tickets.en_proceso + '</option>');
                    selectorEstado.append('<option value="resuelto">' + window.language.Tickets.resuelto + '</option>');

                    selectorEstado.on('change', function () {
                        var val = $.fn.dataTable.util.escapeRegex(
                            $(this).val()
                        );
                        self.table.table.column(i).search(val).draw();
                    });
                }
                else if (title == window.language.Tickets.prioridad) {
                    // Agregar un selector en la tercera columna
                    $(this).html('<select class="form-control" style="min-width:100px;max-width:120px;font-size:0.8rem !important;"></select>');

                    // Agregar opciones al selector
                    var selectorPrioridad = $('select', this);
                    selectorPrioridad.append('<option value="">Todos</option>'); // Opción vacía
                    selectorPrioridad.append('<option value="baja">' + window.language.Tickets.baja + '</option>');
                    selectorPrioridad.append('<option value="media">' + window.language.Tickets.media + '</option>');
                    selectorPrioridad.append('<option value="baja">' + window.language.Tickets.alta + '</option>');

                    selectorPrioridad.on('change', function () {
                        var val = $.fn.dataTable.util.escapeRegex(
                            $(this).val()
                        );
                        self.table.table.column(i).search(val).draw();
                    });
                }
                else {
                    $(this).html('<input type="text" class="form-control " style="min-width:100px;max-width:120px;font-size:0.8rem !important;"  />');

                    $('input', this).on('change clear', function () {
                        if (self.table.table.column(i).search() !== this.value) {
                            self.table.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: ['Tickets', 'datePicker'] }, {},
        function (translations) {
            window.language = JSON.parse(translations);
            new Ticket();
        },
        function (error) {
            console.log("Error getting translations:", error);
        }
    ).post();
});

export default Ticket;