// Client-side Application Logic for Newborn Tracker & Analytics // Enhanced: Record Editing in Timeline, Centered Modal Alignments, Custom Metrics & Default Values in Baby Profiles const API_BASE = '/api'; // Global Reactive State const state = { families: [], currentFamilyId: localStorage.getItem('selected_family_id') || null, babies: [], currentBabyId: localStorage.getItem('selected_baby_id') || null, currentOperator: localStorage.getItem('caregiver_role') || '宝妈', currentDate: getLocalDateString(), currentView: 'quick', currentSpecTab: 'all', timelineFilter: 'all', babySearchQuery: '', summary: null, customMetrics: [], careGuides: [], lastBottleMl: parseInt(localStorage.getItem('last_bottle_ml') || '120'), memos: [], feedingMode: localStorage.getItem('last_feeding_mode') || 'bottle', bfTargetDuration: parseInt(localStorage.getItem('bf_target_duration') || '20'), activeTimer: null, rolePreferences: JSON.parse(localStorage.getItem('baby_role_preferences') || '{}'), memoHistoryFilter: { status: 'all', period: 'all', search: '' }, liveTimerInterval: null }; function getLocalDateString(d = new Date()) { const pad = n => String(n).padStart(2, '0'); return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`; } // ---------------------------------------------------- // Toast Notification // ---------------------------------------------------- function showToast(message, type = 'success') { const container = document.getElementById('toastContainer'); if (!container) return; const toast = document.createElement('div'); const bg = type === 'warning' ? 'bg-amber-500 text-white' : (type === 'error' ? 'bg-rose-500 text-white' : 'bg-slate-800 text-white'); toast.className = `toast-msg flex items-center justify-between px-4 py-2.5 rounded-xl shadow-lg text-xs font-semibold ${bg} transition-all duration-300`; toast.innerHTML = ` ${message} ✕ `; container.appendChild(toast); setTimeout(() => { toast.style.opacity = '0'; setTimeout(() => toast.remove(), 300); }, 3500); } const ROLE_ICONS = { '宝爸': '👨', '宝妈': '👩', '爷爷': '👴', '奶奶': '👵', '外公': '👴', '外婆': '👵', '舅舅': '👨', '舅妈': '👩', '月嫂': '👵', '育儿嫂': '❤️' }; function updateOperatorDisplay() { const opEl = document.getElementById('currentOperatorName'); const iconEl = document.getElementById('currentOperatorIcon'); if (opEl) opEl.textContent = state.currentOperator; if (iconEl) iconEl.textContent = ROLE_ICONS[state.currentOperator] || '👤'; } function openRoleModal() { const container = document.getElementById('roleOptionsContainer'); if (container) { container.innerHTML = ''; const family = state.families.find(f => f.family_id === state.currentFamilyId); const members = (family && family.members && family.members.length > 0) ? family.members : [ { role_name: '宝爸' }, { role_name: '宝妈' }, { role_name: '爷爷' }, { role_name: '奶奶' }, { role_name: '外公' }, { role_name: '外婆' }, { role_name: '舅舅' }, { role_name: '舅妈' } ]; members.forEach(m => { const role = m.role_name; const isCurrent = state.currentOperator === role; const icon = ROLE_ICONS[role] || '👤'; const btn = document.createElement('button'); btn.className = `p-3 rounded-2xl border flex items-center justify-between text-left transition active:scale-95 ${ isCurrent ? 'bg-indigo-50 border-indigo-400 font-bold text-indigo-700 shadow-2xs' : 'bg-slate-50 hover:bg-slate-100 border-slate-200 text-slate-700' }`; btn.innerHTML = `
${icon} ${role}
${isCurrent ? '当前' : '切换'} `; btn.onclick = () => { state.currentOperator = role; localStorage.setItem('caregiver_role', role); updateOperatorDisplay(); applyRolePreferences(role); closeModal('roleModal'); showToast(`操作人已切换为:【${role}】`); }; container.appendChild(btn); }); } openModal('roleModal'); } // ---------------------------------------------------- // Initialization // ---------------------------------------------------- document.addEventListener('DOMContentLoaded', async () => { // Set current operator display and apply its preferences updateOperatorDisplay(); applyRolePreferences(state.currentOperator); const dateInput = document.getElementById('customDatePicker'); if (dateInput) dateInput.value = state.currentDate; const bottleAmountBtn = document.getElementById('btnLastBottleAmount'); if (bottleAmountBtn) bottleAmountBtn.textContent = `${state.lastBottleMl}ml`; // Bind Bottom Navigation Tabs document.querySelectorAll('.tab-btn').forEach(btn => { btn.addEventListener('click', () => { const target = btn.dataset.target; switchTab(target); }); }); // Bind Date Buttons (Inside Dashboard View) document.querySelectorAll('.date-tab').forEach(btn => { btn.addEventListener('click', () => { document.querySelectorAll('.date-tab').forEach(b => { b.classList.remove('active', 'bg-indigo-600', 'text-white'); b.classList.add('bg-slate-100', 'text-slate-600'); }); btn.classList.add('active', 'bg-indigo-600', 'text-white'); btn.classList.remove('bg-slate-100', 'text-slate-600'); const offset = parseInt(btn.dataset.offset || '0'); const target = new Date(Date.now() + offset * 24 * 3600 * 1000); state.currentDate = getLocalDateString(target); if (dateInput) dateInput.value = state.currentDate; loadSummaryData(); }); }); if (dateInput) { dateInput.addEventListener('change', (e) => { state.currentDate = e.target.value; document.querySelectorAll('.date-tab').forEach(b => { b.classList.remove('active', 'bg-indigo-600', 'text-white'); b.classList.add('bg-slate-100', 'text-slate-600'); }); loadSummaryData(); }); } // Operator / Role Selector Modal const roleBtn = document.getElementById('roleSelectorBtn'); if (roleBtn) roleBtn.addEventListener('click', openRoleModal); // Top-left Baby Indicator Button -> opens Profile Tab const babyBtn = document.getElementById('babySelectorBtn'); if (babyBtn) { babyBtn.addEventListener('click', () => switchTab('profile')); } // Dashboard Spec Segment Switcher Tabs document.querySelectorAll('.spec-tab').forEach(btn => { btn.addEventListener('click', () => { document.querySelectorAll('.spec-tab').forEach(b => { b.classList.remove('active', 'bg-slate-900', 'text-white'); b.classList.add('bg-slate-100', 'text-slate-600'); }); btn.classList.add('active', 'bg-slate-900', 'text-white'); btn.classList.remove('bg-slate-100', 'text-slate-600'); const spec = btn.dataset.spec; state.currentSpecTab = spec; document.querySelectorAll('.spec-subpanel').forEach(p => p.classList.add('hidden')); const activePanel = document.getElementById(`specPanel-${spec}`); if (activePanel) activePanel.classList.remove('hidden'); }); }); // Timeline Drawer Category Filter Tabs document.querySelectorAll('.timeline-filter-btn').forEach(btn => { btn.addEventListener('click', () => { document.querySelectorAll('.timeline-filter-btn').forEach(b => { b.classList.remove('active', 'bg-slate-900', 'text-white'); b.classList.add('bg-slate-100', 'text-slate-600'); }); btn.classList.add('active', 'bg-slate-900', 'text-white'); btn.classList.remove('bg-slate-100', 'text-slate-600'); state.timelineFilter = btn.dataset.type; renderModalTimeline(); }); }); // Care Guides Filter Tabs document.querySelectorAll('.guide-filter-btn').forEach(btn => { btn.addEventListener('click', () => { document.querySelectorAll('.guide-filter-btn').forEach(b => { b.classList.remove('active', 'bg-indigo-600', 'text-white'); b.classList.add('bg-slate-100', 'text-slate-600'); }); btn.classList.add('active', 'bg-indigo-600', 'text-white'); btn.classList.remove('bg-slate-100', 'text-slate-600'); renderCareGuides(btn.dataset.cat); }); }); // Baby Search Input (search as you type) const searchInput = document.getElementById('babySearchInput'); if (searchInput) { searchInput.addEventListener('input', (e) => { state.babySearchQuery = e.target.value.trim().toLowerCase(); renderBabiesList(); }); } // Page Visibility Change (Sync when user returns to browser) document.addEventListener('visibilitychange', () => { if (!document.hidden) { loadSummaryData(true); } }); // Initial Data Fetch await loadFamilies(); await loadCustomMetrics(); await loadCareGuides(); setupSSE(); // Periodic heartbeat / timer update (every 10s) state.liveTimerInterval = setInterval(() => { if (state.summary) { loadSummaryData(true); } }, 10000); }); // ---------------------------------------------------- // Tab Navigation // ---------------------------------------------------- function switchTab(viewId) { state.currentView = viewId; document.querySelectorAll('.view-panel').forEach(p => p.classList.add('hidden')); const targetView = document.getElementById(`view-${viewId}`); if (targetView) targetView.classList.remove('hidden'); document.querySelectorAll('.tab-btn').forEach(b => { const isDesktopTab = b.closest('#desktopNavTabs') !== null; const isTarget = b.dataset.target === viewId; if (isDesktopTab) { if (isTarget) { b.classList.add('active', 'bg-white', 'text-indigo-600', 'font-bold', 'shadow-2xs'); b.classList.remove('text-slate-500', 'hover:text-slate-800', 'font-semibold'); } else { b.classList.remove('active', 'bg-white', 'text-indigo-600', 'font-bold', 'shadow-2xs'); b.classList.add('text-slate-500', 'hover:text-slate-800', 'font-semibold'); } } else { if (isTarget) { b.classList.add('active', 'text-indigo-600', 'font-bold'); b.classList.remove('text-slate-400', 'font-semibold'); } else { b.classList.remove('active', 'text-indigo-600', 'font-bold'); b.classList.add('text-slate-400', 'font-semibold'); } } }); if (viewId === 'dashboard' || viewId === 'quick') { loadSummaryData(); } if (viewId === 'profile') { renderProfileConfigMenu(); } } // ---------------------------------------------------- // Family Management & Switching // ---------------------------------------------------- async function loadFamilies() { try { const res = await fetch(`${API_BASE}/families`); const json = await res.json(); if (json.success && json.data.length > 0) { state.families = json.data; if (!state.currentFamilyId || !state.families.find(f => f.family_id === state.currentFamilyId)) { const def = state.families.find(f => f.is_default) || state.families[0]; state.currentFamilyId = def.family_id; localStorage.setItem('selected_family_id', state.currentFamilyId); } updateCurrentFamilyDisplay(); // Populate role preferences from members if available const currentFam = state.families.find(f => f.family_id === state.currentFamilyId); if (currentFam && currentFam.members) { currentFam.members.forEach(m => { if (m.preferences && Object.keys(m.preferences).length > 0) { state.rolePreferences[m.role_name] = { ...(state.rolePreferences[m.role_name] || {}), ...m.preferences }; } }); localStorage.setItem('baby_role_preferences', JSON.stringify(state.rolePreferences)); } applyRolePreferences(state.currentOperator); await loadBabies(); await loadMemos(); } } catch (err) { console.error('Failed to load families:', err); } } function updateCurrentFamilyDisplay() { const family = state.families.find(f => f.family_id === state.currentFamilyId); if (!family) return; const headerBadge = document.getElementById('headerFamilyNameBadge'); if (headerBadge) { headerBadge.textContent = `🏡 ${family.name}`; headerBadge.onclick = (e) => { e.stopPropagation(); openFamilySwitchModal(); }; } const titleEl = document.getElementById('currentFamilyTitle'); if (titleEl) titleEl.textContent = family.name; const metaEl = document.getElementById('currentFamilyMeta'); if (metaEl) { const babyCount = (family.babies || []).length; const memberCount = (family.members || []).length; metaEl.textContent = `创建人: ${family.creator_name || '宝妈'} · ${babyCount} 位宝宝 · ${memberCount} 位看护人`; } const codeEl = document.getElementById('currentFamilyInviteCode'); if (codeEl) codeEl.textContent = family.invite_code; const memberCountEl = document.getElementById('familyMemberCount'); if (memberCountEl) memberCountEl.textContent = (family.members || []).length; const membersPillsEl = document.getElementById('familyMembersPills'); if (membersPillsEl) { membersPillsEl.innerHTML = (family.members || []).map(m => { const icon = ROLE_ICONS[m.role_name] || '👤'; const ownerTag = m.is_owner ? '创建者' : ''; return ` ${icon} ${m.role_name} ${ownerTag} `; }).join(''); } } function openFamilySwitchModal() { renderFamilySwitchList(); openModal('familySwitchModal'); } function renderFamilySwitchList() { const container = document.getElementById('familySwitchList'); if (!container) return; container.innerHTML = ''; state.families.forEach(f => { const isCurrent = f.family_id === state.currentFamilyId; const card = document.createElement('div'); card.className = `p-3 rounded-2xl border cursor-pointer transition flex items-center justify-between ${ isCurrent ? 'bg-indigo-50/80 border-indigo-400 shadow-2xs' : 'bg-slate-50 border-slate-200/80 hover:bg-slate-100' }`; card.onclick = () => switchFamily(f.family_id); const babyCount = (f.babies || []).length; const memberCount = (f.members || []).length; card.innerHTML = `
🏡
${f.name} ${isCurrent ? '当前活跃' : ''}
邀请码: ${f.invite_code} · ${babyCount} 个宝宝 · ${memberCount} 位看护人
${isCurrent ? '✓ 活跃' : '进入 →'}
`; container.appendChild(card); }); } async function switchFamily(familyId) { if (state.currentFamilyId === familyId) { closeModal('familySwitchModal'); return; } state.currentFamilyId = familyId; localStorage.setItem('selected_family_id', familyId); const fam = state.families.find(f => f.family_id === familyId); updateCurrentFamilyDisplay(); await loadBabies(); await loadMemos(); closeModal('familySwitchModal'); showToast(`已切换至家庭:【${fam ? fam.name : ''}】`); } function copyWechatInviteText() { const family = state.families.find(f => f.family_id === state.currentFamilyId); if (!family) return; const text = `👶【${family.name}】邀请您加入共同记录宝宝成长!在系统输入家庭邀请码【${family.invite_code}】即可加入看护团队。`; if (navigator.clipboard && navigator.clipboard.writeText) { navigator.clipboard.writeText(text).then(() => { showToast('微信邀请口令已复制!快去微信粘贴发给家人吧 💬'); }).catch(() => fallbackCopy(text)); } else { fallbackCopy(text); } } function fallbackCopy(text) { const ta = document.createElement('textarea'); ta.value = text; document.body.appendChild(ta); ta.select(); try { document.execCommand('copy'); showToast('微信邀请口令已复制!快去微信粘贴发给家人吧 💬'); } catch (err) { showToast(`请手动复制邀请码:${state.families.find(f => f.family_id === state.currentFamilyId)?.invite_code}`); } document.body.removeChild(ta); } function openCreateFamilyModal() { const input = document.getElementById('newFamilyName'); if (input) input.value = ''; const select = document.getElementById('newFamilyCreatorRole'); if (select) select.value = state.currentOperator || '宝妈'; openModal('createFamilyModal'); } async function submitCreateFamily() { const nameInput = document.getElementById('newFamilyName'); const roleSelect = document.getElementById('newFamilyCreatorRole'); const name = nameInput ? nameInput.value.trim() : ''; const creatorName = roleSelect ? roleSelect.value : '宝妈'; if (!name) { showToast('请输入家庭名称', 'warning'); return; } try { const res = await fetch(`${API_BASE}/families`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ name, creatorName }) }); const json = await res.json(); if (json.success) { closeModal('createFamilyModal'); showToast(`家庭【${name}】创建成功!专属邀请码:${json.data.invite_code}`); state.currentFamilyId = json.data.family_id; localStorage.setItem('selected_family_id', state.currentFamilyId); await loadFamilies(); } else { showToast(json.message || '创建失败', 'error'); } } catch (err) { console.error('Failed to create family:', err); showToast('网络错误,创建失败', 'error'); } } function openJoinFamilyModal() { const input = document.getElementById('joinFamilyCode'); if (input) input.value = ''; const roleSelect = document.getElementById('joinFamilyRole'); if (roleSelect) roleSelect.value = state.currentOperator || '宝爸'; openModal('joinFamilyModal'); } async function submitJoinFamily() { const input = document.getElementById('joinFamilyCode'); const roleSelect = document.getElementById('joinFamilyRole'); const inviteCode = input ? input.value.trim().toUpperCase() : ''; const roleName = roleSelect ? roleSelect.value : '看护人'; if (!inviteCode) { showToast('请输入 6 位家庭邀请码', 'warning'); return; } try { const res = await fetch(`${API_BASE}/families/join`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ inviteCode, roleName }) }); const json = await res.json(); if (json.success) { closeModal('joinFamilyModal'); showToast(json.message); state.currentFamilyId = json.data.family_id; localStorage.setItem('selected_family_id', state.currentFamilyId); await loadFamilies(); } else { showToast(json.message || '加入失败', 'error'); } } catch (err) { console.error('Failed to join family:', err); showToast('网络错误,加入失败', 'error'); } } function openEditFamilyModal() { const family = state.families.find(f => f.family_id === state.currentFamilyId); if (!family) return; const input = document.getElementById('editFamilyNameInput'); if (input) input.value = family.name; openModal('editFamilyModal'); } async function submitEditFamilyName() { const input = document.getElementById('editFamilyNameInput'); const newName = input ? input.value.trim() : ''; if (!newName) { showToast('家庭名称不能为空', 'warning'); return; } try { const res = await fetch(`${API_BASE}/families/${state.currentFamilyId}`, { method: 'PUT', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ name: newName }) }); const json = await res.json(); if (json.success) { closeModal('editFamilyModal'); showToast('家庭名称修改成功!'); const fam = state.families.find(f => f.family_id === state.currentFamilyId); if (fam) fam.name = newName; updateCurrentFamilyDisplay(); } else { showToast(json.message || '修改失败', 'error'); } } catch (err) { console.error('Failed to update family name:', err); showToast('网络错误,修改失败', 'error'); } } let selectedMemberRole = '宝爸'; function openAddFamilyMemberModal() { selectedMemberRole = '宝爸'; const customInput = document.getElementById('customMemberRoleInput'); if (customInput) customInput.value = ''; openModal('addFamilyMemberModal'); } function selectMemberRoleChoice(role) { selectedMemberRole = role; const customInput = document.getElementById('customMemberRoleInput'); if (customInput) customInput.value = role; } async function submitAddFamilyMember() { const customInput = document.getElementById('customMemberRoleInput'); const roleName = (customInput && customInput.value.trim()) ? customInput.value.trim() : selectedMemberRole; if (!roleName) { showToast('请选择或输入看护人称谓', 'warning'); return; } try { const res = await fetch(`${API_BASE}/families/${state.currentFamilyId}/members`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ roleName }) }); const json = await res.json(); if (json.success) { closeModal('addFamilyMemberModal'); showToast(`已成功将【${roleName}】添加至家庭看护团队!`); await loadFamilies(); } else { showToast(json.message || '添加失败', 'error'); } } catch (err) { console.error('Failed to add member:', err); showToast('网络错误,添加失败', 'error'); } } // ---------------------------------------------------- // Data Loaders // ---------------------------------------------------- async function loadBabies() { try { const url = state.currentFamilyId ? `${API_BASE}/babies?family_id=${state.currentFamilyId}` : `${API_BASE}/babies`; const res = await fetch(url); const json = await res.json(); if (json.success) { state.babies = json.data; if (state.babies.length > 0) { if (!state.currentBabyId || !state.babies.find(b => b.baby_id === state.currentBabyId)) { const def = state.babies.find(b => b.is_default) || state.babies[0]; state.currentBabyId = def.baby_id; localStorage.setItem('selected_baby_id', state.currentBabyId); } } else { state.currentBabyId = null; } updateCurrentBabyDisplay(); renderBabiesList(); renderProfileConfigMenu(); await loadSummaryData(); } } catch (err) { console.error('Failed to load babies:', err); } } function updateCurrentBabyDisplay() { const baby = state.babies.find(b => b.baby_id === state.currentBabyId); const nameEl = document.getElementById('currentBabyName'); const ageEl = document.getElementById('currentBabyAge'); const avatarEl = document.getElementById('babyAvatarDot'); const milestoneEl = document.getElementById('pediatricMilestoneBadge'); if (!baby) { if (nameEl) nameEl.textContent = '暂无宝宝'; if (ageEl) ageEl.textContent = '点击添加'; if (avatarEl) { avatarEl.style.backgroundColor = '#94A3B8'; avatarEl.textContent = '+'; } if (milestoneEl) milestoneEl.textContent = '请为本家庭添加宝宝'; return; } if (nameEl) nameEl.textContent = baby.name; if (ageEl) ageEl.textContent = baby.ageText || `${baby.ageDays || 0}天`; if (avatarEl) { avatarEl.style.backgroundColor = baby.theme_color || '#3B82F6'; avatarEl.textContent = baby.name.substring(0, 1); } if (milestoneEl) { milestoneEl.textContent = baby.baseline ? baby.baseline.stageName : '月龄自适应'; } } async function loadCustomMetrics() { if (!state.currentBabyId) return; try { const res = await fetch(`${API_BASE}/custom-metrics?babyId=${state.currentBabyId}`); const json = await res.json(); if (json.success) { state.customMetrics = json.data; renderQuickCustomMetricsGrid(); renderProfileCustomMetricsList(); } } catch (err) { console.error('Failed to load custom metrics:', err); } } async function loadSummaryData(silent = false) { if (!state.currentBabyId) return; try { const res = await fetch(`${API_BASE}/summary?babyId=${state.currentBabyId}&date=${state.currentDate}`); const json = await res.json(); if (json.success) { state.summary = json.data; renderLiveDashboard(json.data); renderKpiCards(json.data); renderRhythmStream(json.data.timeline || []); renderPeriodSlots(json.data.periodSlots || json.data.periods); renderSpecDeepDives(json.data); renderTrendChart(json.data.trends); updateTimelineCount(json.data.timeline); if (!silent) { const ind = document.getElementById('liveIndicator'); if (ind) { ind.classList.add('bg-emerald-100'); setTimeout(() => ind.classList.remove('bg-emerald-100'), 500); } } } } catch (err) { console.error('Failed to load summary:', err); } } async function loadCareGuides() { try { const res = await fetch(`${API_BASE}/care-guides`); const json = await res.json(); if (json.success) { state.careGuides = json.data; renderCareGuides('all'); } } catch (err) { console.error('Failed to load care guides:', err); } } // ---------------------------------------------------- // Real-time Multi-Device Sync (SSE) // ---------------------------------------------------- function setupSSE() { if (!window.EventSource) return; const source = new EventSource(`${API_BASE}/events/stream`); source.onmessage = (event) => { try { const data = JSON.parse(event.data); if (data.type === 'record_created') { const typeMap = { bottle: '瓶喂', breastfeed: '亲喂', sleep: '睡眠', diaper: '换尿布', custom: '自定义打卡' }; const label = typeMap[data.activityType] || '日常事件'; showToast(`🔔 ${data.operatorName || '家人'} 刚刚打卡了【${label}】!`); loadSummaryData(true); } else if (data.type === 'record_deleted' || data.type === 'record_updated') { loadSummaryData(true); } else if (data.type && data.type.startsWith('memo_')) { loadMemos(); } } catch (e) {} }; source.onerror = () => { source.close(); setTimeout(setupSSE, 10000); }; } // ---------------------------------------------------- // Live Clock & Wake Window Renderer (Quick View) // ---------------------------------------------------- function renderLiveDashboard(data) { const { liveStatus } = data; if (!liveStatus) return; // 1. Feeding Status (距上次已逝时间与上次详情直接融合) const f = liveStatus.feeding; const lastFeedTimeEl = document.getElementById('lastFeedingTime'); const feedLastSummaryEl = document.getElementById('feedLastSummary'); const alertBanner = document.getElementById('feedingAlertBanner'); if (f && f.hasData) { if (lastFeedTimeEl) lastFeedTimeEl.textContent = `距上次 ${f.elapsedText ? f.elapsedText.replace(/前$/, '') : '--'}`; if (feedLastSummaryEl) { const typeStr = f.type === 'bottle' ? `${f.amountMl || 0}ml` : '亲喂'; feedLastSummaryEl.textContent = `上次: ${f.time} ${typeStr} (${f.operator || '家人'})`; } if (alertBanner) { if (f.isOverdue) alertBanner.classList.remove('hidden'); else alertBanner.classList.add('hidden'); } } else { if (lastFeedTimeEl) lastFeedTimeEl.textContent = '今日尚未喂奶'; if (feedLastSummaryEl) feedLastSummaryEl.textContent = '上次: 尚未记录'; if (alertBanner) alertBanner.classList.add('hidden'); } // 2. Sleep Status (当前睡眠/清醒状态与已逝时间直接融合) const s = liveStatus.sleep; const sleepStateTitleEl = document.getElementById('currentSleepStateTitle'); const sleepStateDetailEl = document.getElementById('currentSleepStateDetail'); const sleepToggleIcon = document.getElementById('sleepToggleIcon'); const sleepToggleActionText = document.getElementById('sleepToggleActionText'); const btnSleepToggle = document.getElementById('btnSleepToggle'); const btnSleepFocus = document.getElementById('btnSleepFocusExpand'); if (s && s.hasData && s.isSleeping) { if (btnSleepFocus) btnSleepFocus.classList.remove('hidden'); if (sleepStateTitleEl) { sleepStateTitleEl.textContent = `安睡 ${s.currentDurationText}`; sleepStateTitleEl.className = 'text-xs font-black text-amber-700 bg-amber-50 border border-amber-200/80 px-2 py-1 rounded-xl whitespace-nowrap inline-block'; } if (sleepStateDetailEl) sleepStateDetailEl.textContent = '宝宝正在睡眠中 · 骨骼与大脑发育'; if (sleepToggleIcon) sleepToggleIcon.textContent = '☀️'; if (sleepToggleActionText) sleepToggleActionText.textContent = `☀️ 宝宝醒了?(结算已睡 ${s.currentDurationText})`; if (btnSleepToggle) { btnSleepToggle.className = 'flex-1 bg-gradient-to-r from-amber-500 to-orange-500 hover:from-amber-600 hover:to-orange-600 active:scale-98 text-white font-extrabold text-xs py-3 rounded-2xl shadow-xs transition flex items-center justify-center space-x-2 whitespace-nowrap'; } } else { if (btnSleepFocus) btnSleepFocus.classList.add('hidden'); if (sleepStateTitleEl) { sleepStateTitleEl.textContent = s && s.hasData ? `清醒 ${s.awakeText.replace(/前$/, '')}` : '清醒中'; sleepStateTitleEl.className = 'text-xs font-black text-purple-700 bg-purple-50 border border-purple-200/80 px-2 py-1 rounded-xl whitespace-nowrap inline-block'; } if (sleepStateDetailEl) sleepStateDetailEl.textContent = '宝宝清醒中 · 精神饱满可互动交流'; if (sleepToggleIcon) sleepToggleIcon.textContent = '😴'; if (sleepToggleActionText) sleepToggleActionText.textContent = '🌙 宝宝睡下了 (开始计时)'; if (btnSleepToggle) { btnSleepToggle.className = 'flex-1 bg-gradient-to-r from-purple-600 to-indigo-600 hover:from-purple-700 hover:to-indigo-700 active:scale-98 text-white font-extrabold text-xs py-3 rounded-2xl shadow-xs transition flex items-center justify-center space-x-2 whitespace-nowrap'; } } // 3. Diaper Status (距上次换尿布已逝时间直接融合) const d = liveStatus.diaper; const lastDiaperTimeEl = document.getElementById('lastDiaperTime'); const lastDiaperDetailEl = document.getElementById('lastDiaperDetail'); if (d && d.hasData) { if (lastDiaperTimeEl) lastDiaperTimeEl.textContent = `距上次 ${d.elapsedText ? d.elapsedText.replace(/前$/, '') : '--'}`; const typeLabel = d.diaperType === 'poop' ? '便便' : (d.diaperType === 'both' ? '尿+便' : '小便'); if (lastDiaperDetailEl) lastDiaperDetailEl.textContent = `上次: ${d.time} ${typeLabel} (${d.operator || '家人'})`; } else { if (lastDiaperTimeEl) lastDiaperTimeEl.textContent = '今日尚未更换'; if (lastDiaperDetailEl) lastDiaperDetailEl.textContent = '上次: 尚未记录'; } } // ---------------------------------------------------- // Custom Goals Renderer in Quick View (One-Tap Badges with Configured Defaults) // ---------------------------------------------------- function renderQuickCustomMetricsGrid() { const container = document.getElementById('quickCustomMetricsGrid'); if (!container) return; container.innerHTML = ''; if (state.customMetrics.length === 0) { container.innerHTML = `
暂无私人目标,点击前往「宝贝档案」添加专属项 ❯
`; return; } state.customMetrics.forEach(metric => { const defVal = metric.default_value || '1'; const isDuration = metric.type === 'duration' || metric.unit === '分钟' || (metric.name && (metric.name.includes('俯趴') || metric.name.includes('Tummy'))); const card = document.createElement('div'); card.className = 'bg-stone-50 hover:bg-emerald-50/80 border border-stone-200 hover:border-emerald-300 rounded-2xl p-2.5 flex items-center justify-between transition text-left shadow-2xs group'; const timerBtn = isDuration ? ` ` : ''; card.innerHTML = `
${metric.icon || '⭐'}
${metric.name}
默认: ${defVal} ${metric.unit || '次'}
${timerBtn}
`; const clickArea = card.querySelector('.metric-click-area'); const logBtn = card.querySelector('.btn-metric-log'); const timerEl = card.querySelector('.btn-metric-timer'); if (clickArea) clickArea.onclick = () => quickLogCustomMetric(metric); if (logBtn) logBtn.onclick = () => quickLogCustomMetric(metric); if (timerEl) { timerEl.onclick = (e) => { e.stopPropagation(); startFocusTimer('custom', parseInt(defVal) || 15); }; } container.appendChild(card); }); } async function quickLogCustomMetric(metric) { const val = metric.default_value || '1'; await createRecord({ activityType: 'custom', durationMinutes: metric.type === 'duration' ? (parseInt(val) || 15) : 1, payload: { metricId: metric.metric_id, name: metric.name, icon: metric.icon, unit: metric.unit, value: val, note: `快捷打卡(默认${val}${metric.unit || '次'})` } }); } // ---------------------------------------------------- // Custom Goals & Defaults Management in Baby Profile View // ---------------------------------------------------- function renderProfileCustomMetricsList() { const container = document.getElementById('profileCustomMetricsList'); if (!container) return; container.innerHTML = ''; if (state.customMetrics.length === 0) { container.innerHTML = '
暂无配置项,点击右上角新建私人目标
'; return; } state.customMetrics.forEach(m => { const card = document.createElement('div'); card.className = 'p-3 rounded-2xl bg-slate-50 border border-slate-200/80 flex items-center justify-between hover:border-indigo-300 transition shadow-2xs'; card.innerHTML = `
${m.icon || '✨'}
${m.name} 默认 ${m.default_value || 1} ${m.unit || '次'}
每日目标: ${m.target_daily || 1} ${m.unit || '次'}
`; container.appendChild(card); }); } function openConfigCustomMetricModal(metricId) { const m = state.customMetrics.find(it => it.metric_id === metricId); if (!m) return; document.getElementById('configMetricId').value = m.metric_id; document.getElementById('configMetricTitle').textContent = `配置【${m.name}】默认值与目标`; document.getElementById('configMetricIconPreview').textContent = m.icon || '⚙️'; document.getElementById('configMetricName').value = m.name; document.getElementById('configMetricIcon').value = m.icon || '✨'; document.getElementById('configMetricUnit').value = m.unit || '次'; document.getElementById('configMetricDefaultValue').value = m.default_value || '1'; document.getElementById('configMetricTargetDaily').value = m.target_daily || 1; openModal('editCustomMetricModal'); } async function submitConfigCustomMetric() { const metricId = document.getElementById('configMetricId').value; const name = document.getElementById('configMetricName').value.trim(); const icon = document.getElementById('configMetricIcon').value.trim() || '✨'; const unit = document.getElementById('configMetricUnit').value.trim() || '次'; const defaultValue = document.getElementById('configMetricDefaultValue').value.trim() || '1'; const targetDaily = parseInt(document.getElementById('configMetricTargetDaily').value) || 1; if (!name) { showToast('指标名称必填', 'warning'); return; } closeModal('editCustomMetricModal'); try { const res = await fetch(`${API_BASE}/custom-metrics/${metricId}`, { method: 'PUT', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ name, icon, unit, defaultValue, targetDaily }) }); const json = await res.json(); if (json.success) { showToast(`【${name}】默认值及配置已更新!`); await loadCustomMetrics(); loadSummaryData(true); } else { showToast(json.error || '保存失败', 'error'); } } catch (err) { showToast('网络错误,保存失败', 'error'); } } async function deleteCustomMetricFromConfig() { const metricId = document.getElementById('configMetricId').value; if (!confirm('确定要停用此项自定义指标吗?')) return; closeModal('editCustomMetricModal'); try { const res = await fetch(`${API_BASE}/custom-metrics/${metricId}`, { method: 'DELETE' }); const json = await res.json(); if (json.success) { showToast('已停用该目标项'); await loadCustomMetrics(); loadSummaryData(true); } } catch (err) { showToast('操作失败', 'error'); } } // ---------------------------------------------------- // ---------------------------------------------------- // Dashboard Health KPI Cards & Progress Meters (用户关注的核心达标评估) // ---------------------------------------------------- function renderKpiCards(data) { const { kpi, baby } = data; if (!kpi) return; const dateLabel = document.getElementById('dashboardDateLabel'); if (dateLabel) dateLabel.textContent = state.currentDate; // 1. Feeding KPI const milkEl = document.getElementById('kpiTotalMilk'); const feedCountBadge = document.getElementById('kpiFeedCountBadge'); const feedAvgIntervalEl = document.getElementById('kpiFeedAvgInterval'); const targetMilkRange = document.getElementById('kpiTargetMilkRange'); const milkProgressBar = document.getElementById('kpiMilkProgressBar'); const totalMilk = kpi.feeding.totalBottleMl || 0; if (milkEl) milkEl.textContent = totalMilk; if (feedCountBadge) feedCountBadge.textContent = `${kpi.feeding.feedCount || 0}次喂养`; if (feedAvgIntervalEl) { feedAvgIntervalEl.textContent = kpi.feeding.avgIntervalHours ? `平均间隔 ${kpi.feeding.avgIntervalHours}h` : '间隔规律'; } const milkMax = (baby && baby.baseline && baby.baseline.dailyMilkRange) ? baby.baseline.dailyMilkRange[1] : 850; if (targetMilkRange && baby && baby.baseline) { targetMilkRange.textContent = `${baby.baseline.dailyMilkRange[0]}~${baby.baseline.dailyMilkRange[1]}ml`; } if (milkProgressBar) { const milkPercent = Math.min(100, Math.round((totalMilk / milkMax) * 100)); milkProgressBar.style.width = `${milkPercent}%`; } // 2. Sleep KPI const sleepEl = document.getElementById('kpiTotalSleep'); const sleepCountBadge = document.getElementById('kpiSleepCountBadge'); const sleepLongestEl = document.getElementById('kpiSleepLongest'); const targetSleepRange = document.getElementById('kpiTargetSleepRange'); const sleepProgressBar = document.getElementById('kpiSleepProgressBar'); if (sleepEl) sleepEl.textContent = kpi.sleep.totalSleepText || '0'; if (sleepCountBadge) sleepCountBadge.textContent = `${kpi.sleep.sleepCount || 0}段小睡`; if (sleepLongestEl) { sleepLongestEl.textContent = kpi.sleep.longestSleepText ? `最长连睡 ${kpi.sleep.longestSleepText}` : '昼夜交替'; } const sleepTargetHours = (baby && baby.baseline && baby.baseline.dailySleepRange) ? baby.baseline.dailySleepRange[1] : 16; if (targetSleepRange && baby && baby.baseline) { targetSleepRange.textContent = `${baby.baseline.dailySleepRange[0]}~${baby.baseline.dailySleepRange[1]}小时`; } if (sleepProgressBar) { const sleepMinutes = kpi.sleep.totalSleepMinutes || 0; const sleepPercent = Math.min(100, Math.round((sleepMinutes / (sleepTargetHours * 60)) * 100)); sleepProgressBar.style.width = `${sleepPercent}%`; } // 3. Diaper KPI const diaperEl = document.getElementById('kpiTotalDiaper'); const diaperBreakdown = document.getElementById('kpiDiaperBreakdown'); const diaperStatusTag = document.getElementById('kpiDiaperStatusTag'); if (diaperEl) diaperEl.textContent = kpi.diaper.diaperCount || 0; if (diaperBreakdown) { diaperBreakdown.textContent = `${kpi.diaper.peeCount || 0}次嘘嘘 · ${kpi.diaper.poopCount || 0}次便便`; } if (diaperStatusTag) { if (kpi.diaper.abnormalStoolDetected) { diaperStatusTag.className = 'text-[9px] font-bold px-1.5 py-0.2 rounded-full bg-rose-200 text-rose-800'; diaperStatusTag.textContent = '异常需留意'; } else { diaperStatusTag.className = 'text-[9px] font-bold px-1.5 py-0.2 rounded-full bg-sky-200/70 text-sky-800'; diaperStatusTag.textContent = (kpi.diaper.peeCount || 0) >= 6 ? '水分充足' : '状态正常'; } } // 4. Custom KPI const customSummaryEl = document.getElementById('kpiCustomSummary'); const customPercentEl = document.getElementById('kpiCustomPercent'); const customDetailEl = document.getElementById('kpiCustomDetail'); const completed = kpi.custom ? kpi.custom.completedGoals : 0; const totalGoals = (kpi.custom && kpi.custom.totalGoals > 0) ? kpi.custom.totalGoals : (state.customMetrics.length || 1); if (customSummaryEl) customSummaryEl.textContent = completed; if (customPercentEl) { const pct = totalGoals > 0 ? Math.min(100, Math.round((completed / totalGoals) * 100)) : 0; customPercentEl.textContent = `${pct}%`; } if (customDetailEl && kpi.custom && kpi.custom.items) { const names = Object.values(kpi.custom.items).map(i => `${i.name}${i.count > 0 ? '✓' : ''}`).slice(0, 3).join(' · '); customDetailEl.textContent = names || '暂无专属目标'; } } // ---------------------------------------------------- // 24-Hour Rhythm Timeline (全天吃睡作息规律流 - 解决用户最大痛点) // ---------------------------------------------------- function renderRhythmStream(timeline = []) { const container = document.getElementById('rhythmStreamContainer'); if (!container) return; container.innerHTML = ''; if (!timeline || timeline.length === 0) { container.innerHTML = `
🐣
当天尚未记录任何作息
前往「快速打卡」记录宝宝的第一笔活动吧~
`; return; } // Sort ascending by start_time to show natural rhythm of the day const sorted = [...timeline].sort((a, b) => new Date(a.start_time) - new Date(b.start_time)); sorted.forEach(r => { const typeMeta = { bottle: { icon: '🍼', name: '瓶喂', color: 'bg-amber-500 text-white', border: 'border-amber-200/80 bg-amber-50/40' }, breastfeed: { icon: '🤱', name: '亲喂', color: 'bg-rose-500 text-white', border: 'border-rose-200/80 bg-rose-50/40' }, sleep: { icon: '😴', name: '睡眠', color: 'bg-purple-600 text-white', border: 'border-purple-200/80 bg-purple-50/40' }, diaper: { icon: '💧', name: '换尿布', color: 'bg-sky-500 text-white', border: 'border-sky-200/80 bg-sky-50/40' }, custom: { icon: '✨', name: '日常目标', color: 'bg-emerald-600 text-white', border: 'border-emerald-200/80 bg-emerald-50/40' } }[r.activity_type] || { icon: '📌', name: '日常', color: 'bg-slate-500 text-white', border: 'border-slate-200 bg-slate-50' }; let detail = ''; if (r.activity_type === 'bottle') { detail = `${r.payload.amountMl || 0}ml (${r.payload.milkType === 'formula' ? '配方奶' : '母乳'})`; } else if (r.activity_type === 'breastfeed') { detail = `亲喂 ${r.duration_minutes || 0}分钟 (左右各${r.payload.leftMinutes || 10}m/${r.payload.rightMinutes || 10}m)`; } else if (r.activity_type === 'sleep') { const endStr = r.end_time ? r.end_time.substring(11, 16) : '进行中...'; detail = `安睡 ${r.duration_minutes || 0}分钟 (~ ${endStr})`; } else if (r.activity_type === 'diaper') { const dt = r.payload.diaperType === 'poop' ? '便便 💩' : (r.payload.diaperType === 'both' ? '尿+便' : '小便 💧'); detail = `${dt} ${r.payload.poopColor ? '(' + r.payload.poopColor + ')' : ''}`; } else if (r.activity_type === 'custom') { detail = `${r.payload.name || '私人目标'}: ${r.payload.value || 1}${r.payload.unit || '次'}`; } const note = r.payload.note ? `· ${r.payload.note}` : ''; const card = document.createElement('div'); card.className = `border rounded-2xl p-3 flex items-center justify-between shadow-2xs hover:shadow-xs transition ${typeMeta.border}`; card.innerHTML = `
${r.start_time.substring(11, 16)} ${r.payload.icon || typeMeta.icon}
${typeMeta.name} 【${r.operator_name || '家人'}】
${detail}${note}
`; container.appendChild(card); }); } // ---------------------------------------------------- // 24-Hour Circadian 4-Period Blocks (Mobile Friendly Touch Cards) // Replaces tiny unclickable Gantt dots with generous cards! // ---------------------------------------------------- function renderPeriodSlots(slots) { const container = document.getElementById('periodSlotsContainer'); if (!container) return; container.innerHTML = ''; if (!slots) return; const slotKeys = ['dawn', 'morning', 'afternoon', 'evening']; const slotMeta = { dawn: { title: '🌅 清晨醒脑段', time: '06:00 ~ 11:00', bg: 'bg-amber-50/50 border-amber-200/60' }, morning: { title: '☀️ 午后日常段', time: '11:00 ~ 17:00', bg: 'bg-sky-50/50 border-sky-200/60' }, afternoon: { title: '🌇 傍晚小憩段', time: '17:00 ~ 21:00', bg: 'bg-orange-50/50 border-orange-200/60' }, evening: { title: '🌙 夜间安睡段', time: '21:00 ~ 06:00', bg: 'bg-purple-50/50 border-purple-200/60' } }; slotKeys.forEach(key => { const slot = slots[key] || { items: [] }; const meta = slotMeta[key]; const card = document.createElement('div'); card.className = `border rounded-2xl p-3 space-y-2 ${meta.bg}`; let itemsHtml = ''; if (slot.items.length === 0) { itemsHtml = '
此时段无记录
'; } else { itemsHtml = `
${slot.items.map(it => `
${it.icon} ${it.time} ${it.desc} (${it.operator})
`).join('')}
`; } card.innerHTML = `
${meta.title} (${meta.time})
${slot.items.length} 笔记录
${itemsHtml} `; container.appendChild(card); }); } function showRecordDetailToast(time, desc, operator) { showToast(`【${time}】${desc} · 操作人: ${operator}`); } // ---------------------------------------------------- // Segmented Deep-Dive Panels (Feeding, Sleep, Diaper, Custom) // ---------------------------------------------------- function renderSpecDeepDives(data) { const { kpi, timeline } = data; // 1. Feeding Spec const feedListContainer = document.getElementById('specFeedingList'); const avgFeedIntervalEl = document.getElementById('specFeedAvgInterval'); if (avgFeedIntervalEl) { avgFeedIntervalEl.textContent = `平均间隔: ${kpi.feeding.avgIntervalHours || '--'}h`; } if (feedListContainer) { feedListContainer.innerHTML = ''; const feedItems = timeline.filter(r => r.activity_type === 'bottle' || r.activity_type === 'breastfeed'); if (feedItems.length === 0) { feedListContainer.innerHTML = '
今日暂无喂养记录
'; } else { feedItems.forEach(r => { const item = document.createElement('div'); item.className = 'p-2.5 rounded-xl bg-amber-50/70 border border-amber-200/60 flex items-center justify-between'; const isBottle = r.activity_type === 'bottle'; const valText = isBottle ? `${r.payload.amountMl || 0}ml (${r.payload.milkType === 'formula' ? '配方奶' : '母乳'})` : `亲喂 (左右各${r.payload.leftMinutes || 10}m/${r.payload.rightMinutes || 10}m)`; item.innerHTML = `
${isBottle ? '🍼' : '🤱'}
${r.start_time.substring(11, 16)} · ${valText}
记录人: ${r.operator_name || '家人'} ${r.payload.note ? '· ' + r.payload.note : ''}
`; feedListContainer.appendChild(item); }); } } // 2. Sleep Spec const sleepListContainer = document.getElementById('specSleepList'); const longestSleepEl = document.getElementById('specSleepLongest'); if (longestSleepEl) { longestSleepEl.textContent = `最长连睡: ${kpi.sleep.longestSleepText || '--'}`; } if (sleepListContainer) { sleepListContainer.innerHTML = ''; const sleepItems = timeline.filter(r => r.activity_type === 'sleep'); if (sleepItems.length === 0) { sleepListContainer.innerHTML = '
今日暂无睡眠记录
'; } else { sleepItems.forEach(r => { const item = document.createElement('div'); item.className = 'p-2.5 rounded-xl bg-purple-50/70 border border-purple-200/60 flex items-center justify-between'; const endText = r.end_time ? r.end_time.substring(11, 16) : '睡着中...'; item.innerHTML = `
😴
${r.start_time.substring(11, 16)} ~ ${endText} (${r.duration_minutes || 0}分钟)
记录人: ${r.operator_name || '家人'}
`; sleepListContainer.appendChild(item); }); } } // 3. Diaper Spec const diaperListContainer = document.getElementById('specDiaperList'); const diaperHealthEl = document.getElementById('specDiaperHealth'); if (diaperHealthEl) { diaperHealthEl.textContent = kpi.diaper.abnormalStoolDetected ? '⚠️ 发现异常颜色' : '性状正常 ✓'; } if (diaperListContainer) { diaperListContainer.innerHTML = ''; const diaperItems = timeline.filter(r => r.activity_type === 'diaper'); if (diaperItems.length === 0) { diaperListContainer.innerHTML = '
今日暂无换尿布记录
'; } else { diaperItems.forEach(r => { const item = document.createElement('div'); item.className = 'p-2.5 rounded-xl bg-sky-50/70 border border-sky-200/60 flex items-center justify-between'; const dt = r.payload.diaperType === 'poop' ? '便便 💩' : (r.payload.diaperType === 'both' ? '小便+大便' : '纯小便 💧'); item.innerHTML = `
${r.payload.diaperType === 'poop' ? '💩' : '💧'}
${r.start_time.substring(11, 16)} · ${dt}
记录人: ${r.operator_name || '家人'} ${r.payload.note ? '· ' + r.payload.note : ''}
`; diaperListContainer.appendChild(item); }); } } // 4. Custom Goals Spec const customListContainer = document.getElementById('specCustomList'); if (customListContainer) { customListContainer.innerHTML = ''; if (state.customMetrics.length === 0) { customListContainer.innerHTML = '
暂无自定义目标,可点击右上角创建
'; } else { state.customMetrics.forEach(m => { const kpiItem = (kpi.custom && kpi.custom.items) ? kpi.custom.items[m.metric_id] : null; const currentCount = kpiItem ? kpiItem.count : 0; const target = m.target_daily || 1; const percent = Math.min(100, Math.round((currentCount / target) * 100)); const item = document.createElement('div'); item.className = 'p-3 rounded-xl bg-emerald-50/70 border border-emerald-200/60 space-y-2'; item.innerHTML = `
${m.icon || '⭐'} ${m.name}
${currentCount} / ${target} ${m.unit || '次'} (${percent}%)
`; customListContainer.appendChild(item); }); } } } // ---------------------------------------------------- // 7-Day Trend Chart // ---------------------------------------------------- function renderTrendChart(trends) { const container = document.getElementById('trendChartContainer'); const datesContainer = document.getElementById('trendChartDates'); if (!container || !datesContainer) return; container.innerHTML = ''; datesContainer.innerHTML = ''; if (!trends || trends.length === 0) return; const maxVal = Math.max(900, ...trends.map(t => t.totalMilkMl || 0)); trends.forEach(t => { const heightPercent = Math.min(100, Math.round(((t.totalMilkMl || 0) / maxVal) * 100)); const barCol = document.createElement('div'); barCol.className = 'flex flex-col items-center justify-end h-full flex-1 group cursor-pointer'; barCol.onclick = () => showToast(`${t.date}: 奶量 ${t.totalMilkMl}ml · 睡眠 ${t.totalSleepHours}h`); barCol.innerHTML = ` ${t.totalMilkMl > 0 ? t.totalMilkMl : ''}
`; container.appendChild(barCol); const dSpan = document.createElement('span'); dSpan.className = 'flex-1 text-center'; dSpan.textContent = t.dayLabel; datesContainer.appendChild(dSpan); }); } // ---------------------------------------------------- // Universal Common Timeline Drawer / Modal // ---------------------------------------------------- function updateTimelineCount(timeline = []) { const count = timeline.length; const badge = document.getElementById('quickTimelineCountBadge'); if (badge) badge.textContent = `${count}条`; const headerBadge = document.getElementById('headerTimelineCountBadge'); if (headerBadge) headerBadge.textContent = `${count}`; } function openTimelineModal() { const subTitle = document.getElementById('timelineModalSubtitle'); if (subTitle) subTitle.textContent = `${state.currentDate} 流水记录列表`; renderModalTimeline(); openModal('timelineModal'); } function renderModalTimeline() { const listEl = document.getElementById('modalTimelineList'); if (!listEl) return; listEl.innerHTML = ''; const timeline = (state.summary && state.summary.timeline) ? state.summary.timeline : []; const filtered = state.timelineFilter === 'all' ? timeline : timeline.filter(r => r.activity_type === state.timelineFilter); if (filtered.length === 0) { listEl.innerHTML = '
当前筛选条件下暂无打卡记录
'; return; } filtered.forEach(r => { const typeMeta = { bottle: { icon: '🍼', name: '瓶喂', color: 'text-amber-600 bg-amber-50 border-amber-200' }, breastfeed: { icon: '🤱', name: '亲喂', color: 'text-rose-600 bg-rose-50 border-rose-200' }, sleep: { icon: '😴', name: '睡眠', color: 'text-purple-600 bg-purple-50 border-purple-200' }, diaper: { icon: '💧', name: '尿布', color: 'text-sky-600 bg-sky-50 border-sky-200' }, custom: { icon: '✨', name: '自定义', color: 'text-emerald-600 bg-emerald-50 border-emerald-200' } }[r.activity_type] || { icon: '📌', name: '日常', color: 'text-slate-600 bg-slate-50 border-slate-200' }; let detail = ''; if (r.activity_type === 'bottle') { detail = `${r.payload.amountMl || 0} ml (${r.payload.milkType === 'formula' ? '配方奶' : '母乳'})`; } else if (r.activity_type === 'breastfeed') { detail = `亲喂 ${r.duration_minutes || 0}m (左${r.payload.leftMinutes || 10}m/右${r.payload.rightMinutes || 10}m)`; } else if (r.activity_type === 'sleep') { detail = `睡眠: ${r.duration_minutes || 0} 分钟 (${r.end_time ? '已结束' : '进行中'})`; } else if (r.activity_type === 'diaper') { const dt = r.payload.diaperType === 'poop' ? '便便' : (r.payload.diaperType === 'both' ? '尿+便' : '小便'); detail = `${dt} ${r.payload.poopColor ? '(' + r.payload.poopColor + ')' : ''}`; } else if (r.activity_type === 'custom') { detail = `${r.payload.name || '私人目标'}: ${r.payload.value || 1} ${r.payload.unit || '次'}`; } const note = r.payload.note ? `· ${r.payload.note}` : ''; const row = document.createElement('div'); row.className = 'pt-2.5 pb-2 flex items-start justify-between'; row.innerHTML = `
${r.payload.icon || typeMeta.icon}
${r.start_time.substring(11, 16)} ${typeMeta.name} 【${r.operator_name || '家人'}】
${detail}${note}
`; listEl.appendChild(row); }); } // ---------------------------------------------------- // Edit Activity Record Modal Logic (修改某项流水记录) // ---------------------------------------------------- function toLocalIso(dtStr) { if (!dtStr) return ''; const d = new Date(dtStr); const pad = n => String(n).padStart(2, '0'); return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}T${pad(d.getHours())}:${pad(d.getMinutes())}`; } function openEditRecordModal(recordId) { const timeline = (state.summary && state.summary.timeline) ? state.summary.timeline : []; const rec = timeline.find(r => r.record_id === recordId); if (!rec) return; document.getElementById('editRecordId').value = rec.record_id; document.getElementById('editRecordType').value = rec.activity_type; document.getElementById('editRecordStartTime').value = toLocalIso(rec.start_time); document.getElementById('editRecordEndTime').value = toLocalIso(rec.end_time); document.getElementById('editRecordOperator').value = rec.operator_name || '宝妈'; document.getElementById('editRecordNote').value = rec.payload.note || ''; const endGroup = document.getElementById('editRecordEndGroup'); const valGroup = document.getElementById('editRecordValGroup'); const diaperGroup = document.getElementById('editRecordDiaperGroup'); const valLabel = document.getElementById('editRecordValLabel'); const valInput = document.getElementById('editRecordValInput'); if (rec.activity_type === 'bottle') { endGroup.classList.add('hidden'); diaperGroup.classList.add('hidden'); valGroup.classList.remove('hidden'); valLabel.textContent = '冲奶量 (ml)'; valInput.value = rec.payload.amountMl || 120; } else if (rec.activity_type === 'sleep') { endGroup.classList.remove('hidden'); diaperGroup.classList.add('hidden'); valGroup.classList.remove('hidden'); valLabel.textContent = '睡眠时长 (分钟)'; valInput.value = rec.duration_minutes || 60; } else if (rec.activity_type === 'breastfeed') { endGroup.classList.remove('hidden'); diaperGroup.classList.add('hidden'); valGroup.classList.remove('hidden'); valLabel.textContent = '亲喂总时长 (分钟)'; valInput.value = rec.duration_minutes || 20; } else if (rec.activity_type === 'diaper') { endGroup.classList.add('hidden'); valGroup.classList.add('hidden'); diaperGroup.classList.remove('hidden'); document.getElementById('editRecordDiaperType').value = rec.payload.diaperType || 'pee'; } else if (rec.activity_type === 'custom') { endGroup.classList.add('hidden'); diaperGroup.classList.add('hidden'); valGroup.classList.remove('hidden'); valLabel.textContent = `打卡数值 (${rec.payload.unit || '数值'})`; valInput.value = rec.payload.value || 1; } openModal('editRecordModal'); } async function submitEditRecord() { const recordId = document.getElementById('editRecordId').value; const type = document.getElementById('editRecordType').value; const startLocal = document.getElementById('editRecordStartTime').value; const endLocal = document.getElementById('editRecordEndTime').value; const operator = document.getElementById('editRecordOperator').value; const note = document.getElementById('editRecordNote').value; const val = document.getElementById('editRecordValInput').value; if (!startLocal) { showToast('发生时刻不能为空', 'warning'); return; } const startTime = startLocal.replace('T', ' ') + ':00'; const endTime = endLocal ? endLocal.replace('T', ' ') + ':00' : null; const timeline = (state.summary && state.summary.timeline) ? state.summary.timeline : []; const existing = timeline.find(r => r.record_id === recordId) || {}; const payload = { ...(existing.payload || {}), note }; let durationMinutes = existing.duration_minutes || 0; if (type === 'bottle') { payload.amountMl = parseInt(val) || 120; } else if (type === 'sleep') { durationMinutes = parseInt(val) || (endTime ? Math.max(1, Math.round((new Date(endTime) - new Date(startTime)) / 60000)) : 60); } else if (type === 'breastfeed') { durationMinutes = parseInt(val) || 20; payload.leftMinutes = Math.round(durationMinutes / 2); payload.rightMinutes = Math.round(durationMinutes / 2); } else if (type === 'diaper') { payload.diaperType = document.getElementById('editRecordDiaperType').value; } else if (type === 'custom') { payload.value = val || 1; } closeModal('editRecordModal'); try { const res = await fetch(`${API_BASE}/records/${recordId}`, { method: 'PUT', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ startTime, endTime, durationMinutes, payload, operatorName: operator }) }); const json = await res.json(); if (json.success) { showToast('记录修改成功并已更新!'); await loadSummaryData(); renderModalTimeline(); } else { showToast(json.error || '修改失败', 'error'); } } catch (err) { showToast('网络错误,修改失败', 'error'); } } // ---------------------------------------------------- // Baby Profile Management & Search // ---------------------------------------------------- function renderBabiesList() { const container = document.getElementById('babiesProfileList'); if (!container) return; container.innerHTML = ''; const filtered = state.babies.filter(b => { if (!state.babySearchQuery) return true; return b.name.toLowerCase().includes(state.babySearchQuery); }); if (filtered.length === 0) { container.innerHTML = '
当前家庭暂无宝宝档案,点击上方「+ 新增宝宝」为本家庭创建首位宝宝
'; return; } filtered.forEach(baby => { const isSelected = baby.baby_id === state.currentBabyId; const card = document.createElement('div'); card.className = `p-4 rounded-2xl border transition flex items-center justify-between ${isSelected ? 'bg-indigo-50/70 border-indigo-500 shadow-xs' : 'bg-white border-slate-200 hover:border-slate-300'}`; card.innerHTML = `
${baby.name.substring(0, 1)}
${baby.name} ${baby.gender === 'boy' ? '👦 小王子' : '👧 小公主'} ${isSelected ? '当前记录中' : ''}
出生: ${baby.birth_date} (${baby.ageText || baby.ageDays + '天'})
${!isSelected ? `` : ''}
`; container.appendChild(card); }); } function selectBaby(babyId) { state.currentBabyId = babyId; localStorage.setItem('selected_baby_id', babyId); updateCurrentBabyDisplay(); renderBabiesList(); renderProfileConfigMenu(); applyRolePreferences(state.currentOperator); loadCustomMetrics(); loadSummaryData(); showToast('已切换至目标宝贝!'); switchTab('quick'); } function openAddBabyModal() { document.getElementById('babyFormModalTitle').textContent = '👶 新增宝宝档案'; document.getElementById('editBabyId').value = ''; document.getElementById('formBabyName').value = ''; document.getElementById('formBabyBirth').value = getLocalDateString(); document.getElementById('formBabyGender').value = 'boy'; openModal('babyFormModal'); } function openEditBabyModal(babyId) { const baby = state.babies.find(b => b.baby_id === babyId); if (!baby) return; document.getElementById('babyFormModalTitle').textContent = '✏️ 编辑宝宝资料'; document.getElementById('editBabyId').value = baby.baby_id; document.getElementById('formBabyName').value = baby.name; document.getElementById('formBabyBirth').value = baby.birth_date; document.getElementById('formBabyGender').value = baby.gender || 'boy'; openModal('babyFormModal'); } async function saveBabyProfile() { const babyId = document.getElementById('editBabyId').value; const name = document.getElementById('formBabyName').value.trim(); const birthDate = document.getElementById('formBabyBirth').value; const gender = document.getElementById('formBabyGender').value; const colorInput = document.querySelector('input[name="babyColor"]:checked'); const themeColor = colorInput ? colorInput.value : '#3B82F6'; if (!name || !birthDate) { showToast('请填写宝宝姓名和出生日期', 'warning'); return; } closeModal('babyFormModal'); try { const url = babyId ? `${API_BASE}/babies/${babyId}` : `${API_BASE}/babies`; const method = babyId ? 'PUT' : 'POST'; const res = await fetch(url, { method, headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ babyId, name, birthDate, gender, themeColor, familyId: state.currentFamilyId }) }); const json = await res.json(); if (json.success) { showToast(babyId ? '宝宝资料已更新!' : '新宝宝创建成功!'); await loadBabies(); if (!babyId && json.data) { selectBaby(json.data.baby_id); } } else { showToast(json.error || '保存失败', 'error'); } } catch (err) { console.error('Save baby error:', err); showToast('网络错误,保存失败', 'error'); } } // ---------------------------------------------------- // Custom Metric Add Modal // ---------------------------------------------------- function openAddCustomMetricModal() { document.getElementById('customMetricName').value = ''; document.getElementById('customMetricIcon').value = '💊'; document.getElementById('customMetricUnit').value = '次'; document.getElementById('customMetricDefaultValue').value = '1'; document.getElementById('customMetricTarget').value = '1'; openModal('addCustomMetricModal'); } async function submitCustomMetric() { const name = document.getElementById('customMetricName').value.trim(); const icon = document.getElementById('customMetricIcon').value.trim() || '✨'; const unit = document.getElementById('customMetricUnit').value.trim() || '次'; const defaultValue = document.getElementById('customMetricDefaultValue').value.trim() || '1'; const target = parseInt(document.getElementById('customMetricTarget').value) || 1; if (!name) { showToast('请输入目标名称', 'warning'); return; } closeModal('addCustomMetricModal'); try { const res = await fetch(`${API_BASE}/custom-metrics`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ babyId: state.currentBabyId, name, icon, unit, defaultValue, dailyTarget: target, type: 'count' }) }); const json = await res.json(); if (json.success) { showToast(`私人目标【${name}】创建成功!`); await loadCustomMetrics(); loadSummaryData(true); } else { showToast(json.error || '创建失败', 'error'); } } catch (err) { showToast('网络错误', 'error'); } } // ---------------------------------------------------- // Care Guides & Video Player // ---------------------------------------------------- function renderCareGuides(filterCat = 'all') { const container = document.getElementById('careGuidesList'); if (!container) return; container.innerHTML = ''; const items = filterCat === 'all' ? state.careGuides : state.careGuides.filter(g => g.category === filterCat); items.forEach(guide => { const card = document.createElement('div'); card.className = 'bg-white border border-slate-200 rounded-2xl overflow-hidden shadow-xs hover:shadow-md transition'; card.innerHTML = `
${guide.title}
▶
${guide.categoryName} ${guide.durationText}

${guide.title}

${guide.subtitle}

${guide.keyPoints[0]}
`; container.appendChild(card); }); } function openCareGuideModal(guideId) { const guide = state.careGuides.find(g => g.id === guideId); if (!guide) return; const catEl = document.getElementById('modalGuideCategory'); const titleEl = document.getElementById('modalGuideTitle'); const videoEl = document.getElementById('modalGuideVideo'); const pointsList = document.getElementById('modalGuidePoints'); const cautionsEl = document.getElementById('modalGuideCautions'); if (catEl) catEl.textContent = guide.categoryName; if (titleEl) titleEl.textContent = guide.title; if (videoEl) { videoEl.src = guide.videoUrl; videoEl.poster = guide.posterUrl || ''; videoEl.onerror = () => { console.warn(`Video failed to load: ${guide.videoUrl}`); }; videoEl.load(); } if (pointsList) pointsList.innerHTML = guide.keyPoints.map(p => `
  • ${p}
  • `).join(''); if (cautionsEl) cautionsEl.innerHTML = guide.cautions.map(c => `

    ${c}

    `).join(''); openModal('careGuideModal'); } // ---------------------------------------------------- // One-Tap Quick Log Handlers & Role Preferences // ---------------------------------------------------- // ---------------------------------------------------- // Care & Profile Configuration Menu Functions // ---------------------------------------------------- let pendingBottleMl = 120; function switchConfigSubTab(tab) { const tabs = ['feeding', 'roles', 'metrics']; tabs.forEach(t => { const btn = document.getElementById(`cfgSubTabBtn${t.charAt(0).toUpperCase() + t.slice(1)}`); const panel = document.getElementById(`cfgSubPanel${t.charAt(0).toUpperCase() + t.slice(1)}`); if (t === tab) { if (btn) { btn.className = 'flex-1 py-1.5 rounded-xl bg-white text-indigo-700 shadow-2xs transition whitespace-nowrap cursor-pointer font-bold'; } if (panel) panel.classList.remove('hidden'); } else { if (btn) { btn.className = 'flex-1 py-1.5 rounded-xl text-slate-600 hover:text-slate-900 transition whitespace-nowrap cursor-pointer font-bold'; } if (panel) panel.classList.add('hidden'); } }); } function renderProfileConfigMenu() { const baby = state.babies.find(b => b.baby_id === state.currentBabyId); const babyNameEl = document.getElementById('cfgBabyFeedingName'); if (babyNameEl) { babyNameEl.textContent = baby ? baby.name : '未选择宝宝'; } let defConfig = {}; if (baby && baby.default_config) { try { defConfig = typeof baby.default_config === 'string' ? JSON.parse(baby.default_config) : baby.default_config; } catch (e) { defConfig = {}; } } // Populate baby feeding defaults const mode = defConfig.defaultFeedingMode || 'bottle'; const modeRadio = document.querySelector(`input[name="cfgDefaultMode"][value="${mode}"]`); if (modeRadio) modeRadio.checked = true; const bottleMl = defConfig.defaultBottleMl || state.lastBottleMl || 120; const inputBottle = document.getElementById('cfgInputBottleMl'); const displayBottle = document.getElementById('cfgBottleMlDisplay'); if (inputBottle) inputBottle.value = bottleMl; if (displayBottle) displayBottle.textContent = bottleMl; updateCfgBottleChips(bottleMl); const bfMinutes = defConfig.defaultBfMinutes || state.bfTargetDuration || 20; const inputBf = document.getElementById('cfgInputBfMinutes'); const displayBf = document.getElementById('cfgBfMinDisplay'); if (inputBf) inputBf.value = bfMinutes; if (displayBf) displayBf.textContent = bfMinutes; updateCfgBfChips(bfMinutes); const milkType = defConfig.defaultMilkType || 'formula'; const milkRadio = document.querySelector(`input[name="cfgDefaultMilkType"][value="${milkType}"]`); if (milkRadio) milkRadio.checked = true; // Populate roles dropdown populateConfigRolesSelect(); loadRoleConfigForSelectedRole(); } function updateCfgBottleChips(amount) { document.querySelectorAll('.cfg-bottle-chip').forEach(chip => { if (parseInt(chip.textContent.trim()) === parseInt(amount)) { chip.className = 'cfg-bottle-chip active py-1.5 rounded-xl bg-amber-500 text-white transition cursor-pointer font-bold shadow-2xs'; } else { chip.className = 'cfg-bottle-chip py-1.5 rounded-xl bg-slate-100 hover:bg-amber-100 transition cursor-pointer font-bold text-slate-700'; } }); } function setCfgBottlePreset(ml) { const input = document.getElementById('cfgInputBottleMl'); const display = document.getElementById('cfgBottleMlDisplay'); if (input) input.value = ml; if (display) display.textContent = ml; updateCfgBottleChips(ml); } function onCfgBottleInput(val) { const display = document.getElementById('cfgBottleMlDisplay'); if (display) display.textContent = val || 0; updateCfgBottleChips(val); } function updateCfgBfChips(minutes) { document.querySelectorAll('.cfg-bf-chip').forEach(chip => { if (parseInt(chip.textContent.trim()) === parseInt(minutes)) { chip.className = 'cfg-bf-chip active py-1.5 rounded-xl bg-rose-500 text-white transition cursor-pointer font-bold shadow-2xs'; } else { chip.className = 'cfg-bf-chip py-1.5 rounded-xl bg-slate-100 hover:bg-rose-100 transition cursor-pointer font-bold text-slate-700'; } }); } function setCfgBfPreset(min) { const input = document.getElementById('cfgInputBfMinutes'); const display = document.getElementById('cfgBfMinDisplay'); if (input) input.value = min; if (display) display.textContent = min; updateCfgBfChips(min); } function onCfgBfInput(val) { const display = document.getElementById('cfgBfMinDisplay'); if (display) display.textContent = val || 0; updateCfgBfChips(val); } async function saveBabyFeedingDefaults() { if (!state.currentBabyId) { showToast('请先选择或新增宝宝', 'warning'); return; } const mode = document.querySelector('input[name="cfgDefaultMode"]:checked')?.value || 'bottle'; const bottleMl = parseInt(document.getElementById('cfgInputBottleMl')?.value || '120'); const bfMinutes = parseInt(document.getElementById('cfgInputBfMinutes')?.value || '20'); const milkType = document.querySelector('input[name="cfgDefaultMilkType"]:checked')?.value || 'formula'; const newDefaults = { defaultFeedingMode: mode, defaultBottleMl: bottleMl, defaultBfMinutes: bfMinutes, defaultMilkType: milkType }; try { const res = await fetch(`${API_BASE}/babies/${state.currentBabyId}/defaults`, { method: 'PUT', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ defaultConfig: newDefaults }) }); const json = await res.json(); if (json.success) { showToast('宝宝喂养打卡默认配置已更新!'); const targetBaby = state.babies.find(b => b.baby_id === state.currentBabyId); if (targetBaby) { targetBaby.default_config = newDefaults; } applyRolePreferences(state.currentOperator); } else { showToast(json.error || '保存失败', 'error'); } } catch (err) { console.error('Failed to save baby defaults:', err); showToast('网络错误,保存失败', 'error'); } } function populateConfigRolesSelect() { const select = document.getElementById('cfgRoleSelect'); if (!select) return; const currentVal = select.value; const currentFam = state.families.find(f => f.family_id === state.currentFamilyId); const memberRoles = (currentFam && currentFam.members) ? currentFam.members.map(m => m.role_name) : []; const defaultRoles = ['宝妈', '宝爸', '月嫂', '外婆', '奶奶', '育儿嫂']; const allRoles = Array.from(new Set([...memberRoles, ...defaultRoles])); select.innerHTML = allRoles.map(role => { const icon = ROLE_ICONS[role] || '👤'; return ``; }).join(''); if (currentVal && allRoles.includes(currentVal)) { select.value = currentVal; } else if (allRoles.includes(state.currentOperator)) { select.value = state.currentOperator; } } function loadRoleConfigForSelectedRole() { const select = document.getElementById('cfgRoleSelect'); if (!select) return; const role = select.value; const pref = state.rolePreferences[role] || {}; const mode = pref.defaultFeedingMode || ''; const modeRadio = document.querySelector(`input[name="cfgRoleMode"][value="${mode}"]`); if (modeRadio) modeRadio.checked = true; const bottleInput = document.getElementById('cfgRoleBottleMl'); if (bottleInput) bottleInput.value = pref.defaultBottleMl || ''; const bfInput = document.getElementById('cfgRoleBfMinutes'); if (bfInput) bfInput.value = pref.defaultBfMinutes || ''; } async function saveRolePreferencesFromProfile() { const select = document.getElementById('cfgRoleSelect'); if (!select) return; const role = select.value; const mode = document.querySelector('input[name="cfgRoleMode"]:checked')?.value || ''; const bottleMlStr = document.getElementById('cfgRoleBottleMl')?.value?.trim(); const bfMinStr = document.getElementById('cfgRoleBfMinutes')?.value?.trim(); const pref = {}; if (mode) pref.defaultFeedingMode = mode; if (bottleMlStr && !isNaN(parseInt(bottleMlStr))) pref.defaultBottleMl = parseInt(bottleMlStr); if (bfMinStr && !isNaN(parseInt(bfMinStr))) pref.defaultBfMinutes = parseInt(bfMinStr); state.rolePreferences[role] = pref; localStorage.setItem('baby_role_preferences', JSON.stringify(state.rolePreferences)); if (state.currentFamilyId) { try { await fetch(`${API_BASE}/families/${state.currentFamilyId}/members/${encodeURIComponent(role)}/preferences`, { method: 'PUT', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ preferences: pref }) }); } catch (e) { console.warn('Failed to sync role preference:', e); } } showToast(`【${role}】专属偏好配置已保存!`); if (role === state.currentOperator) { applyRolePreferences(role); } } // Apply role preferences when operator changes or baby changes function applyRolePreferences(roleName) { const baby = state.babies.find(b => b.baby_id === state.currentBabyId); let defConfig = {}; if (baby && baby.default_config) { try { defConfig = typeof baby.default_config === 'string' ? JSON.parse(baby.default_config) : baby.default_config; } catch (e) { defConfig = {}; } } const pref = state.rolePreferences[roleName] || {}; const defaultMode = pref.defaultFeedingMode || defConfig.defaultFeedingMode || (roleName === '宝妈' ? 'breastfeed' : 'bottle'); const bottleMl = pref.defaultBottleMl || defConfig.defaultBottleMl || state.lastBottleMl || 120; const bfMinutes = pref.defaultBfMinutes || defConfig.defaultBfMinutes || state.bfTargetDuration || 20; setFeedingMode(defaultMode, false); selectBottleAmount(bottleMl, false); setBfTargetDuration(bfMinutes, false); const btnLast = document.getElementById('btnLastBottleAmount'); if (btnLast) btnLast.textContent = `${bottleMl}ml`; const bfDurText = document.getElementById('quickBfDurationText'); if (bfDurText) bfDurText.textContent = `${bfMinutes}m`; const bfSecText = document.getElementById('quickBfSecText'); if (bfSecText) bfSecText.textContent = `${bfMinutes}m`; } // Persist role preference locally and async sync to server function saveRolePreference(key, value) { const role = state.currentOperator; if (!state.rolePreferences[role]) { state.rolePreferences[role] = {}; } state.rolePreferences[role][key] = value; localStorage.setItem('baby_role_preferences', JSON.stringify(state.rolePreferences)); if (state.currentFamilyId) { fetch(`${API_BASE}/families/${state.currentFamilyId}/members/${encodeURIComponent(role)}/preferences`, { method: 'PUT', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ preferences: state.rolePreferences[role] }) }).catch(e => console.warn('Failed to sync role preference:', e)); } } // Toggle between Breastfeed and Bottle modes function setFeedingMode(mode, save = true) { state.feedingMode = mode; localStorage.setItem('last_feeding_mode', mode); const btnBf = document.getElementById('btnModeBreastfeed'); const btnBottle = document.getElementById('btnModeBottle'); const secBottle = document.getElementById('feedBottleSection'); const secBf = document.getElementById('feedBreastfeedSection'); const cardIcon = document.getElementById('feedingCardIcon'); const cardTitle = document.getElementById('feedingCardTitle'); if (mode === 'breastfeed') { if (btnBf) { btnBf.className = 'flex-1 py-1.5 rounded-lg transition bg-white text-rose-700 shadow-2xs flex items-center justify-center space-x-1 whitespace-nowrap font-bold cursor-pointer'; } if (btnBottle) { btnBottle.className = 'flex-1 py-1.5 rounded-lg transition text-stone-600 bg-transparent flex items-center justify-center space-x-1 whitespace-nowrap font-bold cursor-pointer'; } if (secBottle) secBottle.classList.add('hidden'); if (secBf) secBf.classList.remove('hidden'); if (cardIcon) cardIcon.textContent = '🤱'; if (cardTitle) cardTitle.textContent = '亲喂打卡'; } else { if (btnBottle) { btnBottle.className = 'flex-1 py-1.5 rounded-lg transition bg-white text-amber-900 shadow-2xs flex items-center justify-center space-x-1 whitespace-nowrap font-bold cursor-pointer'; } if (btnBf) { btnBf.className = 'flex-1 py-1.5 rounded-lg transition text-stone-600 bg-transparent flex items-center justify-center space-x-1 whitespace-nowrap font-bold cursor-pointer'; } if (secBottle) secBottle.classList.remove('hidden'); if (secBf) secBf.classList.add('hidden'); if (cardIcon) cardIcon.textContent = '🍼'; if (cardTitle) cardTitle.textContent = '瓶喂打卡'; } if (save) { saveRolePreference('defaultFeedingMode', mode); } } // Select Bottle preset amount (ml) function selectBottleAmount(amount, save = true) { state.lastBottleMl = amount; localStorage.setItem('last_bottle_ml', amount); const btnLast = document.getElementById('btnLastBottleAmount'); if (btnLast) btnLast.textContent = `${amount}ml`; if (save) { saveRolePreference('defaultBottleMl', amount); } } // Set Breastfeed preset target duration (minutes) function setBfTargetDuration(minutes, save = true) { state.bfTargetDuration = minutes; localStorage.setItem('bf_target_duration', minutes); const bfDurText = document.getElementById('quickBfDurationText'); if (bfDurText) bfDurText.textContent = `${minutes}m`; const bfSecText = document.getElementById('quickBfSecText'); if (bfSecText) bfSecText.textContent = `${minutes}m`; if (save) { saveRolePreference('defaultBfMinutes', minutes); } } // Quick log breastfeed default async function quickLogBreastfeedDefault() { const dur = state.bfTargetDuration || 20; const leftM = Math.round(dur / 2); const rightM = Math.round(dur / 2); const now = new Date(); const startTime = new Date(now.getTime() - dur * 60000); const pad = n => String(n).padStart(2, '0'); const fmtDate = d => `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`; await createRecord({ activityType: 'breastfeed', startTime: fmtDate(startTime), endTime: fmtDate(now), durationMinutes: dur, payload: { leftMinutes: leftM, rightMinutes: rightM, note: `秒记亲喂 (双侧均衡共${dur}m)` } }); } function quickLogBottleDefault() { const baby = state.babies.find(b => b.baby_id === state.currentBabyId); let defConfig = {}; if (baby && baby.default_config) { try { defConfig = typeof baby.default_config === 'string' ? JSON.parse(baby.default_config) : baby.default_config; } catch (e) { defConfig = {}; } } const milkType = defConfig.defaultMilkType || 'formula'; createRecord({ activityType: 'bottle', durationMinutes: 15, payload: { amountMl: state.lastBottleMl || 120, milkType, note: milkType === 'formula' ? '秒记冲调配方奶' : '秒记母乳/冷藏储奶' } }); } function openBottleAdjustModal() { pendingBottleMl = state.lastBottleMl; document.getElementById('inputBottleMl').textContent = pendingBottleMl; openModal('bottleModal'); } function adjustBottleMl(delta) { pendingBottleMl = Math.max(10, Math.min(300, pendingBottleMl + delta)); document.getElementById('inputBottleMl').textContent = pendingBottleMl; } function setBottleMl(val) { pendingBottleMl = val; document.getElementById('inputBottleMl').textContent = pendingBottleMl; } async function submitBottleRecord() { closeModal('bottleModal'); state.lastBottleMl = pendingBottleMl; localStorage.setItem('last_bottle_ml', pendingBottleMl); const btnLast = document.getElementById('btnLastBottleAmount'); if (btnLast) btnLast.textContent = `${pendingBottleMl}ml`; const milkType = document.querySelector('input[name="milkType"]:checked')?.value || 'formula'; await createRecord({ activityType: 'bottle', durationMinutes: 15, payload: { amountMl: pendingBottleMl, milkType, note: milkType === 'formula' ? '冲调配方奶' : '冷藏母乳温热' } }); } // Manual fine-tune breastfeed start and end time async function handleQuickBreastfeed() { const durStr = prompt('请输入本次亲喂总时长 (分钟):', state.bfTargetDuration || 20); if (!durStr) return; const dur = parseInt(durStr) || 20; const leftM = Math.round(dur / 2); const rightM = Math.round(dur / 2); const now = new Date(); const startTime = new Date(now.getTime() - dur * 60000); const pad = n => String(n).padStart(2, '0'); const fmtDate = d => `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`; await createRecord({ activityType: 'breastfeed', startTime: fmtDate(startTime), endTime: fmtDate(now), durationMinutes: dur, payload: { leftMinutes: leftM, rightMinutes: rightM, note: `手动微调亲喂 (左${leftM}m/右${rightM}m)` } }); } // ---------------------------------------------------- // Family Memo Checklist Management // ---------------------------------------------------- function focusMemoInput() { const el = document.getElementById('memoInputContent'); if (el) el.focus(); } function formatDateTimeShort(dtStr) { if (!dtStr) return '--'; const d = new Date(typeof dtStr === 'string' ? dtStr.replace(/-/g, '/') : dtStr); if (isNaN(d.getTime())) return dtStr; const pad = n => String(n).padStart(2, '0'); return `${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}`; } async function loadMemos() { if (!state.currentFamilyId) return; try { const res = await fetch(`${API_BASE}/memos?familyId=${state.currentFamilyId}`); const json = await res.json(); if (json.success) { state.memos = json.data || []; renderMemos(); renderMemoHistoryList(); } } catch (err) { console.error('Failed to load memos:', err); } } function renderMemos() { const container = document.getElementById('memoListContainer'); const countBadge = document.getElementById('memoCountBadge'); if (!container) return; const memos = state.memos || []; const pendingCount = memos.filter(m => !m.is_completed).length; if (countBadge) { countBadge.textContent = `${pendingCount} 项待办`; } if (memos.length === 0) { container.innerHTML = `
    今日暂无家庭备忘,在上方快速添加照料提醒吧 📝
    `; return; } const periodBadges = { today: { text: '全天', class: 'bg-stone-100 text-stone-600 border-stone-200' }, morning: { text: '上午', class: 'bg-amber-50 text-amber-700 border-amber-200' }, afternoon: { text: '下午', class: 'bg-orange-50 text-orange-700 border-orange-200' }, evening: { text: '睡前', class: 'bg-indigo-50 text-indigo-700 border-indigo-200' } }; container.innerHTML = memos.map(memo => { const isCompleted = !!memo.is_completed; const badge = periodBadges[memo.due_period] || periodBadges.today; const checkedClass = isCompleted ? 'bg-emerald-500 border-emerald-500 text-white' : 'bg-white border-stone-300 text-transparent'; const textClass = isCompleted ? 'memo-done-text' : 'font-bold text-stone-800'; const cardBg = isCompleted ? 'bg-stone-50/70 border-stone-200/50' : 'bg-white border-stone-200 shadow-2xs'; return `
    ${badge.text} ${memo.content}
    ${memo.created_by || '家人'}
    `; }).join(''); } // ---------------------------------------------------- // Historical Memos Modal & Maintenance Engine // ---------------------------------------------------- function openMemoHistoryModal() { state.memoHistoryFilter = { status: 'all', period: 'all', search: '' }; const searchInput = document.getElementById('memoHistorySearchInput'); if (searchInput) searchInput.value = ''; const clearBtn = document.getElementById('btnClearMemoSearch'); if (clearBtn) clearBtn.classList.add('hidden'); // Reset filter buttons document.querySelectorAll('.memo-status-filter').forEach(btn => { if (btn.dataset.status === 'all') { btn.className = 'memo-status-filter active px-2.5 py-1 rounded-lg bg-indigo-600 text-white transition cursor-pointer text-xs'; } else { btn.className = 'memo-status-filter px-2.5 py-1 rounded-lg text-slate-600 hover:text-slate-900 transition cursor-pointer text-xs'; } }); document.querySelectorAll('.memo-period-filter').forEach(btn => { if (btn.dataset.period === 'all') { btn.className = 'memo-period-filter active px-2 py-0.5 rounded-lg bg-slate-200 text-slate-800 text-[11px] font-bold cursor-pointer'; } else { btn.className = 'memo-period-filter px-2 py-0.5 rounded-lg bg-white border border-slate-200 text-slate-600 text-[11px] hover:bg-slate-100 cursor-pointer'; } }); renderMemoHistoryList(); openModal('memoHistoryModal'); } function setMemoStatusFilter(status) { state.memoHistoryFilter.status = status; document.querySelectorAll('.memo-status-filter').forEach(btn => { if (btn.dataset.status === status) { btn.className = 'memo-status-filter active px-2.5 py-1 rounded-lg bg-indigo-600 text-white transition cursor-pointer text-xs'; } else { btn.className = 'memo-status-filter px-2.5 py-1 rounded-lg text-slate-600 hover:text-slate-900 transition cursor-pointer text-xs'; } }); renderMemoHistoryList(); } function setMemoPeriodFilter(period) { state.memoHistoryFilter.period = period; document.querySelectorAll('.memo-period-filter').forEach(btn => { if (btn.dataset.period === period) { btn.className = 'memo-period-filter active px-2 py-0.5 rounded-lg bg-slate-200 text-slate-800 text-[11px] font-bold cursor-pointer'; } else { btn.className = 'memo-period-filter px-2 py-0.5 rounded-lg bg-white border border-slate-200 text-slate-600 text-[11px] hover:bg-slate-100 cursor-pointer'; } }); renderMemoHistoryList(); } function onMemoHistoryFilterChange() { const input = document.getElementById('memoHistorySearchInput'); const clearBtn = document.getElementById('btnClearMemoSearch'); const val = input ? input.value.trim().toLowerCase() : ''; state.memoHistoryFilter.search = val; if (clearBtn) { if (val) clearBtn.classList.remove('hidden'); else clearBtn.classList.add('hidden'); } renderMemoHistoryList(); } function clearMemoHistorySearch() { const input = document.getElementById('memoHistorySearchInput'); if (input) input.value = ''; onMemoHistoryFilterChange(); } function renderMemoHistoryList() { const container = document.getElementById('memoHistoryList'); if (!container) return; const memos = state.memos || []; const totalCount = memos.length; const pendingCount = memos.filter(m => !m.is_completed).length; const completedCount = memos.filter(m => !!m.is_completed).length; const totalBadge = document.getElementById('memoHistoryTotalCountBadge'); if (totalBadge) totalBadge.textContent = `${totalCount} 条记录`; const countAll = document.getElementById('memoCountAll'); if (countAll) countAll.textContent = totalCount; const countPending = document.getElementById('memoCountPending'); if (countPending) countPending.textContent = pendingCount; const countCompleted = document.getElementById('memoCountCompleted'); if (countCompleted) countCompleted.textContent = completedCount; // Filter according to filter state const { status, period, search } = state.memoHistoryFilter; const filtered = memos.filter(memo => { if (status === 'pending' && memo.is_completed) return false; if (status === 'completed' && !memo.is_completed) return false; if (period !== 'all' && memo.due_period !== period) return false; if (search) { const c = (memo.content || '').toLowerCase(); const by = (memo.created_by || '').toLowerCase(); if (!c.includes(search) && !by.includes(search)) return false; } return true; }); if (filtered.length === 0) { container.innerHTML = `
    📭
    未找到符合条件的备忘待办记录

    可以尝试更换筛选条件或在下方直接添加新备忘

    `; return; } const periodBadges = { today: { text: '📅 全天', class: 'bg-stone-100 text-stone-600 border-stone-200' }, morning: { text: '☀️ 上午', class: 'bg-amber-50 text-amber-700 border-amber-200' }, afternoon: { text: '🌤️ 下午', class: 'bg-orange-50 text-orange-700 border-orange-200' }, evening: { text: '🌙 睡前', class: 'bg-indigo-50 text-indigo-700 border-indigo-200' } }; container.innerHTML = filtered.map(memo => { const isCompleted = !!memo.is_completed; const badge = periodBadges[memo.due_period] || periodBadges.today; const checkedClass = isCompleted ? 'bg-emerald-500 border-emerald-500 text-white' : 'bg-white border-slate-300 text-transparent'; const textClass = isCompleted ? 'memo-done-text text-slate-400' : 'font-bold text-slate-800'; const cardBg = isCompleted ? 'bg-slate-50/70 border-slate-200/60' : 'bg-white border-slate-200 shadow-2xs hover:border-indigo-300'; const createdTimeStr = formatDateTimeShort(memo.created_at); const completedTimeStr = memo.completed_at ? ` · ✅ 完成于 ${formatDateTimeShort(memo.completed_at)}` : ''; return `
    ${badge.text} ${memo.content}
    👤 ${memo.created_by || '家人'} · 📅 创建于 ${createdTimeStr} ${completedTimeStr ? `${completedTimeStr}` : ''}
    `; }).join(''); } function openEditMemoModal(memoId) { const memo = state.memos.find(m => m.memo_id === memoId); if (!memo) return; const idInput = document.getElementById('editMemoId'); const contentInput = document.getElementById('editMemoContentInput'); const periodSelect = document.getElementById('editMemoPeriodSelect'); const statusPending = document.getElementById('editMemoStatusPending'); const statusDone = document.getElementById('editMemoStatusDone'); if (idInput) idInput.value = memo.memo_id; if (contentInput) contentInput.value = memo.content || ''; if (periodSelect) periodSelect.value = memo.due_period || 'today'; if (memo.is_completed) { if (statusDone) statusDone.checked = true; } else { if (statusPending) statusPending.checked = true; } openModal('editMemoModal'); } async function submitEditMemo() { const memoId = document.getElementById('editMemoId')?.value; const content = document.getElementById('editMemoContentInput')?.value?.trim(); const duePeriod = document.getElementById('editMemoPeriodSelect')?.value || 'today'; const isCompleted = document.querySelector('input[name="editMemoStatus"]:checked')?.value === '1'; if (!memoId || !content) { showToast('待办内容不能为空', 'warning'); return; } closeModal('editMemoModal'); try { const res = await fetch(`${API_BASE}/memos/${memoId}`, { method: 'PUT', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ content, duePeriod, isCompleted }) }); const json = await res.json(); if (json.success) { showToast('备忘修改已保存!'); await loadMemos(); } else { showToast(json.error || '保存失败', 'error'); } } catch (err) { console.error('Failed to update memo:', err); showToast('网络错误,修改失败', 'error'); } } async function handleCreateMemoFromHistory(event) { if (event) event.preventDefault(); const input = document.getElementById('historyModalInputContent'); const periodSelect = document.getElementById('historyModalDuePeriod'); const content = input ? input.value.trim() : ''; const duePeriod = periodSelect ? periodSelect.value : 'today'; if (!content) { showToast('请输入备忘待办内容', 'warning'); return; } try { const res = await fetch(`${API_BASE}/memos`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ familyId: state.currentFamilyId, babyId: state.currentBabyId, content, duePeriod, operatorName: state.currentOperator }) }); const json = await res.json(); if (json.success) { input.value = ''; showToast('新备忘待办已添加!'); await loadMemos(); } else { showToast(json.error || '添加失败', 'error'); } } catch (err) { showToast('网络错误,添加失败', 'error'); } } async function clearCompletedMemos() { const completedMemos = (state.memos || []).filter(m => !!m.is_completed); if (completedMemos.length === 0) { showToast('当前没有已完成的备忘事项', 'warning'); return; } if (!confirm(`确定要清理 ${completedMemos.length} 条已完成的历史备忘吗?清理后无法恢复。`)) { return; } try { const res = await fetch(`${API_BASE}/memos/clear-completed`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ familyId: state.currentFamilyId }) }); const json = await res.json(); if (json.success) { showToast(json.message || '已成功清理已完成历史备忘!'); state.memos = state.memos.filter(m => !m.is_completed); renderMemos(); renderMemoHistoryList(); } else { showToast(json.error || '清理失败', 'error'); } } catch (err) { console.error('Failed to clear completed memos:', err); showToast('网络错误,清理失败', 'error'); } } async function handleCreateMemo(event) { if (event) event.preventDefault(); const input = document.getElementById('memoInputContent'); const periodSelect = document.getElementById('memoDuePeriod'); const content = input ? input.value.trim() : ''; const duePeriod = periodSelect ? periodSelect.value : 'today'; if (!content) { showToast('请输入备忘待办内容', 'warning'); return; } try { const res = await fetch(`${API_BASE}/memos`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ familyId: state.currentFamilyId, babyId: state.currentBabyId, content, duePeriod, operatorName: state.currentOperator }) }); const json = await res.json(); if (json.success) { input.value = ''; showToast('备忘待办已添加!'); await loadMemos(); } else { showToast(json.error || '添加失败', 'error'); } } catch (err) { showToast('网络错误,添加失败', 'error'); } } async function toggleMemoComplete(memoId, currentStatus) { const m = state.memos.find(item => item.memo_id === memoId); if (m) { m.is_completed = currentStatus ? 0 : 1; m.completed_at = !currentStatus ? new Date().toISOString() : null; renderMemos(); renderMemoHistoryList(); } try { const res = await fetch(`${API_BASE}/memos/${memoId}`, { method: 'PUT', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ isCompleted: !currentStatus, operatorName: state.currentOperator }) }); const json = await res.json(); if (json.success) { if (!currentStatus) playChimeSound(); await loadMemos(); } else { showToast(json.error || '更新失败', 'error'); await loadMemos(); } } catch (err) { await loadMemos(); } } async function deleteMemo(memoId) { try { const res = await fetch(`${API_BASE}/memos/${memoId}`, { method: 'DELETE' }); const json = await res.json(); if (json.success) { showToast('备忘待办已删除'); state.memos = state.memos.filter(item => item.memo_id !== memoId); renderMemos(); renderMemoHistoryList(); } else { showToast(json.error || '删除失败', 'error'); } } catch (err) { showToast('网络错误', 'error'); } } // ---------------------------------------------------- // Focus Countdown Timer Engine // ---------------------------------------------------- function playChimeSound() { try { const AudioCtx = window.AudioContext || window.webkitAudioContext; if (!AudioCtx) return; const ctx = new AudioCtx(); const osc = ctx.createOscillator(); const gain = ctx.createGain(); osc.type = 'sine'; osc.frequency.setValueAtTime(523.25, ctx.currentTime); // C5 osc.frequency.exponentialRampToValueAtTime(659.25, ctx.currentTime + 0.25); // E5 gain.gain.setValueAtTime(0.25, ctx.currentTime); gain.gain.exponentialRampToValueAtTime(0.001, ctx.currentTime + 1.2); osc.connect(gain); gain.connect(ctx.destination); osc.start(ctx.currentTime); osc.stop(ctx.currentTime + 1.2); if (navigator.vibrate) navigator.vibrate([150, 80, 150]); } catch (e) { console.warn('AudioContext not allowed or not supported:', e); } } function handleStartBfCountdown() { startFocusTimer('breastfeed', state.bfTargetDuration); } function startFocusTimer(activityType = 'breastfeed', targetMinutes = 20) { if (state.activeTimer && state.activeTimer.type === activityType) { openFocusModal(); return; } if (state.activeTimer && state.activeTimer.timerInterval) { clearInterval(state.activeTimer.timerInterval); } const now = Date.now(); state.activeTimer = { type: activityType, startTime: now, targetMinutes: targetMinutes, currentSide: 'left', leftSeconds: 0, rightSeconds: 0, isPaused: false, pauseStartTime: null, totalPausedMs: 0, lastTickTime: now, timerInterval: null }; updateFocusModalAppearance(activityType); state.activeTimer.timerInterval = setInterval(tickFocusTimer, 500); const btnBfExpand = document.getElementById('btnBfFocusExpand'); if (btnBfExpand && activityType === 'breastfeed') btnBfExpand.classList.remove('hidden'); renderFocusTimer(); openFocusModal(); showToast(`⏱️ ${activityType === 'breastfeed' ? '亲喂' : '睡眠'}倒计时专注已开启!`); } function updateFocusModalAppearance(type) { const iconEl = document.getElementById('focusActivityIcon'); const titleEl = document.getElementById('focusActivityTitle'); const babyBadge = document.getElementById('focusBabyBadge'); const opTip = document.getElementById('focusOperatorTip'); const sideStats = document.getElementById('focusBfSideStats'); const ring = document.getElementById('focusRingCircle'); const currentBaby = state.babies.find(b => b.baby_id === state.currentBabyId); if (babyBadge) babyBadge.textContent = currentBaby ? currentBaby.name : '宝宝'; if (opTip) opTip.textContent = `当前记录人: ${state.currentOperator} · 保持静心专注`; if (type === 'breastfeed') { if (iconEl) iconEl.textContent = '🤱'; if (titleEl) titleEl.textContent = '亲喂专注倒计时'; if (sideStats) sideStats.classList.remove('hidden'); if (ring) { ring.setAttribute('stroke', '#F59E0B'); ring.classList.remove('focus-sleep-glow'); ring.classList.add('focus-glow-ring'); } } else if (type === 'sleep') { if (iconEl) iconEl.textContent = '😴'; if (titleEl) titleEl.textContent = '睡眠哄睡专注大屏'; if (sideStats) sideStats.classList.add('hidden'); if (ring) { ring.setAttribute('stroke', '#8B5CF6'); ring.classList.remove('focus-glow-ring'); ring.classList.add('focus-sleep-glow'); } } else { if (iconEl) iconEl.textContent = '⏱️'; if (titleEl) titleEl.textContent = '日常专注倒计时'; if (sideStats) sideStats.classList.add('hidden'); } } function tickFocusTimer() { if (!state.activeTimer) return; const t = state.activeTimer; if (t.isPaused) return; const now = Date.now(); const deltaSec = Math.max(0, (now - t.lastTickTime) / 1000); t.lastTickTime = now; if (t.type === 'breastfeed') { if (t.currentSide === 'left') { t.leftSeconds += deltaSec; } else { t.rightSeconds += deltaSec; } } renderFocusTimer(); } function renderFocusTimer() { if (!state.activeTimer) return; const t = state.activeTimer; const totalTargetSec = t.targetMinutes * 60; const totalElapsedSec = Math.floor((t.type === 'breastfeed') ? (t.leftSeconds + t.rightSeconds) : Math.max(0, (Date.now() - t.startTime - t.totalPausedMs) / 1000)); const remainingSec = Math.max(0, totalTargetSec - totalElapsedSec); const fmt = (s) => { const m = Math.floor(s / 60); const sec = Math.floor(s % 60); return `${String(m).padStart(2, '0')}:${String(sec).padStart(2, '0')}`; }; const digitsEl = document.getElementById('focusDigitsDisplay'); const subInfoEl = document.getElementById('focusSubInfo'); const phaseEl = document.getElementById('focusCurrentPhaseText'); if (remainingSec > 0) { if (digitsEl) digitsEl.textContent = fmt(remainingSec); } else { const overtime = totalElapsedSec - totalTargetSec; if (digitsEl) digitsEl.textContent = `+${fmt(overtime)}`; if (totalElapsedSec === totalTargetSec) { playChimeSound(); } } if (subInfoEl) { subInfoEl.textContent = `目标: ${t.targetMinutes}分钟 · 已进行: ${fmt(totalElapsedSec)}`; } if (phaseEl) { if (t.isPaused) { phaseEl.textContent = '⏸ 计时已暂停'; phaseEl.className = 'text-xs sm:text-sm font-bold tracking-widest text-stone-400 uppercase mb-1'; } else if (t.type === 'breastfeed') { phaseEl.textContent = t.currentSide === 'left' ? '左侧哺乳进行中' : '右侧哺乳进行中'; phaseEl.className = 'text-xs sm:text-sm font-bold tracking-widest text-amber-300 uppercase mb-1'; } else { phaseEl.textContent = '倒计时进行中'; phaseEl.className = 'text-xs sm:text-sm font-bold tracking-widest text-purple-300 uppercase mb-1'; } } const ring = document.getElementById('focusRingCircle'); if (ring) { const progressRatio = Math.min(1, Math.max(0, remainingSec / totalTargetSec)); const dashoffset = 754 * (1 - progressRatio); ring.style.strokeDashoffset = dashoffset; } if (t.type === 'breastfeed') { const leftTimeEl = document.getElementById('focusLeftTime'); const rightTimeEl = document.getElementById('focusRightTime'); const btnLeft = document.getElementById('btnFocusLeftBreast'); const btnRight = document.getElementById('btnFocusRightBreast'); if (leftTimeEl) leftTimeEl.textContent = fmt(t.leftSeconds); if (rightTimeEl) rightTimeEl.textContent = fmt(t.rightSeconds); if (btnLeft && btnRight) { if (t.currentSide === 'left') { btnLeft.className = 'px-4 py-2 rounded-2xl bg-amber-500/25 border-2 border-amber-400 text-amber-200 font-bold text-xs flex items-center space-x-2 transition shadow-sm'; btnRight.className = 'px-4 py-2 rounded-2xl bg-white/5 border border-white/20 text-stone-400 font-bold text-xs flex items-center space-x-2 transition'; } else { btnRight.className = 'px-4 py-2 rounded-2xl bg-amber-500/25 border-2 border-amber-400 text-amber-200 font-bold text-xs flex items-center space-x-2 transition shadow-sm'; btnLeft.className = 'px-4 py-2 rounded-2xl bg-white/5 border border-white/20 text-stone-400 font-bold text-xs flex items-center space-x-2 transition'; } } } const floatingDigits = document.getElementById('floatingTimerDigits'); const floatingTitle = document.getElementById('floatingTimerTitle'); if (floatingDigits) floatingDigits.textContent = remainingSec > 0 ? fmt(remainingSec) : `+${fmt(totalElapsedSec - totalTargetSec)}`; if (floatingTitle) { const sideText = t.type === 'breastfeed' ? `(${t.currentSide === 'left' ? '左侧' : '右侧'})` : ''; floatingTitle.textContent = `${t.type === 'breastfeed' ? '亲喂' : '睡眠'}中 ${sideText}`; } } function switchBreastSide(side) { if (!state.activeTimer) return; state.activeTimer.currentSide = side; state.activeTimer.lastTickTime = Date.now(); renderFocusTimer(); showToast(`已切换至【${side === 'left' ? '左侧' : '右侧'}】继续计时`); } function toggleBreastSide() { if (!state.activeTimer) return; const nextSide = state.activeTimer.currentSide === 'left' ? 'right' : 'left'; switchBreastSide(nextSide); } function addFocusMinutes(m = 5) { if (!state.activeTimer) return; state.activeTimer.targetMinutes += m; renderFocusTimer(); showToast(`已延长 ${m} 分钟专注时长`); } function togglePauseFocusTimer() { if (!state.activeTimer) return; const t = state.activeTimer; t.isPaused = !t.isPaused; const pauseIcon = document.getElementById('focusPauseIcon'); const pauseText = document.getElementById('focusPauseText'); if (t.isPaused) { t.pauseStartTime = Date.now(); if (pauseIcon) pauseIcon.textContent = '▶'; if (pauseText) pauseText.textContent = '继续'; showToast('计时已暂停'); } else { if (t.pauseStartTime) { t.totalPausedMs += (Date.now() - t.pauseStartTime); t.pauseStartTime = null; } t.lastTickTime = Date.now(); if (pauseIcon) pauseIcon.textContent = '⏸'; if (pauseText) pauseText.textContent = '暂停'; showToast('计时已继续'); } renderFocusTimer(); } async function completeFocusTimerAndRecord() { if (!state.activeTimer) return; const t = state.activeTimer; if (t.timerInterval) clearInterval(t.timerInterval); const totalElapsedSec = Math.floor((t.type === 'breastfeed') ? (t.leftSeconds + t.rightSeconds) : Math.max(0, (Date.now() - t.startTime - t.totalPausedMs) / 1000)); const durationMinutes = Math.max(1, Math.round(totalElapsedSec / 60)); const endTime = new Date(); const startTime = new Date(endTime.getTime() - durationMinutes * 60000); const pad = n => String(n).padStart(2, '0'); const fmtDate = d => `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`; let recordData = { activityType: t.type, startTime: fmtDate(startTime), endTime: fmtDate(endTime), durationMinutes: durationMinutes, operatorName: state.currentOperator }; if (t.type === 'breastfeed') { const leftM = Math.max(0, Math.round(t.leftSeconds / 60)); const rightM = Math.max(0, Math.round(t.rightSeconds / 60)); recordData.payload = { leftMinutes: leftM, rightMinutes: rightM, note: `倒计时专注完成 (左${leftM}m/右${rightM}m)` }; } else if (t.type === 'sleep') { recordData.payload = { note: `倒计时睡眠专注打卡` }; } playChimeSound(); closeFocusModal(); const floatingWidget = document.getElementById('floatingTimerWidget'); if (floatingWidget) floatingWidget.classList.add('hidden'); const btnBfExpand = document.getElementById('btnBfFocusExpand'); if (btnBfExpand) btnBfExpand.classList.add('hidden'); state.activeTimer = null; await createRecord(recordData); } function cancelFocusTimer() { if (!confirm('确定要放弃并退出本次计时吗?')) return; if (state.activeTimer && state.activeTimer.timerInterval) { clearInterval(state.activeTimer.timerInterval); } state.activeTimer = null; closeFocusModal(); const floatingWidget = document.getElementById('floatingTimerWidget'); if (floatingWidget) floatingWidget.classList.add('hidden'); const btnBfExpand = document.getElementById('btnBfFocusExpand'); if (btnBfExpand) btnBfExpand.classList.add('hidden'); showToast('本次计时已取消'); } function openFocusModal(activityType) { if (activityType && (!state.activeTimer || state.activeTimer.type !== activityType)) { startFocusTimer(activityType); return; } const modal = document.getElementById('focusModal'); const floatingWidget = document.getElementById('floatingTimerWidget'); if (modal) modal.classList.remove('hidden'); if (floatingWidget) floatingWidget.classList.add('hidden'); if (state.activeTimer) { updateFocusModalAppearance(state.activeTimer.type); renderFocusTimer(); } } function minimizeFocusModal() { const modal = document.getElementById('focusModal'); const floatingWidget = document.getElementById('floatingTimerWidget'); if (modal) modal.classList.add('hidden'); if (state.activeTimer && floatingWidget) { floatingWidget.classList.remove('hidden'); } } function closeFocusModal() { const modal = document.getElementById('focusModal'); if (modal) modal.classList.add('hidden'); if (state.activeTimer) { const floatingWidget = document.getElementById('floatingTimerWidget'); if (floatingWidget) floatingWidget.classList.remove('hidden'); } } async function handleQuickDiaper(subType = 'pee') { await createRecord({ activityType: 'diaper', durationMinutes: 5, payload: { diaperType: subType, poopColor: subType === 'poop' ? 'yellow' : undefined, poopTexture: subType === 'poop' ? 'pasty' : undefined, note: subType === 'poop' ? '正常黄色便' : '常规换尿包' } }); } async function handleQuickSleepToggle() { const isSleeping = state.summary && state.summary.liveStatus.sleep.isSleeping; if (isSleeping) { const latestSleep = state.summary.timeline.find(r => r.activity_type === 'sleep' && !r.end_time); if (latestSleep) { const now = new Date(); const startTime = new Date(latestSleep.start_time); const dur = Math.max(1, Math.round((now.getTime() - startTime.getTime()) / 60000)); await fetch(`${API_BASE}/records/${latestSleep.record_id}`, { method: 'PUT', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ endTime: formatDateTime(now), durationMinutes: dur }) }); showToast(`宝宝醒来!本次睡眠时长: ${Math.floor(dur / 60)}小时${dur % 60}分`); loadSummaryData(); } } else { await createRecord({ activityType: 'sleep', durationMinutes: 0, payload: { note: '睡下了' } }); } } async function createRecord(recordData) { try { const res = await fetch(`${API_BASE}/records`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ babyId: state.currentBabyId, operatorName: state.currentOperator, ...recordData }) }); const json = await res.json(); if (json.success) { if (json.duplicateWarning) { showToast(`⚠️ 提示:${json.duplicateWarning}`, 'warning'); } else { showToast('打卡成功,已实时入库!'); } loadSummaryData(); if (!document.getElementById('timelineModal').classList.contains('hidden')) { renderModalTimeline(); } } else { showToast(json.error || '打卡失败', 'error'); } } catch (err) { console.error('Failed to create record:', err); showToast('网络异常,请重试', 'error'); } } async function deleteRecord(recordId) { if (!confirm('确定要删除此条打卡记录吗?')) return; try { const res = await fetch(`${API_BASE}/records/${recordId}`, { method: 'DELETE' }); const json = await res.json(); if (json.success) { showToast('已删除该记录'); await loadSummaryData(); if (!document.getElementById('timelineModal').classList.contains('hidden')) { renderModalTimeline(); } } } catch (err) { showToast('删除失败', 'error'); } } // ---------------------------------------------------- // Retro Record Modal (+ 补录) // ---------------------------------------------------- function openRetroRecordModal() { const now = new Date(); const pad = n => String(n).padStart(2, '0'); const localDatetime = `${now.getFullYear()}-${pad(now.getMonth() + 1)}-${pad(now.getDate())}T${pad(now.getHours())}:${pad(now.getMinutes())}`; document.getElementById('retroDateTime').value = localDatetime; openModal('retroModal'); } async function submitRetroRecord() { const type = document.getElementById('retroType').value; const dtVal = document.getElementById('retroDateTime').value; const val = parseInt(document.getElementById('retroValue').value) || 0; const note = document.getElementById('retroNote').value; if (!dtVal) { showToast('请选择发生时间', 'warning'); return; } const startTime = dtVal.replace('T', ' ') + ':00'; const payload = { note }; let duration = 15; if (type === 'bottle') { payload.amountMl = val || 120; payload.milkType = 'formula'; } else if (type === 'sleep') { duration = val || 60; } else if (type === 'breastfeed') { duration = val || 20; payload.leftMinutes = Math.round(duration / 2); payload.rightMinutes = Math.round(duration / 2); } else if (type === 'custom') { payload.name = note || '补录项目'; payload.value = val || 1; } closeModal('retroModal'); await createRecord({ activityType: type, startTime, durationMinutes: duration, payload }); } // ---------------------------------------------------- // Excel Export // ---------------------------------------------------- function downloadExcel() { if (!state.currentBabyId) return; showToast('正在导出标准 Excel 报表...'); window.open(`${API_BASE}/export/excel?babyId=${state.currentBabyId}`, '_blank'); } // ---------------------------------------------------- // Modal Helpers // ---------------------------------------------------- function openModal(id) { const el = document.getElementById(id); if (el) el.classList.remove('hidden'); } function closeModal(id) { const el = document.getElementById(id); if (el) el.classList.add('hidden'); if (id === 'careGuideModal') { const video = document.getElementById('modalGuideVideo'); if (video) video.pause(); } } function formatDateTime(d = new Date()) { const pad = n => String(n).padStart(2, '0'); return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`; }