155 lines
4.9 KiB
JavaScript
155 lines
4.9 KiB
JavaScript
// 推荐功能脚本
|
||
|
||
let currentUserId = null;
|
||
|
||
// DOM元素
|
||
const loginSection = document.getElementById('loginSection');
|
||
const requestSection = document.getElementById('requestSection');
|
||
const recommendationsSection = document.getElementById('recommendationsSection');
|
||
const messageArea = document.getElementById('messageArea');
|
||
|
||
const loginBtn = document.getElementById('loginBtn');
|
||
const userIdInput = document.getElementById('userId');
|
||
const getRecommendationBtn = document.getElementById('getRecommendationBtn');
|
||
const mealTypeSelect = document.getElementById('mealType');
|
||
const recommendationsList = document.getElementById('recommendationsList');
|
||
|
||
// 显示消息
|
||
function showMessage(message, type = 'info') {
|
||
messageArea.textContent = message;
|
||
messageArea.className = `message-area ${type}`;
|
||
messageArea.style.display = 'block';
|
||
setTimeout(() => {
|
||
messageArea.className = 'message-area';
|
||
messageArea.style.display = 'none';
|
||
}, 3000);
|
||
}
|
||
|
||
// 用户登录
|
||
loginBtn.addEventListener('click', async () => {
|
||
const userId = userIdInput.value.trim();
|
||
|
||
if (!userId) {
|
||
showMessage('请输入用户ID', 'error');
|
||
return;
|
||
}
|
||
|
||
loginBtn.disabled = true;
|
||
loginBtn.textContent = '登录中...';
|
||
|
||
try {
|
||
const response = await fetch('/api/user/login', {
|
||
method: 'POST',
|
||
headers: {
|
||
'Content-Type': 'application/json; charset=utf-8'
|
||
},
|
||
body: JSON.stringify({
|
||
user_id: userId
|
||
})
|
||
});
|
||
|
||
const data = await response.json();
|
||
|
||
if (data.success) {
|
||
currentUserId = userId;
|
||
loginSection.style.display = 'none';
|
||
requestSection.style.display = 'block';
|
||
showMessage(`欢迎,${data.name || userId}!`, 'success');
|
||
} else {
|
||
showMessage(data.message || '登录失败', 'error');
|
||
}
|
||
} catch (error) {
|
||
console.error('登录失败:', error);
|
||
showMessage('登录失败,请检查网络连接', 'error');
|
||
} finally {
|
||
loginBtn.disabled = false;
|
||
loginBtn.textContent = '登录';
|
||
}
|
||
});
|
||
|
||
// 获取推荐
|
||
getRecommendationBtn.addEventListener('click', async () => {
|
||
const mealType = mealTypeSelect.value;
|
||
|
||
getRecommendationBtn.disabled = true;
|
||
getRecommendationBtn.textContent = '获取中...';
|
||
|
||
try {
|
||
const response = await fetch('/api/recommendation/get', {
|
||
method: 'POST',
|
||
headers: {
|
||
'Content-Type': 'application/json; charset=utf-8'
|
||
},
|
||
body: JSON.stringify({
|
||
user_id: currentUserId,
|
||
meal_type: mealType,
|
||
preferences: {},
|
||
context: {}
|
||
})
|
||
});
|
||
|
||
const data = await response.json();
|
||
|
||
if (data.success && data.recommendations && data.recommendations.length > 0) {
|
||
displayRecommendations(data.recommendations);
|
||
recommendationsSection.style.display = 'block';
|
||
showMessage('推荐获取成功!', 'success');
|
||
} else {
|
||
showMessage(data.message || '暂无推荐内容,请先完善个人数据', 'info');
|
||
}
|
||
} catch (error) {
|
||
console.error('获取推荐失败:', error);
|
||
showMessage('获取推荐失败,请检查网络连接', 'error');
|
||
} finally {
|
||
getRecommendationBtn.disabled = false;
|
||
getRecommendationBtn.textContent = '获取推荐';
|
||
}
|
||
});
|
||
|
||
// 显示推荐结果
|
||
function displayRecommendations(recommendations) {
|
||
recommendationsList.innerHTML = '';
|
||
|
||
recommendations.forEach((rec, index) => {
|
||
const card = document.createElement('div');
|
||
card.className = 'recommendation-card';
|
||
|
||
let foods = [];
|
||
if (rec.foods && Array.isArray(rec.foods)) {
|
||
foods = rec.foods;
|
||
} else if (rec.food) {
|
||
foods = [rec.food];
|
||
}
|
||
|
||
const foodsHtml = foods.map(food =>
|
||
`<div class="food-item">${escapeHtml(food)}</div>`
|
||
).join('');
|
||
|
||
const confidenceHtml = rec.confidence
|
||
? `<div class="confidence">置信度: ${(rec.confidence * 100).toFixed(1)}%</div>`
|
||
: '';
|
||
|
||
const reasonHtml = rec.reason
|
||
? `<div style="margin-top: 10px; color: #666;">推荐理由: ${escapeHtml(rec.reason)}</div>`
|
||
: '';
|
||
|
||
card.innerHTML = `
|
||
<h3>推荐方案 ${index + 1}</h3>
|
||
<div class="food-list">
|
||
${foodsHtml}
|
||
</div>
|
||
${confidenceHtml}
|
||
${reasonHtml}
|
||
`;
|
||
|
||
recommendationsList.appendChild(card);
|
||
});
|
||
}
|
||
|
||
// HTML转义函数,防止XSS攻击
|
||
function escapeHtml(text) {
|
||
const div = document.createElement('div');
|
||
div.textContent = text;
|
||
return div.innerHTML;
|
||
}
|