today_controller.dart 20.5 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 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650
import 'dart:async';

import 'package:doublefeel_flutter/app/modules/home/widgets/today/no_health_data_page.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/error/app_error.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_upload_models.dart';
import 'package:doublefeel_flutter/data/models/user/user_models.dart';
import 'package:flutter/material.dart';
import 'package:get/get.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,
  );

  final UserApi _userApi;
  final HealthApi _healthApi;
  final UserStateService _userStateService;
  final HealthKitUploadService _healthKitUploadService;

  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;

  // ── 压力状态 ─────────────────────────────
  final stressLabel = '状态正常'.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 latestHrvValue = '--'.obs;
  final latestHrvTimeLabel = ''.obs;

  // ── 睡眠卡片 ──────────────────────────────
  final sleepHours = '--'.obs;
  final sleepMinutes = '--'.obs;
  final sleepQuality = '--'.obs;
  final sleepAverageHeartRate = '--'.obs;
  final sleepProgress = 0.0.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;

  Future<void> requestHealthAuthorization() async {
    // try {
    //   await _healthKitUploadService.requestClientAuthorization();
    //   await _refreshHealthAuthorizationState();
    // } catch (error) {
    //   debugPrint('Health authorization skipped: $error');
    // }
    Get.to(NoHealthDataPage());
  }

  @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));
  }

  Future<void> loadTodayData() => loadDataForDate(lastSelectableDay);

  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([
        _refreshUserGreeting(),
        // _refreshHealthAuthorizationState(),
        _refreshHealthDataForDate(date),
      ]);
    } catch (error, stackTrace) {
      AppLogger.e('TodayController.loadDataForDate failed', error, stackTrace);
    } finally {
      if (selectedDate.value == date) {
        isLoadingToday.value = false;
      }
    }
  }

  Future<void> _refreshUserGreeting() async {
    final result = await _userApi.getUserInfo(errorHandlingPolicy: null);
    if (result case AppSuccess<UserInfoResponse>(data: final user)) {
      final name = user.nickname?.trim();
      stressSubtitle.value = name == null || name.isEmpty
          ? 'Hi, 你今日的综合压力状态'
          : 'Hi, $name 今日的综合压力状态';
    }
  }

  Future<void> _refreshHealthAuthorizationState() async {
    final serverAuth =
        await _healthApi.checkServerHealthAuth(errorHandlingPolicy: null);
    final hasServerAuth = switch (serverAuth) {
      AppSuccess<HealthAuthResponse>(data: final auth) =>
        auth.scope?.trim().isNotEmpty == true,
      _ => false,
    };

    bool hasClientAuth = false;
    try {
      hasClientAuth = await _healthKitUploadService.isHealthAuthorized();
    } catch (error, stackTrace) {
      AppLogger.w('Health authorization check failed', error, stackTrace);
    }

    showHealthDataAuthCard.value = !(hasServerAuth || hasClientAuth);
  }

  Future<void> _refreshHealthDataForDate(DateTime date) async {
    final startYear = date.year;
    final startMonth = date.month;
    final startDate = startYear * 10000 + startMonth * 100 + 1; // e.g. 20260601
    const dateRangeType = 1;

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

    final todayResultFuture = isToday
        ? _healthApi.getTodayData(
            isOther: false,
            errorHandlingPolicy: null,
          )
        : Future.value(
            AppFailure<TodayStatusData>(AppUnknownError('Not today')));

    final latestHrvResultFuture = isToday
        ? _healthApi.getLatestHrvData(
            errorHandlingPolicy: null,
          )
        : Future.value(AppFailure<LatestHrvData>(AppUnknownError('Not today')));

    final hrvStatisticsResultFuture = _healthApi.getHrvStatistics(
      isOther: false,
      dateRangeType: dateRangeType,
      startDate: startDate,
      errorHandlingPolicy: null,
    );
    final sleepStatisticsResultFuture = _healthApi.getSleepStateStatistics(
      isOther: false,
      dateRangeType: dateRangeType,
      startDate: startDate,
      errorHandlingPolicy: null,
    );
    final activityStatisticsResultFuture = _healthApi.getActivityBurnStatistics(
      isOther: false,
      dateRangeType: dateRangeType,
      startDate: startDate,
      errorHandlingPolicy: null,
    );

    final todayResult = await todayResultFuture;
    final latestHrvResult = await latestHrvResultFuture;
    final hrvStatisticsResult = await hrvStatisticsResultFuture;
    final sleepStatisticsResult = await sleepStatisticsResultFuture;
    final activityStatisticsResult = await activityStatisticsResultFuture;

    if (selectedDate.value != date) return;

    if (!isToday) {
      _clearRealTimeData();
    }

    if (todayResult case AppSuccess<TodayStatusData>(data: final today)) {
      _applyTodayData(today);
    } else if (todayResult case AppFailure(error: final error)) {
      if (isToday) {
        AppLogger.w('HealthApi.getTodayData failed: $error');
      }
    }

    if (latestHrvResult case AppSuccess<LatestHrvData>(data: final latestHrv)) {
      _applyLatestHrvData(latestHrv);
    }

    if (hrvStatisticsResult
        case AppSuccess<HrvStatisticsData>(data: final hrvStatistics)) {
      _applyHrvStatistics(hrvStatistics, date);
    }

    if (sleepStatisticsResult
        case AppSuccess<SleepStatisticsData>(data: final sleepStatistics)) {
      _applySleepStatistics(sleepStatistics, date);
    }

    if (activityStatisticsResult
        case AppSuccess<ActivityBurnStatisticsData>(
          data: final activityStatistics
        )) {
      _applyActivityStatistics(activityStatistics, date);
    }
  }

  void _clearRealTimeData() {
    restingHeartRate.value = '--';
    sleepAverageHeartRate.value = '--';
    sleepHours.value = '--';
    sleepMinutes.value = '--';
    sleepQuality.value = '--';
    sleepProgress.value = 0.0;
    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 = '--';
    latestHrvValue.value = '--';
    latestHrvTimeLabel.value = '';
    stressLabel.value = '状态正常';
  }

  void _applyTodayData(TodayStatusData today) {
    final recent = today.recentData;
    if (recent?.heartRate != null) {
      restingHeartRate.value = _formatMetric(recent!.heartRate);
      if (sleepAverageHeartRate.value == '--') {
        sleepAverageHeartRate.value = _formatMetric(recent.heartRate);
      }
    }

    _applySleepDuration(today.sleepDuration);
    _applyActivityRecentData(recent);

    final hrvPoints = _buildHrvChartData(today.hrvDataList);
    hrvChartData.assignAll(hrvPoints);
    stressChartData.assignAll(
      hrvPoints.map((point) {
        return HrvDataPoint(
          hour: point.hour,
          hrv: _stressScoreFromHrv(point.hrv),
        );
      }),
    );

    final latest = _latestTodayHrv(today.hrvDataList);
    _applyLatestTodayHrv(latest);

    final hrvValues = hrvPoints.map((point) => point.hrv).toList();
    if (hrvValues.isNotEmpty) {
      final average = hrvValues.reduce((value, element) => value + element) /
          hrvValues.length;
      avgHrv.value = _formatMetric(average);

      final latestStatus = latest?.hrvStatus;
      if (latestStatus != null) {
        stressLabel.value = latestStatus.title;
      }
      _updateLatestHrvAnnotation(latest);
    }
  }

  void _applyLatestHrvData(LatestHrvData latestHrv) {
    final userHrv = latestHrv.userHrv;
    if (avgHrv.value == '--' && userHrv != null) {
      avgHrv.value = _formatMetric(userHrv);
    }
    if (latestHrvValue.value == '--' && userHrv != null) {
      latestHrvValue.value = _formatMetric(userHrv);
      latestHrvTimeLabel.value = '';
    }
    if (userHrv != null) {
      stressLabel.value = _hrvStatusTitle(
        value: userHrv,
        baseline: latestHrv.userHrvBaseline,
      );
    }
  }

  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);
    }
    if (data.avgSleepingHeartRate != null) {
      sleepAverageHeartRate.value = _formatMetric(data.avgSleepingHeartRate);
    }
  }

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

    if (isToday) {
      if (sleepHours.value == '--' && data.avgSleepDuration != null) {
        _applySleepDuration(data.avgSleepDuration);
      }
    } else {
      int? dailySleep;
      if (data.sleepTrendList != null) {
        for (final trend in data.sleepTrendList!) {
          if (trend.timeKey == dateKey) {
            dailySleep = trend.average;
            break;
          }
        }
      }
      _applySleepDuration(dailySleep);
    }

    final deepPercentage = data.deepPercentage;
    if (deepPercentage != null) {
      sleepQuality.value = _sleepQualityFromDeepPercentage(deepPercentage);
    }
  }

  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;

    latestHrvValue.value = _formatMetric(value);
    final time = latest?.time;
    latestHrvTimeLabel.value =
        time == null ? '' : _formatHour(_hourFromApiTime(time));
  }

  void _applySleepDuration(int? rawDuration) {
    final minutes = _normalizeDurationMinutes(rawDuration);
    if (minutes == null) {
      sleepHours.value = '--';
      sleepMinutes.value = '--';
      sleepQuality.value = '--';
      sleepProgress.value = 0;
      return;
    }

    sleepHours.value = '${minutes ~/ 60}';
    sleepMinutes.value = '${minutes % 60}';
    sleepQuality.value = _sleepQualityFromDuration(minutes);
    sleepProgress.value = _progress(minutes.toDouble(), 8 * 60);
  }

  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;
  }

  void _updateLatestHrvAnnotation(TodayHrvData? latest) {
    if (latest?.time == null || latest?.value == null) {
      hrvAnnotations.clear();
      return;
    }

    final hour = _hourFromApiTime(latest!.time!);
    hrvAnnotations.assignAll([
      HrvAnnotation(
        hour: hour,
        hrv: latest.value!,
        stateLabel: latest.hrvStatus?.title ?? stressLabel.value,
        detail: 'HRV ${_formatMetric(latest.value)}ms · ${_formatHour(hour)}',
      ),
    ]);
  }

  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';
  }
}