today_controller.dart 16.7 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540
import 'dart:async';
import 'dart:math';

import 'package:doublefeel_flutter/app/apple_health_upload/apple_health_upload_tool.dart';
import 'package:doublefeel_flutter/app/modules/friends/controllers/friend_trend_controller.dart';
import 'package:doublefeel_flutter/app/modules/home/controllers/home_controller.dart';
import 'package:doublefeel_flutter/app/modules/home/controllers/trend/trend_controller.dart';
import 'package:doublefeel_flutter/app/modules/home/widgets/today/no_health_data_page.dart';
import 'package:doublefeel_flutter/app/routes/app_pages.dart';
import 'package:doublefeel_flutter/core/logging/app_logger.dart';
import 'package:doublefeel_flutter/core/network/api/health_api.dart';
import 'package:doublefeel_flutter/core/network/api/user_api.dart';
import 'package:doublefeel_flutter/core/result/app_result.dart';
import 'package:doublefeel_flutter/core/services/health_kit_upload_service.dart';
import 'package:doublefeel_flutter/core/services/user_state_service.dart';
import 'package:doublefeel_flutter/data/models/enums/app_enums.dart';
import 'package:doublefeel_flutter/data/models/health/health_models.dart';
import 'package:doublefeel_flutter/data/models/health/health_v2_models.dart';
import 'package:doublefeel_flutter/pigeon/health_kit_api.g.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:intl/intl.dart';

/// HRV 趋势数据点
class HrvDataPoint {
  final double hour; // 0.0 ~ 24.0
  final double hrv;

  const HrvDataPoint({required this.hour, required this.hrv});
}

/// HRV tooltip 标注点
class HrvAnnotation {
  final double hour;
  final double hrv;
  final String stateLabel; // e.g. "状态优秀"
  final String detail; // e.g. "HRV 23ms · 11:28"

  const HrvAnnotation({
    required this.hour,
    required this.hrv,
    required this.stateLabel,
    required this.detail,
  });
}

class TodayController extends GetxController {
  TodayController(
    this._userApi,
    this._healthApi,
    this._userStateService,
    this._healthKitUploadService,
    this._appleHealthUploadTool, {
    this.friendUserId, // null = 自己,非 null = 好友
  });

  final UserApi _userApi;
  final HealthApi _healthApi;
  final UserStateService _userStateService;
  final HealthKitUploadService _healthKitUploadService;
  final AppleHealthUploadTool _appleHealthUploadTool;
  final HealthKitHostApi _hostApi = HealthKitHostApi();

  /// 好友的 userId;null 表示查看自己的数据,非 null 表示查看好友的数据。
  final int? friendUserId;

  /// 是否正在查看好友数据。
  bool get isFriend => friendUserId != null;

  UserStateService get userStateService => _userStateService;

  late final DateTime firstSelectableDay;
  late final DateTime lastSelectableDay;
  final selectedDate = DateTime.now().obs;
  final focusedDay = DateTime.now().obs;
  final scrollOffset = 0.0.obs;

  final isLoadingToday = false.obs;
  final showHealthDataAuthCard = true.obs;
  final stressSubtitle = 'Hi, 你今日的综合压力状态'.obs;

  // ── HRV 表盘引导 Banner ───────────────────
  final showHrvAdBanner = true.obs;
  final showPartnerAdBanner = true.obs;

  void dismissHrvAdBanner() => showHrvAdBanner.value = false;

  void dismissPartnerAdBanner() => showPartnerAdBanner.value = false;

  // ── HRV 数字 + 心率 ───────────────────────
  final avgHrv = '--'.obs;
  final restingHeartRate = '--'.obs;

  // ── 健身卡片 ──────────────────────────────
  final activityCalories = '--'.obs;
  final activityExerciseMinutes = '--'.obs;
  final activityStandHours = '--'.obs;
  final activityMoveProgress = 0.0.obs;
  final activityExerciseProgress = 0.0.obs;
  final activityStandProgress = 0.0.obs;
  int? _activityMoveTarget;
  int? _activityStandTarget;

  // ── HRV 趋势图 ────────────────────────────
  final hrvChartData = <HrvDataPoint>[].obs;
  final stressChartData = <HrvDataPoint>[].obs;

  final hrvAnnotations = <HrvAnnotation>[].obs;

  final v2HealthData = Rxn<V2HealthData>();
  final v2StressScore = Rxn<V2StressScore>();
  final v2LatestHrv = Rxn<V2LatestHrvData>();
  final v2HrvTrend = Rxn<V2HrvTrendData>();
  final v2RealtimeStress = Rxn<V2RealtimeStressData>();

  Future<void> requestHealthAuthorization() async {
    if (GetPlatform.isIOS) {
      try {
        final result = await _hostApi.checkHealthAppAuthorization();
        print("checkHealthAppAuthorization : $result");
        if (result.status == 0) {
          bool success = await _hostApi.requestHealthClientAuthorization();
          print("requestHealthClientAuthorization : $success");
          if (success) {
            _performDataUpload();
          } else {
            Get.to(NoHealthDataPage(
              onRefresh: _performDataUpload,
            ));
          }
          return;
        }
        Get.to(NoHealthDataPage(
          onRefresh: _performDataUpload,
        ));
      } catch (e) {}
    }
  }

  @override
  void onInit() {
    super.onInit();
    final today = DateUtils.dateOnly(DateTime.now());
    firstSelectableDay = DateTime(today.year - 1);
    lastSelectableDay = today;
    selectedDate.value = today;
    focusedDay.value = today;

    ever<DateTime>(selectedDate, (date) {
      unawaited(loadDataForDate(date));
    });

    unawaited(loadDataForDate(today));
  }

  void changeDate(DateTime date, {DateTime? focused}) {
    final normalizedDate = _clampDate(date);
    selectedDate.value = normalizedDate;
    focusedDay.value = _clampDate(focused ?? normalizedDate);
  }

  DateTime _clampDate(DateTime date) {
    final normalizedDate = DateUtils.dateOnly(date);
    if (normalizedDate.isBefore(firstSelectableDay)) return firstSelectableDay;
    if (normalizedDate.isAfter(lastSelectableDay)) return lastSelectableDay;
    return normalizedDate;
  }

  Future<void> loadDataForDate(DateTime date) async {
    isLoadingToday.value = true;
    try {
      await Future.wait([
        _refreshHealthAuthorizationState(),
        _refreshHealthDataForDate(date),
      ]);
    } catch (error, stackTrace) {
      AppLogger.e('TodayController.loadDataForDate failed', error, stackTrace);
    } finally {
      if (selectedDate.value == date) {
        isLoadingToday.value = false;
      }
    }
  }

  /// 上传 Apple Health 新数据。
  Future<void> _performDataUpload() async {
    try {
      final result =
          await _appleHealthUploadTool.uploadAllNewDataFromHealthKit();
      AppLogger.i(
        'Apple Health upload finished: '
        'common=${result.commonUploadSuccess}(${result.commonCount}), '
        'sleep=${result.sleepUploadSuccess}(${result.sleepCount}), '
        'activityTarget=${result.activityTargetUploadSuccess}'
        '(${result.activityTargetCount}), '
        'success=${result.isSuccess}',
      );
    } catch (error, stackTrace) {
      AppLogger.e('Apple Health upload failed', error, stackTrace);
    }
  }

  Future<void> _refreshHealthAuthorizationState() async {
    try {
      final result = await _hostApi.checkHealthAppAuthorization();

      showHealthDataAuthCard.value = result.status != 1;
    } catch (e) {}
  }

  Future<void> _refreshHealthDataForDate(DateTime date) async {
    _clearRealTimeData();
    final intDate = int.parse(DateFormat('yyyyMMdd').format(date));

    final isToday = DateUtils.isSameDay(date, lastSelectableDay);
    stressSubtitle.value = isToday ? 'Hi, 你今日的综合压力状态' : '该日压力状态';
    switch (await _healthApi.getV2HealthData(friendUserId, intDate)) {
      case AppSuccess(:final data):
        v2HealthData.value = data;
      case AppFailure():
        v2HealthData.value = null;
    }

    switch (await _healthApi.getV2StressScore(friendUserId, intDate)) {
      case AppSuccess(:final data):
        v2StressScore.value = data;
      case AppFailure():
        v2StressScore.value = null;
    }

    switch (await _healthApi.getV2LatestHrv(friendUserId, intDate)) {
      case AppSuccess(:final data):
        v2LatestHrv.value = data;
      case AppFailure():
        v2LatestHrv.value = null;
    }

    switch (await _healthApi.getV2HrvTrend(friendUserId, intDate)) {
      case AppSuccess(:final data):
        v2HrvTrend.value = data;
      case AppFailure():
        v2HrvTrend.value = null;
    }

    switch (await _healthApi.getV2RealtimeStress(friendUserId, intDate)) {
      case AppSuccess(:final data):
        v2RealtimeStress.value = data;
      case AppFailure():
        v2RealtimeStress.value = null;
    }
  }

  void _clearRealTimeData() {
    restingHeartRate.value = '--';

    activityCalories.value = '--';
    activityExerciseMinutes.value = '--';
    activityStandHours.value = '--';
    activityMoveProgress.value = 0.0;
    activityExerciseProgress.value = 0.0;
    activityStandProgress.value = 0.0;
    hrvChartData.clear();
    stressChartData.clear();
    hrvAnnotations.clear();
    avgHrv.value = '--';
  }

  void _applyHrvStatistics(HrvStatisticsData data, DateTime date) {
    final dateKey = date.day;
    final isToday = DateUtils.isSameDay(date, lastSelectableDay);

    if (isToday) {
      if (avgHrv.value == '--' && data.avgHrv != null) {
        avgHrv.value = _formatMetric(data.avgHrv);
      }
    } else {
      double? dailyHrv;
      if (data.hrvTrendList != null) {
        for (final trend in data.hrvTrendList!) {
          if (trend.timeKey == dateKey) {
            dailyHrv = trend.average;
            break;
          }
        }
      }
      avgHrv.value = _formatMetric(dailyHrv);
    }

    if (data.avgRestingHeartRate != null) {
      restingHeartRate.value = _formatMetric(data.avgRestingHeartRate);
    }
  }

  void _applyActivityStatistics(
      ActivityBurnStatisticsData data, DateTime date) {
    _activityMoveTarget = data.activityTargetInfo?.move ?? _activityMoveTarget;
    _activityStandTarget =
        data.activityTargetInfo?.stand ?? _activityStandTarget;

    final dateKey = date.day;
    final isToday = DateUtils.isSameDay(date, lastSelectableDay);

    if (isToday) {
      if (activityCalories.value == '--' && data.totalCaloriesBurned != null) {
        activityCalories.value = _formatMetric(data.totalCaloriesBurned);
      }
      if (activityStandHours.value == '--' && data.totalStand != null) {
        activityStandHours.value = _formatMetric(data.totalStand);
      }
    } else {
      int? dailyMove;
      if (data.caloriesBurnedTrendList != null) {
        for (final trend in data.caloriesBurnedTrendList!) {
          if (trend.timeKey == dateKey) {
            dailyMove = trend.value;
            break;
          }
        }
      }
      activityCalories.value = _formatMetric(dailyMove);

      int? dailyExercise;
      if (data.exerciseTimeTrendList != null) {
        for (final trend in data.exerciseTimeTrendList!) {
          if (trend.timeKey == dateKey) {
            dailyExercise = trend.value;
            break;
          }
        }
      }
      activityExerciseMinutes.value = _formatMetric(dailyExercise);
      activityStandHours.value = '--';
    }

    final moveValue = _parseMetric(activityCalories.value);
    final exerciseValue = _parseMetric(activityExerciseMinutes.value);
    final standValue = _parseMetric(activityStandHours.value);

    if (moveValue != null) {
      activityMoveProgress.value = _progress(
        moveValue,
        (_activityMoveTarget ?? 400).toDouble(),
      );
    } else {
      activityMoveProgress.value = 0.0;
    }

    if (exerciseValue != null) {
      activityExerciseProgress.value = _progress(
        exerciseValue,
        30.0,
      );
    } else {
      activityExerciseProgress.value = 0.0;
    }

    if (standValue != null) {
      activityStandProgress.value = _progress(
        standValue,
        (_activityStandTarget ?? 12).toDouble(),
      );
    } else {
      activityStandProgress.value = 0.0;
    }
  }

  void _applyLatestTodayHrv(TodayHrvData? latest) {
    final value = latest?.value;
    if (value == null) return;
  }

  void _applyActivityRecentData(TodayStatusRecentData? recent) {
    activityCalories.value = _formatMetric(recent?.move);
    activityExerciseMinutes.value = _formatMetric(recent?.exercise);
    activityStandHours.value = _formatMetric(recent?.stand);

    activityMoveProgress.value = _progress(
      (recent?.move ?? 0).toDouble(),
      (_activityMoveTarget ?? 400).toDouble(),
    );
    activityExerciseProgress.value = _progress(
      (recent?.exercise ?? 0).toDouble(),
      30,
    );
    activityStandProgress.value = _progress(
      (recent?.stand ?? 0).toDouble(),
      (_activityStandTarget ?? 12).toDouble(),
    );
  }

  List<HrvDataPoint> _buildHrvChartData(List<TodayHrvData>? dataList) {
    final points = <HrvDataPoint>[];
    for (final item in dataList ?? const <TodayHrvData>[]) {
      final time = item.time;
      final value = item.value;
      if (time == null || value == null) continue;
      points.add(HrvDataPoint(hour: _hourFromApiTime(time), hrv: value));
    }
    points.sort((a, b) => a.hour.compareTo(b.hour));
    return points;
  }

  TodayHrvData? _latestTodayHrv(List<TodayHrvData>? dataList) {
    TodayHrvData? latest;
    for (final item in dataList ?? const <TodayHrvData>[]) {
      if (item.value == null) continue;
      final latestTime = latest?.time ?? -1;
      final itemTime = item.time ?? -1;
      if (latest == null || itemTime >= latestTime) {
        latest = item;
      }
    }
    return latest;
  }

  String _hrvStatusTitle({required double value, double? baseline}) {
    if ((baseline ?? 0) > 0) {
      if (value >= 1.2 * baseline!) return HrvStatus.energetic.title;
      if (value <= 0.8 * baseline) return HrvStatus.overload.title;
      return HrvStatus.normal.title;
    }
    if (value >= 128) return HrvStatus.energetic.title;
    if (value <= 30) return HrvStatus.overload.title;
    return HrvStatus.normal.title;
  }

  double _stressScoreFromHrv(double hrv) {
    return (100 - hrv).clamp(0, 100).toDouble();
  }

  int? _normalizeDurationMinutes(int? rawDuration) {
    if (rawDuration == null || rawDuration <= 0) return null;
    if (rawDuration > 24 * 60 * 60) {
      return (rawDuration / 60000).round();
    }
    if (rawDuration > 24 * 60) {
      return (rawDuration / 60).round();
    }
    return rawDuration;
  }

  String _sleepQualityFromDuration(int minutes) {
    if (minutes >= 7 * 60 && minutes <= 9 * 60) return '优秀';
    if (minutes >= 6 * 60 && minutes < 10 * 60) return '良好';
    if (minutes >= 5 * 60) return '一般';
    return '偏少';
  }

  String _sleepQualityFromDeepPercentage(double percentage) {
    if (percentage >= 25) return '优秀';
    if (percentage >= 18) return '良好';
    if (percentage >= 12) return '一般';
    return '偏少';
  }

  double _progress(double value, double target) {
    if (target <= 0) return 0;
    return (value / target).clamp(0, 1).toDouble();
  }

  double? _parseMetric(String value) {
    if (value == '--') return null;
    return double.tryParse(value.replaceAll(',', ''));
  }

  double _hourFromApiTime(int time) {
    if (time >= 1000000000000) {
      final date = DateTime.fromMillisecondsSinceEpoch(time);
      return date.hour + date.minute / 60;
    }
    if (time >= 1000000000) {
      final date = DateTime.fromMillisecondsSinceEpoch(time * 1000);
      return date.hour + date.minute / 60;
    }
    if (time > 24) {
      final hour = (time ~/ 100).clamp(0, 23);
      final minute = (time % 100).clamp(0, 59);
      return hour + minute / 60;
    }
    return time.toDouble().clamp(0, 24).toDouble();
  }

  String _formatMetric(num? value) {
    if (value == null) return '--';
    if (value % 1 == 0) return '${value.toInt()}';
    return value.toStringAsFixed(1);
  }

  String _formatHour(double hour) {
    final totalMinutes = (hour * 60).round();
    final h = (totalMinutes ~/ 60).clamp(0, 23).toString().padLeft(2, '0');
    final m = (totalMinutes % 60).toString().padLeft(2, '0');
    return '$h:$m';
  }

  toTrendHrvPage() {
    if (isFriend) {
      Get.toNamed(
        Routes.FRIEND_TREND,
        arguments: FriendTrendArguments(
          userId: 58,
          name: 'xxa',
          avatarUrl: 'asdfa',
        ),
      );
    } else {
      Get.find<HomeController>().openTrend(TrendType.hrv);
    }
  }

  toTrendSleepPage() {
    if (isFriend) {
      Get.toNamed(
        Routes.FRIEND_TREND,
        arguments: FriendTrendArguments(
          userId: 58,
          name: 'xxa',
          avatarUrl: 'asdfa',
        ),
      );
    } else {
      Get.find<HomeController>().openTrend(TrendType.sleep);
    }
  }

  toTrendActivityPage() {
    if (isFriend) {
      Get.toNamed(
        Routes.FRIEND_TREND,
        arguments: FriendTrendArguments(
          userId: 58,
          name: 'xxa',
          avatarUrl: 'asdfa',
        ),
      );
    } else {
      Get.find<HomeController>().openTrend(TrendType.activity);
    }
  }
}