import Ajax from '../components/ajax.js'
import Modal from './modal.js'
import ClassSelect from './select2.js'
import { alertConfirmAction, alertConfirmationDelete, alertError, alertSuccess } from "./alerts/sweetAlert.js"


class Chat {
    constructor(domItem) {
        this.domItem = domItem
        this.chatList = this.domItem.find("#chat-list")
        this.chatHistory = this.domItem.find("#chat-conversation")
        this.modelId = this.domItem.data("id")
        this.chatHistoryBody = this.domItem.find(".chat-history-body")
        this.sendBtnMessageDepartment = this.domItem.find("#send-msg-btn-deparment")
        this.sendBtnMessageDepartmentClient = this.domItem.find("#send-msg-btn-deparment-client")
        this.sendBtnMessageInternal = this.domItem.find("#send-msg-btn-internal")
        this.chatSidebarLeftUserAbout = this.domItem.find('.chat-sidebar-left-user-about'),
            this.messageInput = this.domItem.find(".message-input")
        this.sideBar = this.domItem.find(".sidebar-body")
        this.selectItem = this.domItem.find(".chat-search-client")
        this.btnExitChat = this.domItem.find(".exit-chat")
        this.btnSubscribeChat = this.domItem.find(".subscribe-chat")

        this.chatDeparmentId = undefined
        this.searchInput = this.domItem.find(".chat-search-input")
        this.headers = {}
        this.chatContactsBody = this.domItem.find('.app-chat-contacts .sidebar-body')
        this.chatContactListItems = [].slice.call(
            document.querySelectorAll('.chat-contact-list-item:not(.chat-contact-list-item-title)')
        )
    }
    init() {

        if (this.searchInput.length) {
            this.searchInput.on('keyup', () => {
                const searchValue = this.searchInput.val(),
                    chatListItem0 = this.domItem.find('.chat-list-item-0'),
                    contactListItem0 = this.domItem.find('.contact-list-item-0'),
                    searchChatListItems = this.domItem.find('#chat-list li:not(.chat-contact-list-item-title)'),
                    searchContactListItems = this.domItem.find('#contact-list li:not(.chat-contact-list-item-title)');

                // Buscar en chats
                const chatListItemsCount = this._searchChatContacts(searchChatListItems, searchValue);
                // Mostrar u ocultar mensaje de "No se encontraron resultados" en chats
                if (chatListItem0.length) {
                    chatListItem0.toggleClass('d-none', chatListItemsCount === 0);
                }

                // Buscar en contactos
                const contactListItemsCount = this._searchChatContacts(searchContactListItems, searchValue);
                // Mostrar u ocultar mensaje de "No se encontraron resultados" en contactos
                if (contactListItem0.length) {
                    contactListItem0.toggleClass('d-none', contactListItemsCount === 0);
                }
            });
        }

        this.sendBtnMessageDepartment.addClass("d-none")
        this.btnExitChat.on('click', this._handleExitChatDepartment.bind(this))
        this.btnSubscribeChat.on('click', this._handleSubscribeChatDepartment.bind(this))

        this.sendBtnMessageInternal.addClass("d-none")
        if (this.chatContactsBody[0]) {
            this.scrollbarContacts = new PerfectScrollbar(this.chatContactsBody[0], {
                wheelPropagation: false,
                suppressScrollX: true,
            });
        }

        if (this.chatHistoryBody[0]) {
            this.scrollbarChatHistory = new PerfectScrollbar(this.chatHistoryBody[0], {
                wheelPropagation: false,
                suppressScrollX: true,

            });
        }
        if (this.chatHistoryBody.length) {
            this.chatHistoryBody.scrollTop(0,this.chatHistoryBody[0].scrollHeight);
        }
    }
    initDirectMessage() {

        this.chatType = "direct"
        this.modalNewParticipant = new Modal(this.domItem.find("#modalAddNewChatParticipant"))
        this.selectPlaceholder = {
            id: '0',
            text: "Seleccione un usuario"
        }
        this.btnUpdateMessagesUnviewed = this.domItem.find("#update-message-unviewed")
        this.btnDirectMessageSubmit = this.domItem.find("#send-msg-btn-direct")
        this.btnDirectMessageSubmit.on("click", this._handleStoreChatDirectMessage.bind(this))
        this.messageInput.on("keypress", this._sendDirectMessagePressKey.bind(this))

        this.selectParticipants = new ClassSelect(this.modalNewParticipant.item.find("#select-users"), `/chat/direct/users/select/${this.modelId}`, this.selectPlaceholder, true)
        this.authUserId = this.domItem.data("user-id")
        this.checkboxNotificationMessage = this.modalNewParticipant.item.find("#checkbox-notification-chat")

        this.btnAddParticipant = this.domItem.find("#btn-chat-add-participant")
        this.btnAddParticipantSubmit = this.domItem.find("#btn-chat-add-participant-submit")
        this.btnAddParticipantSubmit.on("click", this._handleStoreChatDirectUsers.bind(this))
        this.btnAddParticipant.on("click", () => {
            this.selectParticipants.init()
            this.modalNewParticipant.toggle()
        })

        this.selectParticipants.item.on("change", () => {
            if (this.selectParticipants.getVal().length > 0) {
                this.btnAddParticipantSubmit.removeClass("d-none")
            } else {
                this.btnAddParticipantSubmit.addClass("d-none")
            }
        })
        this.btnUpdateMessagesUnviewed.on("click", this._handleUpdateChatMessagesUnread.bind(this))
        this._handleGetChatDirect()
        setInterval(this._handleReloadChatDirectMessages.bind(this), 10000)
    }
    initSelectClient() {
        this.selectClientUser = new ClassSelect(
            this.selectItem, `/chat/direct/client/users/select/${this.chatType}/${this.modelId}`,
            "Seleccione contacto", true)

        this.selectClientUser.config.templateResult = (state) => {
            let $state = $(`
                <div class="d-flex flex-column justify-content-start align-items-start gap-1">
                <span class="item-text">${state.text}</span>
                <span class="badge text-bg-secondary">${state.desc ?? ''}</span>
                </div>`)
            return $state;
        }
        this.selectClientUser.init()
        this.selectItem.on('change', () => {
            if (this.selectClientUser.getVal()) {
                this.sendBtnMessageDepartment.attr('disabled', null)
            } else {
                this.sendBtnMessageDepartment.attr('disabled', 'disabled')
            }
        })

    }
    initGeneral() {
        this.chatType = "general"
        this._handleGetChatList()
        this.sendBtnMessageDepartment.on("click", this._sendMessage.bind(this))
        this.sendBtnMessageDepartmentClient.on("click", this._sendMessage.bind(this))

    }
    initPresupuesto() {
        this.chatType = "presupuesto"
        this._handleGetChatList()
        this.sendBtnMessageDepartment.on("click", this._sendMessage.bind(this))
        this.sendBtnMessageDepartmentClient.on("click", this._sendMessage.bind(this))
        this.scrollbarChatHistory.update()
        this.messageInput.on("keypress", this._sendMessagePressKey.bind(this))
        this.initSelectClient()
        // setInterval(this._getChatMessage.bind(this), 10000)



    }
    initPedido() {
        this.chatType = "pedido"
        this._handleGetChatList()
        this.sendBtnMessageDepartment.on("click", this._sendMessage.bind(this))
        this.sendBtnMessageDepartmentClient.on("click", this._sendMessage.bind(this))
        this.messageInput.on("keypress", this._sendMessagePressKey.bind(this))
        this.initSelectClient()
        // setInterval(this._getChatMessage.bind(this), 10000)



    }
    initFactura() {
        this.chatType = "factura"
        this._handleGetChatList()
        this.sendBtnMessageDepartment.on("click", this._sendMessage.bind(this))
        this.sendBtnMessageDepartmentClient.on("click", this._sendMessage.bind(this))
        this.messageInput.on("keypress", this._sendMessagePressKey.bind(this))
        this.initSelectClient()
        // setInterval(this._getChatMessage.bind(this), 10000)
    }
    initOrdenTrabajo() {
        this.chatType = "ot"
        this._handleGetChatList()
        this.sendBtnMessageDepartment.on("click", this._sendMessage.bind(this))
        this.sendBtnMessageDepartmentClient.on("click", this._sendMessage.bind(this))
        this.messageInput.on("keypress", this._sendMessagePressKey.bind(this))
        this.initSelectClient()
        // setInterval(this._getChatMessage.bind(this), 10000)
    }
    initContacts() {
        this.chatType = "internal"

    }

    _searchChatContacts(searchListItems, searchValue) {
        let searchListItemsCount = 0;
        searchListItems.each(function () {
            const searchListItemText = $(this).text().toLowerCase();
            const matchesSearch = searchListItemText.indexOf(searchValue) !== -1;

            $(this).toggleClass('d-flex', matchesSearch);
            $(this).toggleClass('d-none', !matchesSearch);

            if (matchesSearch) {
                searchListItemsCount++;
            }
        });

        return searchListItemsCount;
    }
    _setBtnInternal() {
        this.sendBtnMessageInternal.removeClass("d-none")
        this.sendBtnMessageDepartment.addClass("d-none")
    }
    _setBtnDeparment() {
        this.sendBtnMessageDepartment.removeClass("d-none")
        this.sendBtnMessageInternal.addClass("d-none")
    }

    /**============================================
     *               PRESUPUESTOS
     *=============================================**/
    _handleGetChatList(event) {
        this.domItem.find(".chat-loader").removeClass("d-none")
        let ajax = new Ajax(
            `/chat/departments/${this.chatType}/${this.modelId}`,
            null,
            null,
            this._handleGetChatListSuccess.bind(this),
            this._handleGetChatListError.bind(this),
        );
        ajax.get();
    }
    _handleGetChatListSuccess(data) {
        this.domItem.find(".chat-loader").addClass("d-none")
        Object.values(data).map(row => {
            this.chatList.append(this._getContact(row))
            this.chatDeparmentId = row.id
            this.chatList.find(`#chat_${row.name}`).on("click", (event) => {
                $(".chat-contact-list-item").removeClass("active")
                $(event.currentTarget).parent().addClass("active")
                this.chatHistory.empty()
                this.chatDeparmentId = this.chatList.find(`#chat_${row.name}`).data("id")
                this.domItem.find(".chat-history-header div.chat-contact-info h6").text(row.display)
                this.domItem.find(".chat-history-header div.chat-contact-info small.user-status").text(row.display)
                this._getChatMessage()
                this._getChatDeparmentUsers()

            })

        })
        if (Object.values(data)) {
            const firstDepartment = Object.values(data)[0]
            this.chatList.find(`#chat_${firstDepartment.name}`).trigger("click");
        }
    }
    _handleGetChatListError(error) {
        console.error(error)
    }
    _getChatDeparmentUsers() {
        this.domItem.find("#chat-header-users").empty()
        this.domItem.find("#chat-header-dropdown-users").removeClass("d-none")
        let ajax = new Ajax(
            `/chat/department/users/${this.chatType}/${this.chatDeparmentId}/${this.modelId}`,
            null,
            null,
            this._getChatDeparmentUsersSuccess.bind(this),
            this._getChatDeparmentUsersError.bind(this),

        )
        ajax.get()
    }
    _getChatDeparmentUsersSuccess(deparmentUsers) {
        deparmentUsers.adminUsers.map(user => this.appendChatDepartmentUser(user))
        deparmentUsers.externalUsers.map(user => this.appendChatDepartmentUser(user, 'warning', 'user'))

    }
    appendChatDepartmentUser(user, color = "primary", icon = "user") {
        this.domItem.find("#chat-header-users").append(
            `
            <li class="chat-contact-list-item p-1">
                <div class="d-flex align-items-center  py-1"
                    id="chat-contact-list-item-${user.id}">

                    <div class="avatar avatar-md px-2 py-2">
                        <img src="https://gravatar.com/avatar/${user.avatar}?s=40" class="rounded-circle"></img>
                    </div>
                    <div class="chat-contact-info flex-grow-1 ms-2">
                        <h6 class="chat-contact-name text-truncate m-0">${user?.first_name ?? "" + " " +
            user?.last_name ?? ""}</h6>
                        <p class="chat-contact-status text-muted text-truncate mb-0">
                            ${user.username}
                        </p>
                    </div>
                </div>
                </li>

        `
        )
    }
    _getChatDeparmentUsersError(err) { }

    _getContact(row) {
        let chat = `
                <li class="chat-contact-list-item">
                    <a class="d-flex align-items-center" id="chat_${row.name}" data-id="${row.id}">
                        <div class="flex-shrink-0 avatar">
                            <span class="avatar-initial rounded-circle bg-label-success">${row.display.charAt(0)}</span>
                        </div>
                        <div class="chat-contact-info flex-grow-1 ms-2">
                            <h6 class="chat-contact-name text-truncate m-0">${row.display}</h6>
                            <p class="chat-contact-status text-muted text-truncate mb-0">
                                ${row.display}
                            </p>
                        </div>
                    <span class="badge badge-center rounded-pill bg-secondary messages-unread-contact">${row.countMessages}</span>
                    </a>
                </li>
        `
        return chat
    }
    _getChatTotalMessages(row_name) {
        let ajax = new Ajax(
            `/chat/department/${this.chatType}/${this.chatDeparmentId}/${this.modelId}`,
            null,
            null,
            (data) => {

            },
            null


        );
        ajax.get();
    }
    _getChatDepartmentMessageCount() {
        let ajax = new Ajax(
            `/chat/department/count/${this.chatType}/${this.chatDeparmentId}/${this.modelId}`,
            null,
            null,
            this._getChatDepartmentMessageCountSuccess.bind(this),
            this._getChatDepartmentMessageCountError.bind(this),


        );
        ajax.get();
    }
    _getChatDepartmentMessageCountSuccess(data) {
        this.domItem.find(`chat_${data.name}`).find(".messages-unread-contact").text(data.count)
    }
    _getChatDepartmentMessageCountError() { }

    _getChatMessage() {
        this.chatHistory.empty()
        this.domItem.find(".chat-loader").removeClass("d-none")
        let ajax = new Ajax(
            `/chat/department/${this.chatType}/${this.chatDeparmentId}/${this.modelId}`,
            null,
            null,
            this._getChatMessageSuccess.bind(this),
            this._getChatMessageError.bind(this),


        );
        ajax.get();
    }
    _getChatMessageSuccess(data) {
        this.domItem.find(".chat-loader").addClass("d-none")
        this._setBtnDeparment()
        this.chatList.find(`#chat_${data.department.name} .messages-unread-contact`).text(data.count ?? 0)
        if (data.messages) {
            data.messages.map((m) => {
                this._addChatMessage(m)
            })
        }
    }
    _getChatMessageError(err) {
        console.log(err)

    }
    _addChatMessage(chatMessage, pos = "left") {
        let chatItem = `
    <li class="chat-message chat-message-${chatMessage.pos}">
        <div class="d-flex overflow-hidden">
            <div class="chat-message-wrapper flex-grow-1">

                <div class="chat-message-text">
                    <p class="mb-0">${chatMessage?.message}</p>
                </div>
                <div class="text-${chatMessage?.pos == "left" ? "start" : "end"} text-muted mt-1">
                    <div class="text-${chatMessage?.pos == "left" ? "start" : "end"} text-muted mt-1">
                        <small>${chatMessage?.user?.first_name + " " + chatMessage?.user?.last_name}</small>
                    </div>
                    <i class="ti ${chatMessage?.viewed == 1 ? "ti-checks" : "ti-check"} ti-xs me-1 text-success"></i>
                    <small>${chatMessage.created_at}</small>
                </div>

            </div>
            <div class="user-avatar flex-shrink-0 ms-3">
                 <div class="avatar avatar-md px-2 py-2">
                        <img src="https://gravatar.com/avatar/${chatMessage.user.avatar}?s=40" class="rounded-circle"></img>
                </div>
            </div>
        </div>
    </li>
        `
        this.chatHistory.append(chatItem)
        return chatItem
    }
    _addChatDirectMessages(chatMessage) {
        let chatItem = `
    <li class="chat-message chat-message-${chatMessage.pos}">
        <div class="d-flex overflow-hidden">
            <div class="chat-message-wrapper flex-grow-1">

                <div class="chat-message-text">
                    <p class="mb-0">${chatMessage?.message}</p>
                </div>
                <div class="text-${chatMessage?.pos == "left" ? "start" : "end"} text-muted mt-1">
                    <div class="text-${chatMessage?.pos == "left" ? "start" : "end"} text-muted mt-1">
                        <i class="ti me-1"></i>
                        <small>${chatMessage?.sender_first_name + " " + chatMessage?.sender_last_name}</small>
                    </div>
                    <i class="ti ${chatMessage?.viewed == "1" ? "ti-checks" : "ti-check"} ti-xs me-1 text-success"></i>
                    <small>${chatMessage.created_at}</small>
                </div>

            </div>
            <div class="user-avatar flex-shrink-0 ms-3">
                <div class="avatar avatar-sm">
                    <span class="avatar-initial rounded-circle bg-label-primary">${chatMessage?.sender_first_name.charAt(0) + chatMessage?.sender_last_name.charAt(0)}</span>
                </div>
            </div>
        </div>
    </li>
        `
        this.chatHistory.append(chatItem)
        return chatItem
    }
    _sendMessagePressKey(e) {
        if (e.which == 13) {
            e.preventDefault();
            this._sendMessage()
        }

    }
    _sendDirectMessagePressKey(e) {
        if (e.which == 13) {
            e.preventDefault();
            this._handleStoreChatDirectMessage()
        }

    }
    _sendMessage() {

        let messageText = this.messageInput.val()
        const body = {
            message: messageText,
            chat_department_id: this.chatDeparmentId,
            user: this.userId,
            client: this.selectClientUser.getVal() ?? null,
            model_id: this.modelId
        }
        if (messageText) {
            let ajax = new Ajax(
                `/chat/message/${this.chatType}`,
                body,
                null,
                this._sendMessageSuccess.bind(this),
                this._sendMessageError.bind(this),

            );
            ajax.post();
        }
    }
    _sendMessageSuccess(data) {
        this.messageInput.val("")
        this._getChatMessage(this.chatDeparmentId)
        this._getChatDeparmentUsers()
    }
    _sendMessageError(err) {
        console.error(err)
    }
    _handleListContacts() {
        this.sideBar.find("#contact-list").removeClass("d-none")
        this.sendBtnMessageInternal.on("click", this._sendMessageInternal.bind(this))
        this.sendBtnMessageInternal.on("keypress", this._sendMessageInternalPressKey.bind(this))
        let ajax = new Ajax(
            "/chat/contacts",
            null,
            null,
            this._handleListContactsSuccess.bind(this),
            this._handleListContactsError.bind(this)

        )
        ajax.get()

    }
    _handleListContactsSuccess(contacts) {
        try {

            if (contacts.length) {

                contacts.map((c, index) => {
                    this._addContactToList(c)

                });
            } else {
                this.sideBar.find("#contact-list").addClass("d-none")
            }
            this.sideBar.find(".contact-chat").on("click", (e) => {
                // $(e.currentTarget).find(".messages-unread-contact").empty()
                $(".contact-chat").parent().removeClass("active")
                $(".chat-contact-list-item").removeClass("active")
                this.chatHistory.empty()
                this.domItem.find("#chat-header-dropdown-users").addClass("d-none")
                let userId = $(e.currentTarget).data("id")
                $(e.currentTarget).parent().addClass('active')
                this.receiverId = userId
                this._handleGetSingleContact(userId)
                this._setBtnInternal()
            })
        } catch (error) {

        } finally {
            this.domItem.find(`#chat-contact-list-item-${contacts[0].id}`).click()

        }
    }
    _handleListContactsError(err) {
        console.error(err)
    }
    _handleGetSingleContact(userId) {
        let ajax = new Ajax(
            `/chat/contacts/${userId}`,
            null,
            null,
            this._handleGetSingleContactSuccess.bind(this),
            this._handleGetSingleContactError.bind(this),
        )
        ajax.get()
    }

    _handleGetSingleContactSuccess(contact) {
        this.domItem.find(".chat-history-header div.chat-contact-info h6").text([contact.first_name, contact.last_name].join(" "))
        this.domItem.find(".chat-history-header div.chat-contact-info small.user-status").text(contact.username)
        let ajax = new Ajax(
            `/chat/contact/${contact.id}/messages`,
            null,
            null,
            this._handleGetSingleContactMessagesSuccess.bind(this),
            this._handleGetSingleContactMessagesError.bind(this)
        )
        ajax.get()
    }
    _handleGetSingleContactMessagesSuccess(data) {
        try {
            if (data) {
                data.map((m) => {
                    this._addChatMessage(m)
                })
            }
        } catch (error) {

        } finally {
            // console.log(this.chatHistoryBody[0].scrollTop)
            this.scrollbarChatHistory.update()
            this.chatHistoryBody[0].scrollTop = this.scrollbarChatHistory.containerHeight
        }
    }
    _handleGetSingleContactMessagesError(err) { }

    _handleGetSingleContactError(err) {

    }
    _sendMessageInternalPressKey(e) {
        if (e.which == 13) {
            e.preventDefault();
            this._sendMessageInternal()
        }
    }
    _sendMessageInternal() {
        let messageText = this.messageInput.val()
        const body = {
            message: messageText,
            receiver_id: this.receiverId,
        }
        if (messageText) {
            let ajax = new Ajax(
                `/chat/message/internal`,
                body,
                null,
                this._sendMessageInternalSuccess.bind(this),
                this._sendMessageInternalError.bind(this),

            );
            ajax.post();
        }
    }
    _sendMessageInternalSuccess(message) {
        this.messageInput.val("")
        this.chatHistory.empty()
        this._handleGetSingleContact(this.receiverId)
    }
    _sendMessageInternalError(err) {
        console.error(err)
    }
    _addContactToList(contact) {

        let contactItem =
            `
        <li class="chat-contact-list-item">
            <a class="d-flex align-items-center contact-chat" data-id="${contact.id}"
                id="chat-contact-list-item-${contact.id}">
                <div class="avatar d-block flex-shrink-0">
                    <span class="avatar-initial rounded-circle bg-label-primary">
                        ${contact?.first_name?.charAt(0) ?? "?"
            + contact?.last_name?.charAt(0) ?? "?"}</span>

                </div>
                <div class="chat-contact-info flex-grow-1 ms-2">
                    <h6 class="chat-contact-name text-truncate m-0">${contact?.first_name ?? "" + " " +
            contact?.last_name ?? ""}</h6>
                    <p class="chat-contact-status text-muted text-truncate mb-0">
                    ${contact?.cliente_id ? "[CLIENTE]" : ""}${contact.username}
                    </p>
                </div>
                ${contact.unreadMessages ? `<span
                    class="badge badge-center rounded-pill bg-secondary messages-unread-contact">${contact.unreadMessages}</span>` : ""}
            </a>
        </li>
        `

        if (contact.first_name || contact.last_name) {
            this.sideBar.find("#contact-list").append(contactItem)
        }
    }
    _addParticipantToList(contact) {
        let contactItem =
            `
        <li class="chat-contact-list-item ${this.authUserId == contact.id ? "active" : ""}">
            <div class="d-flex align-items-center contact-chat" data-id="${contact.id}"
                id="chat-contact-list-item-${contact.id}">
                <div class="avatar d-block flex-shrink-0">
                    <span class="avatar-initial rounded-circle bg-label-primary">
                        ${contact?.first_name?.charAt(0) ?? "?"
            + contact?.last_name?.charAt(0) ?? "?"}</span>

                </div>
                <div class="chat-contact-info flex-grow-1 ms-2">
                    <h6 class="chat-contact-name text-truncate m-0">${contact?.first_name ?? "" + " " +
            contact?.last_name ?? ""}</h6>
                    <p class="chat-contact-status text-muted text-truncate mb-0">
                    ${contact?.cliente_id ? "[CLIENTE]" : ""}${contact.username}
                    </p>
                </div>
            </div>
        </li>
        `

        if (contact.first_name || contact.last_name) {
            this.sideBar.find("#contact-list").append(contactItem)
        }
    }
    _handleGetChatDirect() {
        const ajax = new Ajax(
            `/chat/${this.chatType}/conversation/${this.modelId}`,
            null,
            null,
            this._handleGetChatDirectSuccess.bind(this),
            this._handleGetChatDirectError.bind(this)
        )
        ajax.get()
    }

    _handleGetChatDirectSuccess(response) {
        const { chat, users, messages } = response
        if (users.length > 0) {
            users.map(c => this._addParticipantToList(c))
        }
        if (messages.length > 0) {
            messages.map(m => this._addChatDirectMessages(m))
        }
        this.domItem.find("#chat-direct-title").text(chat.title)
        this.domItem.find(".chat-loader").addClass("d-none")
    }
    _handleGetChatDirectError(error) { }
    _handleReloadChatDirectMessages() {
        const ajax = new Ajax(
            `/chat/${this.chatType}/conversation/${this.modelId}`,
            null,
            null,
            this._handleReloadChatDirectMessagesSuccess.bind(this),
            this._handleReloadChatDirectMessagesError.bind(this)
        )
        ajax.get()
    }
    _handleReloadChatDirectMessagesSuccess(response) {
        const { chat, users, messages } = response
        this.chatHistory.empty()

        if (messages.length > 0) {
            messages.map(m => this._addChatDirectMessages(m))
        }
        this.domItem.find("#chat-direct-title").text(chat.title)
        this.domItem.find(".chat-loader").addClass("d-none")
    }
    _handleReloadChatDirectMessagesError(error) { }
    _handleStoreChatDirectUsers() {
        const data = { "users": this.selectParticipants.getVal(), "notification": this.checkboxNotificationMessage.prop("checked") }
        this.domItem.find(".chat-loader").removeClass("d-none")

        const ajax = new Ajax(
            `/chat/${this.chatType}/users/${this.modelId}`,
            data,
            null,
            this._handleStoreChatDirectUsersSuccess.bind(this),
            this._handleStoreChatDirectUsersError.bind(this)
        )
        ajax.post()
    }
    _handleStoreChatDirectUsersSuccess(response) {
        this.domItem.find(".chat-loader").removeClass("d-none")
        this.chatHistory.empty()
        this.sideBar.find("#contact-list").empty()
        this.modalNewParticipant.toggle()
        this._handleGetChatDirect()
        this.selectParticipants.reset()
    }
    _handleStoreChatDirectUsersError() {
        this.domItem.find(".chat-loader").removeClass("d-none")
    }
    _handleStoreChatDirectMessage() {
        const data = { "message": this.messageInput.val(), "chat_id": this.modelId }
        if (data.message) {
            const ajax = new Ajax(
                `/chat/${this.chatType}/messages/${this.modelId}`,
                data,
                null,
                this._handleStoreChatDirectMessageSuccess.bind(this),
                this._handleStoreChatDirectMessageError.bind(this)
            )
            ajax.post()
        }
    }
    _handleStoreChatDirectMessageSuccess(response) {
        try {
            let message = response
            this._addChatDirectMessages(message)
            this.messageInput.val("")
        } catch (error) {

        } finally {
            this.scrollbarChatHistory.update()
            this.chatHistoryBody[0].scrollTop = this.scrollbarChatHistory.containerHeight
        }

    }
    _handleStoreChatDirectMessageError(error) { }

    _handleUpdateChatMessagesUnread() {
        const ajax = new Ajax(
            `/chat/${this.chatType}/messages/unread/${this.modelId}`,
            null,
            null,
            this._handleUpdateChatMessagesUnreadSuccess.bind(this),
            this._handleUpdateChatMessagesUnreadError.bind(this)
        )
        ajax.post()
    }
    _handleUpdateChatMessagesUnreadSuccess() {
        this._handleReloadChatDirectMessages();
    }
    _handleUpdateChatMessagesUnreadError() { }
    _handleRequestExitChatDeparment() {
        const ajax = new Ajax('/chat/department/user/' + this.chatDeparmentId,
            {
                model_fk: this.chatType + "_id",
                model_id_fk: this.modelId
            },
            null,
            (response) => {
                if (response.status) {
                    alertSuccess(response.message).fire()
                    this._getChatDeparmentUsers()
                } else {
                    alertError(response.message).fire()
                }
            },
            (error) => {
                alertError("Error")
            }

        )
        ajax.delete();
    }
    _handleRequestSubscribeChatDeparment() {
        const ajax = new Ajax('/chat/department/user',
            {
                chat_department_id: this.chatDeparmentId,
                model_fk: this.chatType + "_id",
                model_id_fk: this.modelId
            },
            null,
            (response) => {
                if (response.status) {
                    alertSuccess(response.message).fire()
                    this._getChatDeparmentUsers()
                } else {
                    alertError(response.message).fire()
                }
            },
            (error) => {
                alertError("Error")
            }

        )
        ajax.post();
    }
    _handleExitChatDepartment() {
        if (this.chatDeparmentId) {
            alertConfirmationDelete('¿Estás seguro de salir de la conversación?').then((result) => {
                if (result.isConfirmed) {
                    this._handleRequestExitChatDeparment()
                }
            })
        }
    }
    _handleSubscribeChatDepartment() {
        if (this.chatDeparmentId) {
            alertConfirmAction('¿Estás seguro de subscribirte al chat?').then((result) => {
                if (result.isConfirmed) {
                    this._handleRequestSubscribeChatDeparment()
                }
            })
        }
    }







}

const addInternalNotification = (e) => {
    let numberOfMessages = e.unreadMessages
    if (numberOfMessages > 0) {
        $("#chat-notification-list").append(
            `
        <li class="mb-2">
            <a href="${e.uri}" class="d-flex align-items-center flex-grow">
                <div class="avatar d-block flex-shrink-0">
                    <span class="avatar-initial rounded-circle bg-label-primary">${e.avatar}</span>
                </div>
                <div class="chat-contact-info flex-grow-1 ms-2">
                    <h6 class="chat-contact-name text-truncate m-0">[${e.title}] ${e.chatDisplay}</h6>
                </div>
                <span class="badge badge-center rounded-pill bg-primary p-1 m-2">${numberOfMessages}</span>
            </a>
        </li>
                    `
        )
    }
}
const addDepartmentNotification = (e) => {
    let numberOfMessages = e.unreadMessages
    if (numberOfMessages > 0) {
        $("#chat-notification-list").append(
            `
        <li class="mb-2">
            <a href="${e.uri}" class="d-flex align-items-center flex-grow">
                <div class="avatar d-block flex-shrink-0">
                    <span class="avatar-initial rounded-circle bg-label-primary">${e.avatar}</span>
                </div>
                <div class="chat-contact-info flex-grow-1 ms-2">
                    <h6 class="chat-contact-name text-truncate m-0">[${e.title}] ${e.chatDisplay}</h6>
                </div>
                <span class="badge badge-center rounded-pill bg-primary p-1 m-2">${numberOfMessages}</span>
            </a>
        </li>
                    `
        )
    }
}

const addNotificationsToDom = (data) => {
    $("#chat-notification-list").empty()
    if (data.totalMessages > 0) {
        $("#chat-message-notification-title").addClass("d-none")
        $("#chat-notification-number").removeClass("d-none")
        $("#chat-notification-number").text(data.totalMessages ?? 0)
    } else {
        $("#chat-message-notification-title").removeClass("d-none")
        $("#chat-notification-number").addClass("d-none")
        $("#chat-notification-number").text(0)
    }
    data.departmentNotifications?.map(e => {
        addDepartmentNotification(e)
    }
    )
    data.internalNotifications?.map(e => {
        addInternalNotification(e)
    }
    )

}
export const showNotificationMessages = () => {
    let ajax = new Ajax(
        '/chat/notifications',
        null,
        null,
        addNotificationsToDom,
        (err) => { }
    )
    ajax.get()
}
export default Chat


