2053 lines
82 KiB
JavaScript
2053 lines
82 KiB
JavaScript
// 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'),
|
|
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 = `
|
|
<span>${message}</span>
|
|
<span class="ml-2 text-white/70 cursor-pointer">✕</span>
|
|
`;
|
|
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 = `
|
|
<div class="flex items-center space-x-2">
|
|
<span class="text-xl">${icon}</span>
|
|
<span class="text-xs font-bold">${role}</span>
|
|
</div>
|
|
${isCurrent ? '<span class="text-[10px] font-bold text-indigo-600 bg-white px-2 py-0.5 rounded-full shadow-2xs">当前</span>' : '<span class="text-xs text-slate-400">切换</span>'}
|
|
`;
|
|
btn.onclick = () => {
|
|
state.currentOperator = role;
|
|
localStorage.setItem('caregiver_role', role);
|
|
updateOperatorDisplay();
|
|
closeModal('roleModal');
|
|
showToast(`操作人已切换为:【${role}】`);
|
|
};
|
|
container.appendChild(btn);
|
|
});
|
|
}
|
|
openModal('roleModal');
|
|
}
|
|
|
|
// ----------------------------------------------------
|
|
// Initialization
|
|
// ----------------------------------------------------
|
|
document.addEventListener('DOMContentLoaded', async () => {
|
|
// Set current operator display
|
|
updateOperatorDisplay();
|
|
|
|
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();
|
|
}
|
|
}
|
|
|
|
// ----------------------------------------------------
|
|
// 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();
|
|
await loadBabies();
|
|
}
|
|
} 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 ? '<span class="text-[9px] bg-amber-100 text-amber-800 px-1.5 py-0.2 rounded-md font-bold ml-1">创建者</span>' : '';
|
|
return `
|
|
<span class="inline-flex items-center px-2.5 py-1 rounded-full text-xs font-semibold bg-white border border-slate-200/80 text-slate-700 shadow-2xs">
|
|
<span>${icon}</span>
|
|
<span class="ml-1">${m.role_name}</span>
|
|
${ownerTag}
|
|
</span>
|
|
`;
|
|
}).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 = `
|
|
<div class="flex items-center space-x-2.5">
|
|
<span class="text-xl p-1.5 bg-white rounded-xl shadow-2xs">🏡</span>
|
|
<div>
|
|
<div class="flex items-center space-x-1.5">
|
|
<span class="font-bold text-xs text-slate-800">${f.name}</span>
|
|
${isCurrent ? '<span class="text-[9px] font-bold bg-indigo-600 text-white px-1.5 py-0.2 rounded-full">当前活跃</span>' : ''}
|
|
</div>
|
|
<div class="text-[10px] text-slate-500 mt-0.5">
|
|
邀请码: <span class="font-mono font-bold text-indigo-700">${f.invite_code}</span> · ${babyCount} 个宝宝 · ${memberCount} 位看护人
|
|
</div>
|
|
</div>
|
|
</div>
|
|
<div>
|
|
<span class="text-xs font-bold ${isCurrent ? 'text-indigo-600' : 'text-slate-400'}">${isCurrent ? '✓ 活跃' : '进入 →'}</span>
|
|
</div>
|
|
`;
|
|
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();
|
|
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();
|
|
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);
|
|
}
|
|
} 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}`;
|
|
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');
|
|
|
|
if (s && s.hasData && s.isSleeping) {
|
|
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.5 py-1 rounded-xl';
|
|
}
|
|
if (sleepStateDetailEl) sleepStateDetailEl.textContent = '宝宝正在睡眠中 · 骨骼与大脑高速发育';
|
|
if (sleepToggleIcon) sleepToggleIcon.textContent = '☀️';
|
|
if (sleepToggleActionText) sleepToggleActionText.textContent = `☀️ 宝宝醒了?(点击结算已睡 ${s.currentDurationText})`;
|
|
if (btnSleepToggle) {
|
|
btnSleepToggle.className = 'w-full 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.5 rounded-2xl shadow-md transition flex items-center justify-center space-x-2';
|
|
}
|
|
} else {
|
|
if (sleepStateTitleEl) {
|
|
sleepStateTitleEl.textContent = s && s.hasData ? `清醒 ${s.awakeText}` : '清醒中';
|
|
sleepStateTitleEl.className = 'text-xs font-black text-purple-700 bg-purple-50 border border-purple-200/80 px-2.5 py-1 rounded-xl';
|
|
}
|
|
if (sleepStateDetailEl) sleepStateDetailEl.textContent = '宝宝清醒中 · 精神饱满可互动交流';
|
|
if (sleepToggleIcon) sleepToggleIcon.textContent = '😴';
|
|
if (sleepToggleActionText) sleepToggleActionText.textContent = '🌙 宝宝睡下了 (点击开始计时)';
|
|
if (btnSleepToggle) {
|
|
btnSleepToggle.className = 'w-full 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.5 rounded-2xl shadow-md transition flex items-center justify-center space-x-2';
|
|
}
|
|
}
|
|
|
|
// 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}`;
|
|
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 = `
|
|
<div class="col-span-2 text-slate-400 py-3 text-center text-[11px] bg-slate-50 rounded-xl cursor-pointer hover:text-indigo-600" onclick="switchTab('profile')">
|
|
暂无私人目标,点击前往「宝贝档案」添加专属项 ❯
|
|
</div>
|
|
`;
|
|
return;
|
|
}
|
|
|
|
state.customMetrics.forEach(metric => {
|
|
const defVal = metric.default_value || '1';
|
|
const card = document.createElement('button');
|
|
card.className = 'bg-slate-50 hover:bg-emerald-50 border border-slate-200 hover:border-emerald-300 rounded-xl p-2.5 flex items-center justify-between active:scale-95 transition text-left shadow-2xs';
|
|
card.onclick = () => quickLogCustomMetric(metric);
|
|
|
|
card.innerHTML = `
|
|
<div class="flex items-center space-x-2">
|
|
<span class="text-xl">${metric.icon || '⭐'}</span>
|
|
<div>
|
|
<div class="font-bold text-slate-800 text-xs">${metric.name}</div>
|
|
<div class="text-[10px] text-emerald-700 font-semibold mt-0.5">默认: ${defVal} ${metric.unit || '次'}</div>
|
|
</div>
|
|
</div>
|
|
<span class="text-[10px] font-bold text-emerald-700 bg-emerald-100 px-2 py-0.5 rounded-full">打卡</span>
|
|
`;
|
|
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 = '<div class="text-slate-400 py-4 text-center text-xs">暂无配置项,点击右上角新建私人目标</div>';
|
|
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 = `
|
|
<div class="flex items-center space-x-3">
|
|
<span class="text-2xl p-1.5 bg-white rounded-xl shadow-2xs border border-slate-100">${m.icon || '✨'}</span>
|
|
<div>
|
|
<div class="flex items-center space-x-2">
|
|
<span class="font-extrabold text-xs text-slate-900">${m.name}</span>
|
|
<span class="text-[10px] px-2 py-0.5 rounded-full font-bold bg-indigo-50 text-indigo-700 border border-indigo-200">默认 ${m.default_value || 1} ${m.unit || '次'}</span>
|
|
</div>
|
|
<div class="text-[10px] text-slate-500 mt-0.5">每日目标: ${m.target_daily || 1} ${m.unit || '次'}</div>
|
|
</div>
|
|
</div>
|
|
<button class="text-xs font-bold text-indigo-600 bg-white border border-indigo-200 hover:bg-indigo-50 px-2.5 py-1.5 rounded-xl active:scale-95 transition shadow-2xs" onclick="openConfigCustomMetricModal('${m.metric_id}')">
|
|
✏️ 配置默认值
|
|
</button>
|
|
`;
|
|
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 = `
|
|
<div class="text-center py-6 bg-slate-50 border border-dashed border-slate-200 rounded-2xl">
|
|
<div class="text-2xl mb-1">🐣</div>
|
|
<div class="text-xs font-bold text-slate-700">当天尚未记录任何作息</div>
|
|
<div class="text-[11px] text-slate-400 mt-0.5">前往「快速打卡」记录宝宝的第一笔活动吧~</div>
|
|
</div>
|
|
`;
|
|
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 ? `<span class="text-slate-400 ml-1">· ${r.payload.note}</span>` : '';
|
|
|
|
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 = `
|
|
<div class="flex items-center space-x-3">
|
|
<div class="flex flex-col items-center">
|
|
<span class="font-mono font-black text-xs text-slate-800">${r.start_time.substring(11, 16)}</span>
|
|
<span class="text-sm p-1.5 rounded-xl ${typeMeta.color} shadow-xs mt-0.5">${r.payload.icon || typeMeta.icon}</span>
|
|
</div>
|
|
<div>
|
|
<div class="flex items-center space-x-1.5">
|
|
<span class="font-bold text-xs text-slate-900">${typeMeta.name}</span>
|
|
<span class="text-[10px] text-slate-500 bg-white/80 px-1.5 py-0.2 rounded font-medium border border-slate-200/60">【${r.operator_name || '家人'}】</span>
|
|
</div>
|
|
<div class="text-[11px] text-slate-600 font-medium mt-0.5">${detail}${note}</div>
|
|
</div>
|
|
</div>
|
|
<button class="text-indigo-600 bg-white hover:bg-indigo-50 border border-indigo-200/80 text-[11px] font-bold px-2.5 py-1 rounded-xl shadow-2xs active:scale-95 transition" onclick="openEditRecordModal('${r.record_id}')">
|
|
✏️ 修改
|
|
</button>
|
|
`;
|
|
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 = '<div class="text-[11px] text-slate-400 py-1">此时段无记录</div>';
|
|
} else {
|
|
itemsHtml = `
|
|
<div class="flex flex-wrap gap-1.5 pt-1">
|
|
${slot.items.map(it => `
|
|
<div class="px-2.5 py-1 rounded-xl border text-[11px] font-bold flex items-center space-x-1 shadow-2xs cursor-pointer active:scale-95 transition ${it.badgeColor}" onclick="showRecordDetailToast('${it.time}', '${it.desc}', '${it.operator}')">
|
|
<span>${it.icon}</span>
|
|
<span class="font-mono">${it.time}</span>
|
|
<span>${it.desc}</span>
|
|
<span class="opacity-75 text-[9px]">(${it.operator})</span>
|
|
</div>
|
|
`).join('')}
|
|
</div>
|
|
`;
|
|
}
|
|
|
|
card.innerHTML = `
|
|
<div class="flex items-center justify-between">
|
|
<div class="flex items-center space-x-2">
|
|
<span class="font-extrabold text-xs text-slate-800">${meta.title}</span>
|
|
<span class="text-[10px] text-slate-500 font-mono">(${meta.time})</span>
|
|
</div>
|
|
<span class="text-[10px] font-bold text-slate-600 bg-white/80 px-2 py-0.5 rounded-full border border-slate-200">${slot.items.length} 笔记录</span>
|
|
</div>
|
|
${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 = '<div class="text-slate-400 py-3 text-center">今日暂无喂养记录</div>';
|
|
} 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 = `
|
|
<div class="flex items-center space-x-2">
|
|
<span class="text-base">${isBottle ? '🍼' : '🤱'}</span>
|
|
<div>
|
|
<div class="font-bold text-slate-800">${r.start_time.substring(11, 16)} · ${valText}</div>
|
|
<div class="text-[10px] text-slate-500">记录人: ${r.operator_name || '家人'} ${r.payload.note ? '· ' + r.payload.note : ''}</div>
|
|
</div>
|
|
</div>
|
|
<div class="flex items-center space-x-1">
|
|
<button class="text-indigo-600 bg-white border border-indigo-100 px-2 py-0.5 rounded text-[11px] font-bold" onclick="openEditRecordModal('${r.record_id}')">修改</button>
|
|
<button class="text-slate-400 hover:text-rose-500 text-xs px-2" onclick="deleteRecord('${r.record_id}')">✕</button>
|
|
</div>
|
|
`;
|
|
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 = '<div class="text-slate-400 py-3 text-center">今日暂无睡眠记录</div>';
|
|
} 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 = `
|
|
<div class="flex items-center space-x-2">
|
|
<span class="text-base">😴</span>
|
|
<div>
|
|
<div class="font-bold text-slate-800">${r.start_time.substring(11, 16)} ~ ${endText} (${r.duration_minutes || 0}分钟)</div>
|
|
<div class="text-[10px] text-slate-500">记录人: ${r.operator_name || '家人'}</div>
|
|
</div>
|
|
</div>
|
|
<div class="flex items-center space-x-1">
|
|
<button class="text-indigo-600 bg-white border border-indigo-100 px-2 py-0.5 rounded text-[11px] font-bold" onclick="openEditRecordModal('${r.record_id}')">修改</button>
|
|
<button class="text-slate-400 hover:text-rose-500 text-xs px-2" onclick="deleteRecord('${r.record_id}')">✕</button>
|
|
</div>
|
|
`;
|
|
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 = '<div class="text-slate-400 py-3 text-center">今日暂无换尿布记录</div>';
|
|
} 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 = `
|
|
<div class="flex items-center space-x-2">
|
|
<span class="text-base">${r.payload.diaperType === 'poop' ? '💩' : '💧'}</span>
|
|
<div>
|
|
<div class="font-bold text-slate-800">${r.start_time.substring(11, 16)} · ${dt}</div>
|
|
<div class="text-[10px] text-slate-500">记录人: ${r.operator_name || '家人'} ${r.payload.note ? '· ' + r.payload.note : ''}</div>
|
|
</div>
|
|
</div>
|
|
<div class="flex items-center space-x-1">
|
|
<button class="text-indigo-600 bg-white border border-indigo-100 px-2 py-0.5 rounded text-[11px] font-bold" onclick="openEditRecordModal('${r.record_id}')">修改</button>
|
|
<button class="text-slate-400 hover:text-rose-500 text-xs px-2" onclick="deleteRecord('${r.record_id}')">✕</button>
|
|
</div>
|
|
`;
|
|
diaperListContainer.appendChild(item);
|
|
});
|
|
}
|
|
}
|
|
|
|
// 4. Custom Goals Spec
|
|
const customListContainer = document.getElementById('specCustomList');
|
|
if (customListContainer) {
|
|
customListContainer.innerHTML = '';
|
|
if (state.customMetrics.length === 0) {
|
|
customListContainer.innerHTML = '<div class="text-slate-400 py-3 text-center">暂无自定义目标,可点击右上角创建</div>';
|
|
} 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 = `
|
|
<div class="flex items-center justify-between">
|
|
<div class="flex items-center space-x-2">
|
|
<span class="text-xl">${m.icon || '⭐'}</span>
|
|
<span class="font-extrabold text-slate-800">${m.name}</span>
|
|
</div>
|
|
<span class="text-xs font-bold text-emerald-800">${currentCount} / ${target} ${m.unit || '次'} (${percent}%)</span>
|
|
</div>
|
|
<div class="w-full bg-slate-200 h-2 rounded-full overflow-hidden">
|
|
<div class="h-full bg-emerald-500 rounded-full transition-all duration-500" style="width: ${percent}%;"></div>
|
|
</div>
|
|
`;
|
|
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 = `
|
|
<span class="text-[9px] font-bold text-amber-700 opacity-0 group-hover:opacity-100 transition mb-0.5">${t.totalMilkMl > 0 ? t.totalMilkMl : ''}</span>
|
|
<div class="w-5 bg-gradient-to-t from-amber-500 to-amber-400 rounded-t-md transition-all duration-500 shadow-2xs hover:brightness-110" style="height: ${Math.max(6, heightPercent)}%;"></div>
|
|
`;
|
|
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 = '<div class="text-slate-400 py-8 text-center text-xs">当前筛选条件下暂无打卡记录</div>';
|
|
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 ? `<span class="text-slate-400 ml-1">· ${r.payload.note}</span>` : '';
|
|
|
|
const row = document.createElement('div');
|
|
row.className = 'pt-2.5 pb-2 flex items-start justify-between';
|
|
row.innerHTML = `
|
|
<div class="flex items-start space-x-2.5">
|
|
<span class="text-base p-1.5 rounded-lg border ${typeMeta.color}">${r.payload.icon || typeMeta.icon}</span>
|
|
<div>
|
|
<div class="flex items-center space-x-1.5">
|
|
<span class="font-extrabold text-slate-900">${r.start_time.substring(11, 16)}</span>
|
|
<span class="text-slate-700 font-semibold">${typeMeta.name}</span>
|
|
<span class="text-[10px] px-1.5 py-0.2 bg-slate-100 text-slate-600 rounded font-medium">【${r.operator_name || '家人'}】</span>
|
|
</div>
|
|
<div class="text-[11px] text-slate-600 mt-0.5">${detail}${note}</div>
|
|
</div>
|
|
</div>
|
|
<div class="flex items-center space-x-1 shrink-0">
|
|
<button class="text-indigo-600 bg-indigo-50 hover:bg-indigo-100 text-[11px] font-bold px-2.5 py-1 rounded-lg active:scale-95 transition" onclick="openEditRecordModal('${r.record_id}')">✏️ 修改</button>
|
|
<button class="text-slate-300 hover:text-rose-500 text-xs px-2 py-1 active:scale-95 transition" onclick="deleteRecord('${r.record_id}')" title="删除记录">✕</button>
|
|
</div>
|
|
`;
|
|
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 = '<div class="text-slate-400 py-6 text-center text-xs">当前家庭暂无宝宝档案,点击上方「+ 新增宝宝」为本家庭创建首位宝宝</div>';
|
|
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 = `
|
|
<div class="flex items-center space-x-3 cursor-pointer" onclick="selectBaby('${baby.baby_id}')">
|
|
<div class="w-10 h-10 rounded-full flex items-center justify-center text-white font-black text-sm" style="background-color: ${baby.theme_color}">
|
|
${baby.name.substring(0, 1)}
|
|
</div>
|
|
<div>
|
|
<div class="flex items-center space-x-2">
|
|
<span class="font-bold text-sm text-slate-800">${baby.name}</span>
|
|
<span class="text-xs">${baby.gender === 'boy' ? '👦 小王子' : '👧 小公主'}</span>
|
|
${isSelected ? '<span class="text-[10px] bg-indigo-600 text-white px-2 py-0.5 rounded-full font-bold">当前记录中</span>' : ''}
|
|
</div>
|
|
<div class="text-xs text-slate-500 mt-0.5">出生: ${baby.birth_date} (${baby.ageText || baby.ageDays + '天'})</div>
|
|
</div>
|
|
</div>
|
|
<div class="flex items-center space-x-2">
|
|
<button class="text-slate-500 hover:text-indigo-600 text-xs font-semibold px-2 py-1 bg-slate-100 rounded-lg active:scale-95" onclick="openEditBabyModal('${baby.baby_id}')">✏️ 编辑</button>
|
|
${!isSelected ? `<button class="text-indigo-600 text-xs font-bold px-2 py-1 bg-indigo-50 rounded-lg active:scale-95" onclick="selectBaby('${baby.baby_id}')">切换 ▶</button>` : ''}
|
|
</div>
|
|
`;
|
|
container.appendChild(card);
|
|
});
|
|
}
|
|
|
|
function selectBaby(babyId) {
|
|
state.currentBabyId = babyId;
|
|
localStorage.setItem('selected_baby_id', babyId);
|
|
updateCurrentBabyDisplay();
|
|
renderBabiesList();
|
|
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 = `
|
|
<div class="relative h-32 bg-slate-900 cursor-pointer" onclick="openCareGuideModal('${guide.id}')">
|
|
<img src="${guide.posterUrl}" class="w-full h-full object-cover opacity-80" alt="${guide.title}">
|
|
<div class="absolute inset-0 flex items-center justify-center">
|
|
<div class="w-11 h-11 rounded-full bg-white/90 text-slate-900 flex items-center justify-center shadow-lg active:scale-90 transition">
|
|
<span class="text-base ml-0.5">▶</span>
|
|
</div>
|
|
</div>
|
|
<span class="absolute top-2 left-2 text-[10px] font-bold bg-black/60 text-white px-2 py-0.5 rounded-full">${guide.categoryName}</span>
|
|
<span class="absolute bottom-2 right-2 text-[10px] font-mono bg-black/70 text-white px-2 py-0.5 rounded-md">${guide.durationText}</span>
|
|
</div>
|
|
<div class="p-3.5 space-y-2">
|
|
<div class="flex items-center justify-between">
|
|
<h3 class="font-bold text-sm text-slate-800">${guide.title}</h3>
|
|
<button class="text-xs text-indigo-600 font-bold" onclick="openCareGuideModal('${guide.id}')">看视频 ▶</button>
|
|
</div>
|
|
<p class="text-xs text-slate-500">${guide.subtitle}</p>
|
|
<div class="text-[11px] bg-slate-50 p-2 rounded-lg text-slate-600 line-clamp-2">
|
|
${guide.keyPoints[0]}
|
|
</div>
|
|
</div>
|
|
`;
|
|
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 => `<li>${p}</li>`).join('');
|
|
if (cautionsEl) cautionsEl.innerHTML = guide.cautions.map(c => `<p class="mb-1 font-medium">${c}</p>`).join('');
|
|
|
|
openModal('careGuideModal');
|
|
}
|
|
|
|
// ----------------------------------------------------
|
|
// One-Tap Quick Log Handlers
|
|
// ----------------------------------------------------
|
|
let pendingBottleMl = 120;
|
|
|
|
function quickLogBottleDefault() {
|
|
createRecord({
|
|
activityType: 'bottle',
|
|
durationMinutes: 15,
|
|
payload: {
|
|
amountMl: state.lastBottleMl,
|
|
milkType: 'formula',
|
|
note: '快捷一键打卡'
|
|
}
|
|
});
|
|
}
|
|
|
|
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' ? '冲调配方奶' : '冷藏母乳温热'
|
|
}
|
|
});
|
|
}
|
|
|
|
async function handleQuickBreastfeed() {
|
|
await createRecord({
|
|
activityType: 'breastfeed',
|
|
durationMinutes: 20,
|
|
payload: {
|
|
leftMinutes: 10,
|
|
rightMinutes: 10,
|
|
note: '双侧亲喂'
|
|
}
|
|
});
|
|
}
|
|
|
|
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())}`;
|
|
}
|