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

class MessagesDatatable {
    constructor(domItem) {
        this.item = domItem
        this.datatableItem = this.item.find("#tableAllMessages")
        this.datatablePresupuestoMessageItem = this.item.find("#tablePresupuestoMessages")
        this.datatablePedidoMessageItem = this.item.find("#tablePedidoMessages")
        this.datatableFacturaMessageItem = this.item.find("#tableFacturaMessages")
        this.focusTable = this.datatableItem
        this.columnDefs = [
        ]
        this.datatableColumns = [
            { data: 'created_at', searchable: true, sortable: true },
            { data: 'updated_at', searchable: true, sortable: true },
            { data: 'title', name:"chats.title",searchable: true, sortable: true },
            { data: 'message', searchable: false, sortable: true },
            { data: 'creator', searchable: false, sortable: false },
            {
                data: 'viewed', searchable: false, sortable: true,
                render: (d, t) => {
                    const iconClass = d == true ? "ti ti-sm ti-check" : "ti ti-sm ti-x"
                    return `<span class="${iconClass}"</span>`
                }
            },
            {
                data: 'action', searchable: false, sortable: false,
                render: (d, t) => {
                    return `<div class="btn-group btn-group-sm">
                    <a href="/chat/${d.type}/${d.modelId}" class="message-edit" title="${d.lang.view_chat}"><i class="ti ti-eye ti-sm mx-2"></i></a>
                    ${d.isAdmin ?
                            `<div class="btn-group dropstart btn-group-sm">
                        <button data-id="${d.chatMessageId}" type="button" title="${d.lang.view_by_alt_message}" class="btn btn-icon rounded-pill dropdown-toggle hide-arrow text-primary btn-notification-viewed" data-bs-toggle="dropdown">
                        <i class="icon-base ti ti-messages"></i>
                        </button>
                        <ul class="dropdown-menu" id="dropdown-viewed-${d.chatMessageId}">
                        </ul>
                    </div>` : ""
                        }
                    </div>
                    `

                }
            }
        ]



    }
    init() {
        this.item.on('click', '.btn-notification-viewed', (event) => {
            const chatMessageId = $(event.currentTarget).data('id')
            this.focusTable.find(`#dropdown-viewed-${chatMessageId}`).empty()
            this.handleDropUp(chatMessageId)
        })

        this.datatable = this.datatableItem.DataTable({
            processing: true,
            order: [[1, 'desc']],
            columnDefs : this.columnDefs,
            orderCellsTop : true,
            layout: {
                topStart: 'pageLength',
                topEnd: 'search',
                bottomStart: 'info',
                bottomEnd: 'paging'
            },
            serverSide: true,
            pageLength: 10,
            language: {
                url: "/themes/vuexy/vendor/libs/datatables-sk/plugins/i18n/es-ES.json"
            },
            columns: this.datatableColumns,
            ajax: '/messages/datatable'
        });

        this.datatablePresupuestoMessage = this.datatablePresupuestoMessageItem.DataTable({
            processing: true,
            order: [[1, 'desc']],
            columnDefs : this.columnDefs,
            orderCellsTop : true,
            layout: {
                topStart: 'pageLength',
                topEnd: 'search',
                bottomStart: 'info',
                bottomEnd: 'paging'
            },
            serverSide: true,
            pageLength: 10,
            language: {
                url: "/themes/vuexy/vendor/libs/datatables-sk/plugins/i18n/es-ES.json"
            },
            columns: this.datatableColumns,
            ajax: '/messages/datatable/presupuesto'
        });
        this.datatablePedidoMessage = this.datatablePedidoMessageItem.DataTable({
            processing: true,
            orderCellsTop : true,
            columnDefs : this.columnDefs,
            order: [[1, 'desc']],
            layout: {
                topStart: 'pageLength',
                topEnd: 'search',
                bottomStart: 'info',
                bottomEnd: 'paging'
            },
            serverSide: true,
            pageLength: 10,
            language: {
                url: "/themes/vuexy/vendor/libs/datatables-sk/plugins/i18n/es-ES.json"
            },
            columns: this.datatableColumns,
            ajax: '/messages/datatable/pedido'
        });
        this.datatableFacturaMessage = this.datatableFacturaMessageItem.DataTable({
            processing: true,
            orderCellsTop : true,
            columnDefs : this.columnDefs,
            order: [[1, 'desc']],
            layout: {
                topStart: 'pageLength',
                topEnd: 'search',
                bottomStart: 'info',
                bottomEnd: 'paging'
            },
            serverSide: true,
            pageLength: 10,
            language: {
                url: "/themes/vuexy/vendor/libs/datatables-sk/plugins/i18n/es-ES.json"
            },
            columns: this.datatableColumns,
            ajax: '/messages/datatable/factura'
        });
        this.datatablePresupuestoMessageItem.on("keyup", ".datatable-message-filter", (event) => {
            let columnIndex = this.datatableColumns.findIndex((element) => element.data == $(event.currentTarget).attr("name"))
            this.datatablePresupuestoMessage.column(columnIndex).search($(event.currentTarget).val()).draw()
        })
        this.datatablePedidoMessageItem.on("keyup", ".datatable-message-filter", (event) => {
            let columnIndex = this.datatableColumns.findIndex((element) => element.data == $(event.currentTarget).attr("name"))
            this.datatablePedidoMessage.column(columnIndex).search($(event.currentTarget).val()).draw()
        })
        this.datatableFacturaMessageItem.on("keyup", ".datatable-message-filter", (event) => {
            let columnIndex = this.datatableColumns.findIndex((element) => element.data == $(event.currentTarget).attr("name"))
            this.datatableFacturaMessage.column(columnIndex).search($(event.currentTarget).val()).draw()
        })

    }

    handleDropUp(chatMessageId) {
        let ajax = new Ajax('/chat/users/message/notifications-unviewed/' + chatMessageId,
            null,
            null,
            this.handleDropUpSuccess.bind(this),
            this.handleDropUpError.bind(this)

        )
        ajax.get();
    }
    handleDropUpSuccess(response) {
        const chat_message_id = response.chat_message_id
        const notifications = response.data.notifications

        if (notifications.length > 0) {
            notifications.forEach(user => {
                if (user.userFullName || user.userName) {
                    console.log(user.userFullName)
                    this.focusTable.find(`#dropdown-viewed-${chat_message_id}`)
                        .append(this.addDropUpItem(user))
                }

            });
        }
    }
    handleDropUpError() { }
    addDropUpItem(user)
    {
        return `
            <li >
                <a type="button" class="d-flex flex-row justify-content-between align-items-center dropdown-item px-2 gap-2" href="javascript:void(0);"  >
                <span> ${user.userFullName ?? user.userName} </span>
                <span class="badge badge-center rounded-pill text-bg-${
                    user.viewed == 1 ? 'success' : 'danger'
                }">
                <i class="ti ti-xs ti-${
                    user.viewed == 1 ? 'eye-check' : 'eye-off'
                } "></i>
                </span>
                </a>
            </li>`;
    }

}

export default MessagesDatatable;