var divHeight = 0; var scrollPosition = 0; var scrollStart = 0; var chatDiv; let qtdMsg = 0; var offsetMessage = 0; $(document).ready(() => { addEventSelectChat(); $('.footer-write').on('click', function () { if ($('.chatSelected').length > 0) { var $this = $(this); var range = document.createRange(); var sel = window.getSelection(); range.setStart($this[0], 0); range.collapse(true); sel.removeAllRanges(); sel.addRange(range); $this.focus(); } }); }) function addEventSelectChat() { $('body').on('click', '.selectChat', e => { const chatData = e.target; const chatId = chatData.getAttribute('data-id'); const chatType = chatData.getAttribute('data-type'); let chatSelected = document.querySelector('.chatSelected'); if ((chatType !== $(chatSelected).data('type'))) { changeChat(chatId, chatType); messageViewed(chatId, chatType); } else { if (($(chatSelected).data('id') > 0 && chatId > 0) && ($(chatSelected).data('id') != chatId)) { changeChat(chatId, chatType); messageViewed(chatId, chatType); } } }) chatDiv = document.querySelector('.body-message'); } function changeChat(chatId, chatType, showNotification = false) { offsetMessage = 0; const receiver = receiverData(chatId, chatType); changeChatName(receiver); changeChatPicture(receiver); saveChat(chatId, chatType); styleChatSelected(chatId, chatType); loadMessages(chatId, chatType, showNotification); hiddenNewMensagemInChat(); existsNotification(); setTimeout(() => verificaMensagensNovas(), 1000); $('.footer-write').focus(); } function changeChatPicture(receiver) { $('#userPick') .attr('src', receiver.picture) .attr('onclick', "FileModal('" + receiver.picture + "')"); } function styleChatSelected(chatId, chatType) { $('.selectChat').removeClass('chatSelected'); if (chatType == 'user') $(`#user-${chatId}`).addClass('chatSelected'); if (chatType == 'departament') $(`#departament-${chatId}`).addClass('chatSelected'); if (chatType == 'mural') $('#mural-1').addClass('chatSelected'); if (chatType == 'bot') { $('#chatbot').addClass('chatSelected'); $('.body-footer').css({ 'pointer-events': 'none', 'opacity': '0.6' }); return; } $('.body-footer').css({ 'pointer-events': 'auto', 'opacity': '1' }); } function changeChatName(receiver) { document.querySelector('#chatName').innerHTML = receiver.name[0].toUpperCase() + receiver.name.slice(1, receiver.name.length); // placeholder chat $('.footer-write').html(''); $(".footer-write").attr("data-placeholder", `Envie uma mensagem para ${receiver.name}`); } function removeNotification(chatId, chatType) { try { if (chatType == 'user') $(`.userNotification-${chatId}, .user-${chatId}-unread-notification`).remove(); if (chatType == 'departament') $(`.departamentNotification-${chatId}, .departament-${chatId}-unread-notification`).remove(); if (chatType == 'mural') $(`.muralNotification, .mural-1-unread-notification`).remove(); if (chatType == 'bot') setTimeout(() => $(`.botNotification`).remove(), 1000); } catch (error) { } } function defaultScroll(novaMensagem) { if (novaMensagem) hiddenNewMensagemInChat(); chatDiv.scrollTop = chatDiv.scrollHeight; } function receiverData(receiverId, chatType) { let tableName; if (chatType == 'user') tableName = 'usuario'; else if (chatType == 'departament') tableName = 'departamento'; else if (chatType == 'bot') tableName = 'bot'; else tableName = 'mural'; // mural if (tableName == 'mural') { RECEIVER_DATA.id = null; RECEIVER_DATA.picture = DEFAULT_PICTURE; RECEIVER_DATA.name = "Mural"; return RECEIVER_DATA; } // dotsbot if (tableName == 'bot') { RECEIVER_DATA.id = 0; RECEIVER_DATA.picture = DEFAULT_PICTURE; RECEIVER_DATA.name = "DotsBot"; return RECEIVER_DATA; } // usuario ou departamento _GET('/App/Controller/Query/get.controller.php', { table_name: tableName, condition: ` AND id = ${receiverId}` }).done(data => { const response = JSON.parse(data); RECEIVER_DATA.id = response[0].id; RECEIVER_DATA.name = response[0].apelido || response[0].nome; RECEIVER_DATA.picture = response[0].src_foto ? URL_ARQUIVOS + '/' + response[0].src_foto : DEFAULT_PICTURE; }) return RECEIVER_DATA; } function saveChat(chatId, chatType) { localStorage.setItem('openChat', JSON.stringify({ chatId, chatType })); } function loadMessagesScroll(chatId, chatType, callback) { let pointerPositionScroll; const formData = new FormData(); if (chatType == 'user') formData.append('idDestinatario', RECEIVER_DATA.id); else if (chatType == 'departament') formData.append('idDepartamento', RECEIVER_DATA.id); // mensagens enviadas pelo chatbot else if (chatType == 'bot') formData.append('idDestinatario', SENDER_DATA.id); // mensagens normais else formData.append('idRemetente', SENDER_DATA.id); // remetente if (chatType == 'bot') formData.append('idRemetente', '-1'); else formData.append('idRemetente', SENDER_DATA.id); formData.append('scroll', offsetMessage); fetch(`${URL_BASE}App/Controller/Chat/MessageAPI.php`, { method: 'POST', body: formData }) .then(req => req.json()) .then(messages => { const messagesData = messages.message; const amountMessages = messages.amountMessage; if (messages.message.length == 0) pointerPositionScroll = false; else pointerPositionScroll = true; processMessages(messagesData, true, false) .then((result) => { createDateMessageV2(result); }) .catch((error) => { console.error("Error processing messages:", error); }); // notification amountMessages.forEach(message => { let chatType; if (message.remetente == '-1') chatType = 'bot'; else if (message.remetente && message.destinatario) chatType = 'user'; else if (message.remetente && message.departamento) chatType = 'departament'; else if (!message.destinatario && !message.departamento) chatType = 'mural'; const messageData = { chatType, sender: { id: message.remetente }, receiver: { id: message.destinatario ? message.destinatario : message.departamento } } }) }).finally(() => { offsetMessage += 20; callback(pointerPositionScroll); }); } // Loop assíncrono para processar mensagens async function processMessages(messagesData, createData = true, positionScroll = false) { let childType; if (createData) childType = 'prepend'; else childType = 'append'; let dateArray = []; for (const [key, message] of messagesData.entries()) { const dateSplit = message.data_envio.split(' '); if (!dateArray.includes(dateSplit[0])) dateArray.push(dateSplit[0]); let nextKey = key + 1; let nextMessage = messagesData[nextKey]; if ((!nextMessage) || (nextMessage.id_remetente !== message.id_remetente)) { message.printPicture = true; } else { message.printPicture = false; } let messageData; if (createData) { messageData = createMessageData(message); } else { messageData = message; } await fillMessages(messageData, childType); if (positionScroll) defaultScroll(); } let object = { child_type: childType, date_array: dateArray, qtd_msg: messagesData.length } return object; } function loadMessages(chatId, chatType, showNotification = false) { $('body').off('click', '.selectChat'); document.querySelector('.body-message').innerHTML = ''; const formData = new FormData(); if (chatType == 'user') formData.append('idDestinatario', RECEIVER_DATA.id); else if (chatType == 'departament') formData.append('idDepartamento', RECEIVER_DATA.id); // mensagens enviadas pelo chatbot else if (chatType == 'bot') formData.append('idDestinatario', SENDER_DATA.id); // mensagens normais else formData.append('idRemetente', SENDER_DATA.id); // remetente if (chatType == 'bot') formData.append('idRemetente', '-1'); else formData.append('idRemetente', SENDER_DATA.id); formData.append('scroll', offsetMessage); fetch(`${URL_BASE}App/Controller/Chat/MessageAPI.php`, { method: 'POST', body: formData }) .then(req => req.json()) .then(messages => { const messagesData = messages.message; const amountMessages = messages.amountMessage; processMessages(messagesData, true, true) .then((result) => { createDateMessageV2(result); setTimeout(() => { qtdMsg = result.qtd_msg; chatDiv.scrollTop = chatDiv.scrollHeight; $('.body-message').css({ 'opacity': '1' }); }, 200); }) .catch((error) => { console.error("Error processing messages:", error); }); // notification amountMessages.forEach(message => { let chatType; if (message.remetente == '-1') chatType = 'bot'; else if (message.remetente && message.destinatario) chatType = 'user'; else if (message.remetente && message.departamento) chatType = 'departament'; else if (!message.destinatario && !message.departamento) chatType = 'mural'; const messageData = { chatType, sender: { id: message.remetente }, receiver: { id: message.destinatario ? message.destinatario : message.departamento } } if (showNotification) showNotificationNewMessage(messageData); }) }).finally(() => { let elapsedTime = 0; const maxTime = 10000; let Time = setInterval(function () { elapsedTime += 10; let msgsInsert = document.querySelectorAll('.body-message .message-data').length; if (qtdMsg == 0) { clearInterval(Time); addEventSelectChat(); } else { if (elapsedTime >= maxTime) { clearInterval(Time); addEventSelectChat(); } else if (qtdMsg <= msgsInsert) { clearInterval(Time); addEventSelectChat(); offsetMessage += 20; monitoringScroll(); } } }, 10); }); } function fillMessages(messageData, childType) { const { chatType, chatId } = JSON.parse(localStorage.getItem('openChat')); // mensagem usuário if (messageData.chatType == 'user') { // mensagem enviada para mim mesmo if (messageData.sender.id == SESSION_DATA.id && messageData.receiver.id == SESSION_DATA.id && chatId == SESSION_DATA.id) { messageSender(messageData, childType); } // mensagem recebida por um usuário else if (messageData.receiver.id == SESSION_DATA.id && chatId == messageData.sender.id) messageReceiver(messageData, childType); // mensagem enviada por mim else if (messageData.sender.id == SESSION_DATA.id && chatId == messageData.receiver.id) messageSender(messageData, childType); } if ((messageData.chatType == 'departament') || (messageData.chatType == 'mural')) { if ((chatId == messageData.receiver.id) || (chatId == null)) { if (messageData.sender.id == SESSION_DATA.id) { messageSender(messageData, childType); } else { messageReceiver(messageData, childType); } } } if (messageData.chatType == 'bot') messageNeutral(messageData, childType); } function createMessageData(message) { const date = message.data_envio.split(' '); const hours = date[1].split(':'); const hoursSend = `${hours[0]}:${hours[1]}`; let chatType; if (message.chatType == '' || message.chatType == undefined) { if (message.id_remetente == '-1') chatType = 'bot'; else if (message.id_remetente && message.id_destinatario) chatType = 'user'; else if (message.id_remetente && message.id_departamento) chatType = 'departament'; else if (!message.id_destinatario && !message.id_departamento) chatType = 'mural'; } else { chatType = message.chatType; } const messageData = { user_exclusao: message.user_exclusao, data_exclusao: message.data_exclusao, chatType, sender: { id: message.id_remetente, name: message.nome_remetente ? message.nome_remetente : 'DotsBot', picture: message.foto_remetente ? `${URL_ARQUIVOS}/${message.foto_remetente}` : null }, receiver: { id: message.id_destinatario || message.id_departamento, id_departamento: message.id_departamento, name: message.nome_destinatario, picture: message.foto_destinatario ? `${URL_ARQUIVOS}/${message.foto_remetente}` : null }, dataReply: { messageId: message.id_msg_respondida, message: message.msg_respondida, id_remetente: message.id_remet_msg_respondida, name_remetente: message.remet_msg_respondida, id_destinatario: message.id_dest_msg_respondida, id_departamento: message.id_dep_msg_respondida, arquivos: message.arquivos_msg_respondida, caminho_arquivo: message.caminho_arquivo_msg_respondida ? message.caminho_arquivo_msg_respondida : '{}', nome_arquivo: message.nome_arquivo_msg_respondida }, files: message.caminho_arquivo ? message.caminho_arquivo : '{}', nome_arquivo: message.nome_arquivo, printPicture: message.printPicture, hour: hoursSend, date: date[0], message: message.mensagem, messageId: message.id, favorite: message.favoritos ? message.favoritos : [], viewed: message.visualizado, reactions: { '👍': { amount: message.reacao_1, names: message.nome_reacao_1 }, '👎': { amount: message.reacao_2, names: message.nome_reacao_2 }, '😂': { amount: message.reacao_3, names: message.nome_reacao_3 }, '😍': { amount: message.reacao_4, names: message.nome_reacao_4 }, '😥': { amount: message.reacao_5, names: message.nome_reacao_5 }, '🎯': { amount: message.reacao_6, names: message.nome_reacao_6 }, '🆗': { amount: message.reacao_7, names: message.nome_reacao_7 }, } }; return messageData; } function messageViewed(chatId, chatType) { if (chatType == 'user') { const formData = new FormData(); removeNotification(chatId, chatType); formData.append('idRemetente', chatId); formData.append('idDestinatario', SESSION_DATA.id); formData.append('tipoUsuario', 'usuario'); requestMessageViewed(formData); // conn.send(JSON.stringify({ // type: 'messageViewed', // receiverId: SESSION_DATA.id, // senderId: chatId // })); } if (chatType == 'departament') { const formData = new FormData(); removeNotification(chatId, chatType); formData.append('idRemetente', null); formData.append('idDestinatario', chatId); formData.append('tipoUsuario', 'departamento'); requestMessageViewed(formData); } if (chatType == 'mural') { const formData = new FormData(); removeNotification(chatId, chatType); formData.append('idRemetente', null); formData.append('idDestinatario', null); formData.append('tipoUsuario', 'mural'); requestMessageViewed(formData); } if (chatType == 'bot') { const formData = new FormData(); removeNotification(chatId, chatType); formData.append('idRemetente', '-1'); formData.append('idDestinatario', SESSION_DATA.id); formData.append('tipoUsuario', 'bot'); requestMessageViewed(formData); } } function requestMessageViewed(data) { fetch(`${URL_BASE}App/Controller/Chat/MensagemVisualizadaAPI.php`, { method: 'POST', body: data }) .then(req => req.json()) .then(res => { verificaMensagensNovas(); }) } function existsNotification() { setTimeout(() => { fetch(`${URL_BASE}App/Controller/Chat/QuantidadeMensagens.php`) .then(req => req.json()) .then(res => { if (res.length > 0) changeFavicon(); else changeFavicon(true); verificaMensagensNovas(); }) }, 500); }