%PDF- %PDF-
Direktori : /home/tjamichg/chatbot.tjamich.gob.mx/ |
Current File : /home/tjamichg/chatbot.tjamich.gob.mx/script.js |
//VARIABLE GLOBALES// let telefono = ""; let esperandoAsesor = false; const chatBox = document.getElementById("chat-box"); const chatBoxAsesor = document.getElementById("chat-box-asesor"); //LOGIN// document.getElementById("phone-form").addEventListener("submit", function (e) { e.preventDefault(); const phoneInput = document.getElementById("user-phone").value.trim(); if (phoneInput === "") { alert("Por favor, ingresa tu número de teléfono."); return; } telefono = phoneInput; document.querySelector(".chat-card-dos").style.display = "none"; document.querySelector(".chat-card").style.display = "block"; cargarHistorial(); setInterval(() => { cargarHistorial(); }, 5000); }); //HISTORIAL BOT// let ultimoHistorial = ""; function cargarHistorial(){ if (!telefono) return; fetch("conexion/responder.php", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ telefono: telefono, mensaje: "" //indica que queremos el historial }) }) .then(res => res.json()) .then(data => { //chatBox.innerHTML = ""; //limpia el historial anterior (por si las mosquis) if (!data.historial) return; // Convertimos a string simple para comparar const historialActual = JSON.stringify(data.historial); if (historialActual === ultimoHistorial) return; // Guardamos el historial actual para la próxima comparación ultimoHistorial = historialActual; // Limpiamos y pintamos el historial actualizado chatBox.innerHTML = ""; data.historial.forEach(chat => { if (chat.usuario) appendMessage(chat.usuario, "user-message"); if (chat.bot) appendMessage(chat.bot, "bot-message"); }); chatBox.scrollTop = chatBox.scrollHeight; }) .catch(error => { console.error("Error al cargar historial:", error); appendMessage("Hubo un error al cargar tus mensajes anteriores.", "bot-message"); }); } //HISTORIAL DE ASESOR// function cargarHistorialAsesor() { if (!telefono) return; fetch("conexion/responder-asesor.php", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ telefono: telefono, mensaje_asesor: "" }) }) .then(res => res.json()) .then(data => { const chatBoxAsesor = document.getElementById("chat-box-asesor"); if(!chatBoxAsesor || !data.historial) return; chatBoxAsesor.innerHTML = ""; data.historial.forEach(chat => { if (chat.usuario) appendAsesorMessage(chat.usuario, "user-message-asesor"); if (chat.asesor) appendAsesorMessage(chat.asesor, "bot-message-asesor"); }); chatBoxAsesor.scrollTop = chatBoxAsesor.scrollHeight; }) .catch(error => { console.error("Error historial asesor:", error); appendAsesorMessage("No se pudo cargar el historial del asesor.", "bot-message-asesor"); }); } //CHATBOT// document.getElementById("chat-form").addEventListener("submit", function (e) { e.preventDefault(); const input = document.getElementById("user-input"); const userText = input.value.trim(); if (userText === "") return; input.value = ""; appendMessage(userText, "user-message"); const lowerText = userText.toLowerCase(); let botReply = ""; //dependiendo el contexto solo tomara si la palabra se menciona if ( lowerText.includes("asesor") || lowerText.includes("comunicarme con alguien") || lowerText.includes("real") ) { const solicitud = { telefono: telefono, mensaje: userText, hora: new Date().toISOString() }; fetch("conexion/asesor.php", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(solicitud) }) .then(res => res.json()) .then(data => { if (data.status === "ok") { setTimeout(() => { appendMessage("Espere un momento, le conectare con un asesor en breve...", "bot-message"); }, 1500); setTimeout(() => { appendMessage("Dirijase al boton de Asesor para que puedo visualizar los mensajes del Asesor..", "bot-message"); }, 3500); } else { appendMessage("Ocurrió un error al contactar al asesor. Intenta más tarde.", "bot-message"); } }) .catch(err => { console.error("Error al contactar al asesor:", err); appendMessage("No se pudo contactar con el servidor.", "bot-message"); }); return; } else if ( lowerText.includes("ubicaciones") || lowerText.includes("lugares") || lowerText.includes("oficinas") ) { setTimeout(() =>{ botReply = "Redirigiendo a la página de ubicaciones del TJAM..."; appendMessage(botReply, "bot-message"); }, 1500); setTimeout(() => { window.open("../TJAMUbicanos/index.php", "_blank"); }, 3500); } else if ( lowerText.includes("redirigeme") || lowerText.includes("mandame") || lowerText.includes("llevame") ) { botReply = "Redirigiendo al apartado de Inicio de Sesion..."; appendMessage(botReply, "bot-message"); setTimeout(() => { window.open("https://jel.tjamich.gob.mx/JEL/login", "_blank"); }, 1500); } else if ( lowerText.includes("intranet") || lowerText.includes("Intranet") ) { botReply = "Redirigiendo al Intranet..."; appendMessage(botReply, "bot-message"); setTimeout(() => { window.open("https://www.intranet.tjamich.gob.mx/", "_blank"); }, 1500); } else if ( lowerText.includes("magistrados") ) { botReply = "Redirigiendo al apartado pleno, donde estan nuestros magistrados..."; appendMessage(botReply, "bot-message"); setTimeout(() => { window.open("https://portal.tjamich.gob.mx/Pleno", "_blank"); appendMessage("Ellos son nuestros magistrados.", "bot-message"); //se encargara de redigir si una de las tres opciones es mencionada en la oracion }, 1500); } else if ( lowerText.includes("menu") || lowerText.includes("principal") ) { botReply = "Redirigiendo a la página principal..."; appendMessage(botReply, "bot-message"); setTimeout(() => { window.location.href = "https://portal.tjamich.gob.mx/Tribunal-en-Materia-Anticorrupci%C3%B3n-y-Administrativa-de-Michoacan-de-Ocampo"; //se encargara de redigir si una de las tres opciones es mencionada en la oracion }, 1500); } else { fetch("conexion/responder.php", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ mensaje: userText, telefono: telefono }) }) .then(res => res.json()) .then(data => { setTimeout(() => { if(data.respuesta){ cargarHistorial(); }; }, 1500); }); } }); //CHATASESOR// document.getElementById("chat-form-asesor").addEventListener("submit", async function (e) { e.preventDefault(); const input = document.getElementById("user-input-asesor"); const userDos = input.value.trim(); if (userDos === "") return; input.value = ""; /*appendAsesorMessage(userDos, "user-message-asesor");*/ try { const res = await fetch("conexion/responder-asesor.php", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ telefono, mensaje_asesor: userDos, hora: new Date().toISOString() }) }); const data = await res.json(); if (data.status === "ok") { setTimeout(() => { cargarHistorialAsesor(); }, 300); // da chance de guardar antes de cargar } } catch (error) { console.error("Error al enviar mensaje del asesor:", error); } }); //SCROLL DE MENSAJES function appendMessage(text, className) { const msgDiv = document.createElement("div"); msgDiv.classList.add("message", className); msgDiv.textContent = text; chatBox.appendChild(msgDiv); chatBox.scrollTop = chatBox.scrollHeight; } function appendAsesorMessage(text, className) { const msgElement = document.createElement("div"); msgElement.classList.add("message-asesor", className); msgElement.textContent = text; chatBoxAsesor.appendChild(msgElement); chatBoxAsesor.scrollTop = chatBoxAsesor.scrollHeight; } //BOTON ABRIR CHATASESOR function abrirAsesor(){ const chatCard = document.getElementById("chat-card-tres"); const chatCardDos = document.getElementById("chat-card"); if(chatCard){ chatCard.style.display = "block"; chatCardDos.style.opacity = "0.5"; cargarHistorialAsesor(); } } function cerrarAsesor(){ const chatCard = document.getElementById("chat-card-tres"); const chatCardDos = document.getElementById("chat-card"); if(chatCard){ chatCard.style.display = "none"; chatCardDos.style.opacity = "1"; } }