const { formatDate } = require('./util') const cloud = require('./cloud') const RECORDS_KEY = 'training_records' const SETTINGS_KEY = 'user_settings' const STREAK_KEY = 'current_streak' const getRecords = () => wx.getStorageSync(RECORDS_KEY) || {} const saveRecord = (record) => { record.id = Date.now() const records = getRecords() const month = record.date.substring(0, 7) if (!records[month]) records[month] = [] records[month].push(record) records[month].sort((a, b) => b.date.localeCompare(a.date)) wx.setStorageSync(RECORDS_KEY, records) cloud.pushAll() } const deleteRecord = (recordId) => { const records = getRecords() Object.keys(records).forEach((month) => { records[month] = records[month].filter((r) => r.id !== recordId) if (records[month].length === 0) delete records[month] }) wx.setStorageSync(RECORDS_KEY, records) cloud.pushAll() } const getRecordsByMonth = (month) => { const records = getRecords() return records[month] || [] } const getTotalStats = () => { const records = getRecords() let totalDuration = 0 let totalSessions = 0 let maxDuration = 0 Object.keys(records).forEach((key) => { records[key].forEach((r) => { totalDuration += r.duration totalSessions++ if (r.duration > maxDuration) maxDuration = r.duration }) }) return { totalDuration, totalSessions, maxDuration } } const getSettings = () => wx.getStorageSync(SETTINGS_KEY) || { planId: 'beginner', dailyReminder: true, reminderTime: '08:00', voiceGuide: true, vibrate: true } const saveSettings = (settings) => { wx.setStorageSync(SETTINGS_KEY, settings) cloud.pushAll() } const getStreak = () => wx.getStorageSync(STREAK_KEY) || { count: 0, lastDate: '' } const updateStreak = (date) => { const streak = getStreak() const today = date || getToday() const yesterday = getDateOffset(today, -1) if (streak.lastDate === today) return streak if (streak.lastDate === yesterday) { streak.count += 1 } else { streak.count = 1 } streak.lastDate = today wx.setStorageSync(STREAK_KEY, streak) cloud.pushAll() return streak } const getToday = () => formatDate(new Date()) const getDateOffset = (dateStr, offset) => { const d = new Date(dateStr) d.setDate(d.getDate() + offset) return formatDate(d) } const getTodayRecord = () => { const today = getToday() const records = getRecords() let totalDuration = 0 let hasRecord = false Object.keys(records).forEach((month) => { records[month].forEach((r) => { if (r.date === today) { totalDuration += r.duration hasRecord = true } }) }) return hasRecord ? { date: today, duration: totalDuration } : null } module.exports = { getRecords, saveRecord, deleteRecord, getRecordsByMonth, getTotalStats, getSettings, saveSettings, getStreak, updateStreak, getToday, formatDate, getDateOffset, getTodayRecord }