436 lines
14 KiB
TypeScript
436 lines
14 KiB
TypeScript
import { defineStore } from 'pinia'
|
|
import {
|
|
createBaby,
|
|
createFeeding,
|
|
createManualRecord,
|
|
createMember,
|
|
createPee,
|
|
createPoop,
|
|
deleteMember,
|
|
endFeeding,
|
|
endSleep,
|
|
getDailySummary,
|
|
getFamilyContext,
|
|
setDefaultBaby as apiSetDefaultBaby,
|
|
startFeeding,
|
|
startSleep,
|
|
updateBaby,
|
|
updateCurrentBaby,
|
|
updateFamily,
|
|
updateMember,
|
|
updateRecord,
|
|
getServerTime
|
|
} from '../api/client'
|
|
import type {
|
|
ActionPreferences,
|
|
BabyProfile,
|
|
CreateBabyPayload,
|
|
CreateManualRecordPayload,
|
|
CreateMemberPayload,
|
|
DailySummary,
|
|
FamilyContext,
|
|
FamilyMember,
|
|
FeedingMethod,
|
|
UpdateCareRecordPayload,
|
|
UpdateFamilyPayload,
|
|
UpdateMemberPayload
|
|
} from '../types/domain'
|
|
|
|
const defaultPreferences: ActionPreferences = {
|
|
defaultFeedingMethod: 'breastfeed',
|
|
defaultBottleAmount: 30,
|
|
defaultBreastSide: 'left',
|
|
defaultSleepMode: 'timer',
|
|
quickFeedbackToast: true,
|
|
autoBurpReminder: true
|
|
}
|
|
|
|
function loadInitialPreferences(): ActionPreferences {
|
|
try {
|
|
const raw = localStorage.getItem('actionPreferences')
|
|
if (raw) {
|
|
return { ...defaultPreferences, ...JSON.parse(raw) }
|
|
}
|
|
} catch {
|
|
// fallback
|
|
}
|
|
return defaultPreferences
|
|
}
|
|
|
|
let bfTicker: ReturnType<typeof setInterval> | null = null
|
|
|
|
function startBfTicker(store: any) {
|
|
if (bfTicker) return
|
|
bfTicker = setInterval(() => {
|
|
if (!store.bfTimerActive) {
|
|
stopBfTicker()
|
|
return
|
|
}
|
|
const now = Date.now()
|
|
const delta = Math.max(0, Math.floor((now - store.bfLastTickTime) / 1000))
|
|
if (delta > 0) {
|
|
if (store.bfActiveSide === 'left') {
|
|
store.bfLeftSeconds += delta
|
|
} else {
|
|
store.bfRightSeconds += delta
|
|
}
|
|
store.bfLastTickTime = now
|
|
store.persistBfTimer()
|
|
}
|
|
}, 1000)
|
|
}
|
|
|
|
function stopBfTicker() {
|
|
if (bfTicker) {
|
|
clearInterval(bfTicker)
|
|
bfTicker = null
|
|
}
|
|
}
|
|
|
|
export const useCareStore = defineStore('care', {
|
|
state: () => ({
|
|
context: null as FamilyContext | null,
|
|
babies: [] as BabyProfile[],
|
|
members: [] as FamilyMember[],
|
|
selectedBabyId: localStorage.getItem('selectedBabyId') || '',
|
|
baby: null as BabyProfile | null,
|
|
summary: null as DailySummary | null,
|
|
operatorName: localStorage.getItem('operatorName') || '宝妈',
|
|
preferences: loadInitialPreferences() as ActionPreferences,
|
|
bfTimerActive: false,
|
|
bfActiveSide: 'left' as 'left' | 'right',
|
|
bfLeftSeconds: 0,
|
|
bfRightSeconds: 0,
|
|
bfLastTickTime: 0,
|
|
serverOffsetMs: 0,
|
|
loading: false,
|
|
error: ''
|
|
}),
|
|
actions: {
|
|
async syncServerTime() {
|
|
try {
|
|
const info = await getServerTime()
|
|
if (info && typeof info.timestamp === 'number') {
|
|
this.serverOffsetMs = info.timestamp - Date.now()
|
|
}
|
|
} catch {
|
|
// fallback
|
|
}
|
|
},
|
|
getServerNow(): Date {
|
|
return new Date(Date.now() + this.serverOffsetMs)
|
|
},
|
|
async load() {
|
|
this.loading = true
|
|
this.error = ''
|
|
try {
|
|
await this.syncServerTime()
|
|
this.context = await getFamilyContext()
|
|
this.babies = this.context.babies
|
|
this.members = this.context.members
|
|
if (!this.selectedBabyId && this.babies[0]) {
|
|
this.selectedBabyId = this.babies[0].babyId
|
|
}
|
|
const selected = this.babies.find(baby => baby.babyId === this.selectedBabyId) || this.babies[0]
|
|
this.baby = selected || null
|
|
if (this.baby) {
|
|
localStorage.setItem('selectedBabyId', this.baby.babyId)
|
|
this.summary = await getDailySummary(this.baby.babyId)
|
|
this.syncBreastfeedTimer()
|
|
}
|
|
} catch (error) {
|
|
this.error = error instanceof Error ? error.message : '加载失败'
|
|
} finally {
|
|
this.loading = false
|
|
}
|
|
},
|
|
async refreshSummary() {
|
|
if (!this.baby) return
|
|
await this.syncServerTime()
|
|
this.summary = await getDailySummary(this.baby.babyId)
|
|
this.syncBreastfeedTimer()
|
|
},
|
|
async selectBaby(babyId: string) {
|
|
this.selectedBabyId = babyId
|
|
localStorage.setItem('selectedBabyId', babyId)
|
|
this.baby = this.babies.find(baby => baby.babyId === babyId) || this.baby
|
|
await this.refreshSummary()
|
|
},
|
|
setOperatorName(name: string) {
|
|
this.operatorName = name || '宝妈'
|
|
localStorage.setItem('operatorName', this.operatorName)
|
|
},
|
|
savePreferences(prefs: Partial<ActionPreferences>) {
|
|
this.preferences = { ...this.preferences, ...prefs }
|
|
localStorage.setItem('actionPreferences', JSON.stringify(this.preferences))
|
|
},
|
|
async saveBaby(payload: Pick<BabyProfile, 'name' | 'gender' | 'birthDate' | 'deliveryType'>) {
|
|
this.baby = this.baby ? await updateBaby(this.baby.babyId, payload) : await updateCurrentBaby(payload)
|
|
this.babies = this.babies.map(baby => baby.babyId === this.baby?.babyId ? this.baby! : baby)
|
|
await this.refreshSummary()
|
|
},
|
|
async addBaby(payload: CreateBabyPayload) {
|
|
const newBaby = await createBaby(payload)
|
|
this.babies.push(newBaby)
|
|
if (payload.isDefault || this.babies.length === 1) {
|
|
await this.selectBaby(newBaby.babyId)
|
|
}
|
|
return newBaby
|
|
},
|
|
async setDefaultBaby(babyId: string) {
|
|
const updated = await apiSetDefaultBaby(babyId)
|
|
this.babies = this.babies.map(b => ({
|
|
...b,
|
|
isDefault: b.babyId === babyId ? 1 : 0
|
|
}))
|
|
await this.selectBaby(babyId)
|
|
return updated
|
|
},
|
|
async saveFamily(payload: UpdateFamilyPayload) {
|
|
if (!this.context?.family.familyId) return
|
|
const updated = await updateFamily(this.context.family.familyId, payload)
|
|
this.context.family = updated
|
|
},
|
|
async addMember(payload: CreateMemberPayload) {
|
|
if (!this.context?.family.familyId) return
|
|
const newMember = await createMember(this.context.family.familyId, payload)
|
|
if (payload.defaultOperator) {
|
|
this.members.forEach(m => { m.defaultOperator = false })
|
|
this.setOperatorName(newMember.roleName)
|
|
}
|
|
this.members.push(newMember)
|
|
return newMember
|
|
},
|
|
async editMember(memberId: string, payload: UpdateMemberPayload) {
|
|
if (!this.context?.family.familyId) return
|
|
const updated = await updateMember(this.context.family.familyId, memberId, payload)
|
|
if (payload.defaultOperator) {
|
|
this.members.forEach(m => { m.defaultOperator = false })
|
|
this.setOperatorName(updated.roleName)
|
|
}
|
|
this.members = this.members.map(m => m.memberId === memberId ? updated : m)
|
|
return updated
|
|
},
|
|
async removeMember(memberId: string) {
|
|
if (!this.context?.family.familyId) return
|
|
await deleteMember(this.context.family.familyId, memberId)
|
|
this.members = this.members.filter(m => m.memberId !== memberId)
|
|
},
|
|
async logFeeding(
|
|
payloadOrMethod: {
|
|
method: FeedingMethod
|
|
amountMl?: number
|
|
breastSide?: string
|
|
durationMinutes?: number
|
|
feedingTime?: string
|
|
endTime?: string
|
|
leftDurationMinutes?: number
|
|
rightDurationMinutes?: number
|
|
note?: string
|
|
} | FeedingMethod,
|
|
amountMl?: number,
|
|
breastSide?: string
|
|
) {
|
|
if (!this.baby) return
|
|
if (typeof payloadOrMethod === 'string') {
|
|
await createFeeding({
|
|
babyId: this.baby.babyId,
|
|
feedingMethod: payloadOrMethod,
|
|
amountMl,
|
|
breastSide,
|
|
operatorName: this.operatorName
|
|
})
|
|
} else {
|
|
await createFeeding({
|
|
babyId: this.baby.babyId,
|
|
feedingMethod: payloadOrMethod.method,
|
|
amountMl: payloadOrMethod.amountMl,
|
|
breastSide: payloadOrMethod.breastSide,
|
|
durationMinutes: payloadOrMethod.durationMinutes,
|
|
feedingTime: payloadOrMethod.feedingTime,
|
|
endTime: payloadOrMethod.endTime,
|
|
leftDurationMinutes: payloadOrMethod.leftDurationMinutes,
|
|
rightDurationMinutes: payloadOrMethod.rightDurationMinutes,
|
|
note: payloadOrMethod.note,
|
|
operatorName: this.operatorName
|
|
})
|
|
}
|
|
await this.refreshSummary()
|
|
},
|
|
persistBfTimer() {
|
|
if (!this.baby) return
|
|
try {
|
|
localStorage.setItem(`bfTimer_${this.baby.babyId}`, JSON.stringify({
|
|
activeSide: this.bfActiveSide,
|
|
leftSeconds: this.bfLeftSeconds,
|
|
rightSeconds: this.bfRightSeconds,
|
|
lastTickTime: this.bfLastTickTime
|
|
}))
|
|
} catch {
|
|
// ignore
|
|
}
|
|
},
|
|
clearBfTimerStorage() {
|
|
if (!this.baby) return
|
|
try {
|
|
localStorage.removeItem(`bfTimer_${this.baby.babyId}`)
|
|
} catch {
|
|
// ignore
|
|
}
|
|
},
|
|
syncBreastfeedTimer() {
|
|
if (!this.baby) return
|
|
const active = this.summary?.activeFeeding
|
|
if (active) {
|
|
let restored = false
|
|
try {
|
|
const raw = localStorage.getItem(`bfTimer_${this.baby.babyId}`)
|
|
if (raw) {
|
|
const data = JSON.parse(raw)
|
|
this.bfActiveSide = data.activeSide === 'right' ? 'right' : 'left'
|
|
this.bfLeftSeconds = Number(data.leftSeconds) || 0
|
|
this.bfRightSeconds = Number(data.rightSeconds) || 0
|
|
const lastTick = Number(data.lastTickTime) || Date.now()
|
|
const delta = Math.max(0, Math.floor((Date.now() - lastTick) / 1000))
|
|
if (delta > 0) {
|
|
if (this.bfActiveSide === 'left') {
|
|
this.bfLeftSeconds += delta
|
|
} else {
|
|
this.bfRightSeconds += delta
|
|
}
|
|
}
|
|
this.bfLastTickTime = Date.now()
|
|
this.bfTimerActive = true
|
|
restored = true
|
|
}
|
|
} catch {
|
|
// ignore
|
|
}
|
|
if (!restored) {
|
|
const startMs = active.startTime ? new Date(active.startTime).getTime() : Date.now()
|
|
const totalElapsed = Math.max(0, Math.floor((Date.now() - startMs) / 1000))
|
|
this.bfActiveSide = this.preferences.defaultBreastSide || 'left'
|
|
this.bfLeftSeconds = this.bfActiveSide === 'left' ? totalElapsed : 0
|
|
this.bfRightSeconds = this.bfActiveSide === 'right' ? totalElapsed : 0
|
|
this.bfLastTickTime = Date.now()
|
|
this.bfTimerActive = true
|
|
}
|
|
this.persistBfTimer()
|
|
startBfTicker(this)
|
|
} else {
|
|
if (this.bfTimerActive) {
|
|
this.bfTimerActive = false
|
|
this.bfLeftSeconds = 0
|
|
this.bfRightSeconds = 0
|
|
this.clearBfTimerStorage()
|
|
stopBfTicker()
|
|
}
|
|
}
|
|
},
|
|
async startBreastfeedTimer(breastSide: 'left' | 'right') {
|
|
if (!this.baby) return
|
|
await startFeeding({
|
|
babyId: this.baby.babyId,
|
|
breastSide,
|
|
operatorName: this.operatorName
|
|
})
|
|
this.bfTimerActive = true
|
|
this.bfActiveSide = breastSide
|
|
this.bfLeftSeconds = 0
|
|
this.bfRightSeconds = 0
|
|
this.bfLastTickTime = Date.now()
|
|
this.persistBfTimer()
|
|
startBfTicker(this)
|
|
await this.refreshSummary()
|
|
},
|
|
switchBreastfeedSide(targetSide: 'left' | 'right') {
|
|
if (!this.bfTimerActive || this.bfActiveSide === targetSide) return
|
|
const now = Date.now()
|
|
const delta = Math.max(0, Math.floor((now - this.bfLastTickTime) / 1000))
|
|
if (delta > 0) {
|
|
if (this.bfActiveSide === 'left') {
|
|
this.bfLeftSeconds += delta
|
|
} else {
|
|
this.bfRightSeconds += delta
|
|
}
|
|
}
|
|
this.bfActiveSide = targetSide
|
|
this.bfLastTickTime = now
|
|
this.persistBfTimer()
|
|
},
|
|
async endBreastfeedTimer() {
|
|
if (!this.baby) return
|
|
if (this.bfTimerActive) {
|
|
const now = Date.now()
|
|
const delta = Math.max(0, Math.floor((now - this.bfLastTickTime) / 1000))
|
|
if (delta > 0) {
|
|
if (this.bfActiveSide === 'left') {
|
|
this.bfLeftSeconds += delta
|
|
} else {
|
|
this.bfRightSeconds += delta
|
|
}
|
|
}
|
|
}
|
|
const leftMinutes = this.bfLeftSeconds > 0 ? Math.max(1, Math.round(this.bfLeftSeconds / 60)) : 0
|
|
const rightMinutes = this.bfRightSeconds > 0 ? Math.max(1, Math.round(this.bfRightSeconds / 60)) : 0
|
|
|
|
await endFeeding({
|
|
babyId: this.baby.babyId,
|
|
breastSide: this.bfActiveSide,
|
|
leftDurationMinutes: leftMinutes,
|
|
rightDurationMinutes: rightMinutes,
|
|
operatorName: this.operatorName
|
|
})
|
|
|
|
this.bfTimerActive = false
|
|
this.bfLeftSeconds = 0
|
|
this.bfRightSeconds = 0
|
|
this.clearBfTimerStorage()
|
|
stopBfTicker()
|
|
await this.refreshSummary()
|
|
},
|
|
async toggleBreastfeedTimer(breastSide: 'left' | 'right') {
|
|
if (!this.baby) return
|
|
if (this.summary?.activeFeeding) {
|
|
await this.endBreastfeedTimer()
|
|
} else {
|
|
await this.startBreastfeedTimer(breastSide)
|
|
}
|
|
await this.refreshSummary()
|
|
},
|
|
async toggleSleep() {
|
|
if (!this.baby) return
|
|
if (this.summary?.activeSleep) {
|
|
await endSleep({ babyId: this.baby.babyId, operatorName: this.operatorName })
|
|
} else {
|
|
await startSleep({ babyId: this.baby.babyId, operatorName: this.operatorName })
|
|
}
|
|
await this.refreshSummary()
|
|
},
|
|
async logPee() {
|
|
if (!this.baby) return
|
|
await createPee({ babyId: this.baby.babyId, operatorName: this.operatorName })
|
|
await this.refreshSummary()
|
|
},
|
|
async logPoop() {
|
|
if (!this.baby) return
|
|
await createPoop({ babyId: this.baby.babyId, operatorName: this.operatorName })
|
|
await this.refreshSummary()
|
|
},
|
|
async manualLog(payload: Omit<CreateManualRecordPayload, 'babyId'>) {
|
|
if (!this.baby) return
|
|
const res = await createManualRecord({
|
|
...payload,
|
|
babyId: this.baby.babyId
|
|
})
|
|
await this.refreshSummary()
|
|
return res
|
|
},
|
|
async editRecord(recordId: string, payload: UpdateCareRecordPayload) {
|
|
const res = await updateRecord(recordId, payload)
|
|
await this.refreshSummary()
|
|
return res
|
|
}
|
|
}
|
|
})
|