Files
recommend/static/js/recommendation.js
赵杰 Jie Zhao (雄狮汽车科技) f65abdef0f feat: complete web app features and fix encoding
2025-11-02 22:23:10 +08:00

136 lines
4.3 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// 推荐功能脚本
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}`;
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];
}
card.innerHTML = `
<h3>推荐方案 ${index + 1}</h3>
<div class="food-list">
${foods.map(food => `<div class="food-item">${food}</div>`).join('')}
</div>
${rec.confidence ? `<div class="confidence">置信度: ${(rec.confidence * 100).toFixed(1)}%</div>` : ''}
${rec.reason ? `<div style="margin-top: 10px; color: #666;">推荐理由: ${rec.reason}</div>` : ''}
`;
recommendationsList.appendChild(card);
});
}