feat(notifications): 新增晚餐和心情提醒功能,支持HRV压力检测和后台处理
- 新增晚餐提醒(18:00)和心情提醒(21:00)的定时通知 - 实现基于HRV数据的压力检测和智能鼓励通知 - 添加后台任务处理支持,修改iOS后台模式为processing - 优化营养记录页面使用Redux状态管理,支持实时数据更新 - 重构卡路里计算公式,移除目标卡路里概念,改为基代+运动-饮食 - 新增营养目标动态计算功能,基于用户身体数据智能推荐 - 完善通知点击跳转逻辑,支持多种提醒类型的路由处理
This commit is contained in:
@@ -13,12 +13,15 @@ import { getTabBarBottomPadding } from '@/constants/TabBar';
|
||||
import { useAppDispatch, useAppSelector } from '@/hooks/redux';
|
||||
import { useAuthGuard } from '@/hooks/useAuthGuard';
|
||||
import { useBackgroundTasks } from '@/hooks/useBackgroundTasks';
|
||||
import { notificationService } from '@/services/notifications';
|
||||
import { selectHealthDataByDate, setHealthData } from '@/store/healthSlice';
|
||||
import { fetchDailyMoodCheckins, selectLatestMoodRecordByDate } from '@/store/moodSlice';
|
||||
import { fetchDailyNutritionData, selectNutritionSummaryByDate } from '@/store/nutritionSlice';
|
||||
import { getMonthDaysZh, getTodayIndexInMonth } from '@/utils/date';
|
||||
import { ensureHealthPermissions, fetchHealthDataForDate } from '@/utils/health';
|
||||
import { ensureHealthPermissions, fetchHealthDataForDate, fetchTodayHRV, fetchRecentHRV } from '@/utils/health';
|
||||
import { getTestHealthData } from '@/utils/mockHealthData';
|
||||
import { calculateNutritionGoals } from '@/utils/nutrition';
|
||||
import AsyncStorage from '@react-native-async-storage/async-storage';
|
||||
import { useBottomTabBarHeight } from '@react-navigation/bottom-tabs';
|
||||
import { useFocusEffect } from '@react-navigation/native';
|
||||
import dayjs from 'dayjs';
|
||||
@@ -58,6 +61,7 @@ const FloatingCard = ({ children, delay = 0, style }: {
|
||||
|
||||
export default function ExploreScreen() {
|
||||
const stepGoal = useAppSelector((s) => s.user.profile?.dailyStepsGoal) ?? 2000;
|
||||
const userProfile = useAppSelector((s) => s.user.profile);
|
||||
|
||||
// 开发调试:设置为true来使用mock数据
|
||||
const useMockData = __DEV__; // 改为true来启用mock数据调试
|
||||
@@ -128,6 +132,16 @@ export default function ExploreScreen() {
|
||||
// 从 Redux 获取营养数据
|
||||
const nutritionSummary = useAppSelector(selectNutritionSummaryByDate(currentSelectedDateString));
|
||||
|
||||
// 计算用户的营养目标
|
||||
const nutritionGoals = useMemo(() => {
|
||||
return calculateNutritionGoals({
|
||||
weight: userProfile.weight,
|
||||
height: userProfile.height,
|
||||
birthDate: userProfile?.birthDate ? new Date(userProfile?.birthDate) : undefined,
|
||||
gender: userProfile?.gender || undefined,
|
||||
});
|
||||
}, [userProfile]);
|
||||
|
||||
const { registerTask } = useBackgroundTasks();
|
||||
// 心情相关状态
|
||||
const dispatch = useAppDispatch();
|
||||
@@ -284,6 +298,8 @@ export default function ExploreScreen() {
|
||||
handler: async () => {
|
||||
try {
|
||||
await loadHealthData();
|
||||
|
||||
checkStressLevelAndNotify()
|
||||
} catch (error) {
|
||||
console.error('健康数据任务执行失败:', error);
|
||||
}
|
||||
@@ -291,6 +307,80 @@ export default function ExploreScreen() {
|
||||
});
|
||||
}, []);
|
||||
|
||||
// 检查压力水平并发送通知
|
||||
const checkStressLevelAndNotify = React.useCallback(async () => {
|
||||
try {
|
||||
console.log('开始检查压力水平...');
|
||||
|
||||
// 确保有健康权限
|
||||
const hasPermission = await ensureHealthPermissions();
|
||||
if (!hasPermission) {
|
||||
console.log('没有健康权限,跳过压力检查');
|
||||
return;
|
||||
}
|
||||
|
||||
// 获取最近2小时内的实时HRV数据
|
||||
const recentHRV = await fetchRecentHRV(2);
|
||||
console.log('获取到的最近2小时HRV值:', recentHRV);
|
||||
|
||||
if (recentHRV === null || recentHRV === undefined) {
|
||||
console.log('没有最近的HRV数据,跳过压力检查');
|
||||
return;
|
||||
}
|
||||
|
||||
// 判断压力水平(HRV值低于60表示压力过大)
|
||||
if (recentHRV < 60) {
|
||||
console.log(`检测到压力过大,HRV值: ${recentHRV},准备发送鼓励通知`);
|
||||
|
||||
// 检查是否在过去2小时内已经发送过压力提醒,避免重复打扰
|
||||
const lastNotificationKey = '@last_stress_notification';
|
||||
const lastNotificationTime = await AsyncStorage.getItem(lastNotificationKey);
|
||||
const now = new Date().getTime();
|
||||
const twoHoursAgo = now - (2 * 60 * 60 * 1000); // 2小时前
|
||||
|
||||
if (lastNotificationTime && parseInt(lastNotificationTime) > twoHoursAgo) {
|
||||
console.log('2小时内已发送过压力提醒,跳过本次通知');
|
||||
return;
|
||||
}
|
||||
|
||||
// 随机选择一条鼓励性消息
|
||||
const encouragingMessages = [
|
||||
'放松一下吧 🌸\n检测到您的压力指数较高,不妨暂停一下,做几个深呼吸,或者来一段轻松的普拉提练习。您的健康最重要!',
|
||||
'该休息一下了 🧘♀️\n您的身体在提醒您需要放松。试试冥想、散步或听听舒缓的音乐,让心情平静下来。',
|
||||
'压力山大?我们来帮您 💆♀️\n高压力对健康不利,建议您做一些放松运动,比如瑜伽或普拉提,释放身心压力。',
|
||||
'关爱自己,从现在开始 💝\n检测到您可能承受较大压力,记得给自己一些时间,做喜欢的事情,保持身心健康。',
|
||||
'深呼吸,一切都会好的 🌈\n压力只是暂时的,试试腹式呼吸或简单的伸展运动,让身体和心灵都得到放松。'
|
||||
];
|
||||
|
||||
const randomMessage = encouragingMessages[Math.floor(Math.random() * encouragingMessages.length)];
|
||||
const [title, body] = randomMessage.split('\n');
|
||||
|
||||
// 发送鼓励性推送通知
|
||||
await notificationService.sendImmediateNotification({
|
||||
title: title,
|
||||
body: body,
|
||||
data: {
|
||||
type: 'stress_alert',
|
||||
hrvValue: recentHRV,
|
||||
timestamp: new Date().toISOString(),
|
||||
url: '/mood/calendar' // 点击通知跳转到心情页面
|
||||
},
|
||||
sound: true,
|
||||
priority: 'high'
|
||||
});
|
||||
|
||||
// 记录通知发送时间
|
||||
await AsyncStorage.setItem(lastNotificationKey, now.toString());
|
||||
|
||||
console.log('压力提醒通知已发送');
|
||||
} else {
|
||||
console.log(`压力水平正常,HRV值: ${recentHRV}`);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('检查压力水平失败:', error);
|
||||
}
|
||||
}, []);
|
||||
|
||||
// 日期点击时,加载对应日期数据
|
||||
const onSelectDate = (index: number, date: Date) => {
|
||||
setSelectedIndex(index);
|
||||
@@ -331,8 +421,10 @@ export default function ExploreScreen() {
|
||||
{/* 营养摄入雷达图卡片 */}
|
||||
<NutritionRadarCard
|
||||
nutritionSummary={nutritionSummary}
|
||||
nutritionGoals={nutritionGoals}
|
||||
burnedCalories={(basalMetabolism || 0) + (activeCalories || 0)}
|
||||
calorieDeficit={0}
|
||||
basalMetabolism={basalMetabolism || 0}
|
||||
activeCalories={activeCalories || 0}
|
||||
resetToken={animToken}
|
||||
onMealPress={(mealType: 'breakfast' | 'lunch' | 'dinner' | 'snack') => {
|
||||
console.log('选择餐次:', mealType);
|
||||
|
||||
Reference in New Issue
Block a user