%PDF- %PDF-
| Direktori : /home/tjamichg/chatbot.tjamich.gob.mx/ |
| Current File : /home/tjamichg/chatbot.tjamich.gob.mx/script-copy.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);
});
//ajax del historial del ChatBot
//cargar historial del usuario
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");
});
}
//CHATBOT//
const form = document.getElementById("chat-form");
const input = document.getElementById("user-input");
let pendingPhoneRequest = false; //variable de contexto
form.addEventListener("submit", function (e) {
e.preventDefault();
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, un asesor se conectará en breve...", "bot-message");
}, 1500);
} 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("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 {
//consultar base de datos vía PHP
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(() =>{
appendMessage(data.respuesta, "bot-message");
}, 1500);
});
}
input.value = "";
});
function appendMessage(text, className) {
const msgDiv = document.createElement("div");
msgDiv.classList.add("message", className);
msgDiv.textContent = text;
chatBox.appendChild(msgDiv);
chatBox.scrollTop = chatBox.scrollHeight;
}
//abrir y cerrar el asesorCard
function abrirAsesor(){
const chatCard = document.getElementById("chat-card-tres");
if(chatCard){
chatCard.style.display = "block";
}
}