// 数据采集功能脚本

let currentUserId = null;

// DOM元素
const loginSection = document.getElementById('loginSection');
const basicQuestionnaire = document.getElementById('basicQuestionnaire');
const mealRecord = document.getElementById('mealRecord');
const messageArea = document.getElementById('messageArea');

const loginBtn = document.getElementById('loginBtn');
const userIdInput = document.getElementById('userId');
const userNameInput = document.getElementById('userName');

const submitBasicBtn = document.getElementById('submitBasicBtn');
const submitMealBtn = document.getElementById('submitMealBtn');

// 显示消息
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();
    const userName = userNameInput.value.trim();
    
    if (!userId || !userName) {
        showMessage('请输入用户ID和姓名', 'error');
        return;
    }
    
    loginBtn.disabled = true;
    loginBtn.textContent = '登录中...';
    
    try {
        const response = await fetch('/api/user/register', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json; charset=utf-8'
            },
            body: JSON.stringify({
                user_id: userId,
                name: userName
            })
        });
        
        const data = await response.json();
        
        if (data.success) {
            currentUserId = userId;
            loginSection.style.display = 'none';
            basicQuestionnaire.style.display = 'block';
            mealRecord.style.display = 'block';
            showMessage('注册成功！', 'success');
        } else {
            showMessage(data.message || '注册失败', 'error');
        }
    } catch (error) {
        console.error('注册失败:', error);
        showMessage('注册失败，请检查网络连接', 'error');
    } finally {
        loginBtn.disabled = false;
        loginBtn.textContent = '登录/注册';
    }
});

// 提交基础信息
submitBasicBtn.addEventListener('click', async () => {
    const age = document.getElementById('age').value;
    const gender = document.getElementById('gender').value;
    const height = document.getElementById('height').value;
    const weight = document.getElementById('weight').value;
    const activityLevel = document.getElementById('activityLevel').value;
    
    if (!age || !gender || !height || !weight || !activityLevel) {
        showMessage('请填写完整的基础信息', 'error');
        return;
    }
    
    submitBasicBtn.disabled = true;
    submitBasicBtn.textContent = '提交中...';
    
    try {
        const response = await fetch('/api/questionnaire/submit', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json; charset=utf-8'
            },
            body: JSON.stringify({
                user_id: currentUserId,
                type: 'basic',
                answers: {
                    age: parseInt(age),
                    gender: gender,
                    height: parseFloat(height),
                    weight: parseFloat(weight),
                    activity_level: activityLevel
                }
            })
        });
        
        const data = await response.json();
        
        if (data.success) {
            showMessage('基础信息提交成功！', 'success');
        } else {
            showMessage(data.message || '提交失败', 'error');
        }
    } catch (error) {
        console.error('提交失败:', error);
        showMessage('提交失败，请检查网络连接', 'error');
    } finally {
        submitBasicBtn.disabled = false;
        submitBasicBtn.textContent = '提交基础信息';
    }
});

// 记录餐食
submitMealBtn.addEventListener('click', async () => {
    const mealDate = document.getElementById('mealDate').value || new Date().toISOString().split('T')[0];
    const mealType = document.getElementById('mealType').value;
    const foodsText = document.getElementById('foods').value;
    const calories = document.getElementById('calories').value;
    const satisfaction = document.getElementById('satisfaction').value;
    
    if (!foodsText || !calories) {
        showMessage('请填写完整的餐食信息', 'error');
        return;
    }
    
    // 解析食物列表
    const foods = foodsText.split('\n').filter(line => line.trim());
    const quantities = foods.map(f => {
        const parts = f.trim().split(/\s+/);
        return parts.length > 1 ? parts.slice(1).join(' ') : '适量';
    });
    const foodNames = foods.map(f => f.trim().split(/\s+/)[0]);
    
    submitMealBtn.disabled = true;
    submitMealBtn.textContent = '记录中...';
    
    try {
        const response = await fetch('/api/meal/record', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json; charset=utf-8'
            },
            body: JSON.stringify({
                user_id: currentUserId,
                date: mealDate,
                meal_type: mealType,
                foods: foodNames,
                quantities: quantities,
                calories: parseFloat(calories),
                satisfaction_score: parseInt(satisfaction),
                notes: ''
            })
        });
        
        const data = await response.json();
        
        if (data.success) {
            showMessage('餐食记录成功！', 'success');
            // 清空表单
            document.getElementById('foods').value = '';
            document.getElementById('calories').value = '';
            document.getElementById('satisfaction').value = '3';
        } else {
            showMessage(data.message || '记录失败', 'error');
        }
    } catch (error) {
        console.error('记录失败:', error);
        showMessage('记录失败，请检查网络连接', 'error');
    } finally {
        submitMealBtn.disabled = false;
        submitMealBtn.textContent = '记录餐食';
    }
});

// 设置默认日期为今天
document.addEventListener('DOMContentLoaded', () => {
    const mealDateInput = document.getElementById('mealDate');
    if (mealDateInput) {
        mealDateInput.value = new Date().toISOString().split('T')[0];
    }
});
