today_controller.dart 33.1 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 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003
import 'dart:async';

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/friend_select_bottom_sheet.dart';
import 'package:doublefeel_flutter/app/modules/home/widgets/today/no_health_data_page.dart';
import 'package:doublefeel_flutter/app/modules/home/widgets/today/huawei_health_registration_dialog.dart';
import 'package:doublefeel_flutter/app/modules/login/views/email_login_contact_us_bottom_sheet.dart';
import 'package:doublefeel_flutter/app/modules/report_common/models/report_period.dart';
import 'package:doublefeel_flutter/app/routes/app_pages.dart';
import 'package:doublefeel_flutter/app/utils/platform_compact.dart';
import 'package:doublefeel_flutter/core/config/app_environment_config.dart';
import 'package:doublefeel_flutter/core/constants/intent_keys.dart';
import 'package:doublefeel_flutter/core/logging/app_logger.dart';
import 'package:doublefeel_flutter/core/network/api/friend_api.dart';
import 'package:doublefeel_flutter/core/network/api/pay_api.dart';
import 'package:doublefeel_flutter/core/network/api/vip_api.dart';
import 'package:doublefeel_flutter/core/result/app_result.dart';
import 'package:doublefeel_flutter/core/services/raw_data_service/health_raw_data_core_service.dart';
import 'package:doublefeel_flutter/core/services/thinking_data_service.dart';
import 'package:doublefeel_flutter/core/services/user_state_service.dart';
import 'package:doublefeel_flutter/core/util/app_toast.dart';
import 'package:doublefeel_flutter/data/datasource/health/health_datasource.dart';
import 'package:doublefeel_flutter/data/local/user_account_storage.dart';
import 'package:doublefeel_flutter/data/local/user_preferences_storage.dart';
import 'package:doublefeel_flutter/data/models/friend/friend_models.dart';
import 'package:doublefeel_flutter/data/models/health/health_v2_models.dart';
import 'package:doublefeel_flutter/data/models/local/user_preferences.dart';
import 'package:doublefeel_flutter/data/models/pay/pay_models.dart';
import 'package:doublefeel_flutter/l10n/l10n_extensions.dart';
import 'package:doublefeel_flutter/core/platform/pigeon_api_facade.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:intl/intl.dart';
import 'package:permission_handler/permission_handler.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 with WidgetsBindingObserver {
  TodayController(
    this._payApi,
    this._vipApi,
    this._healthApi,
    this._friendApi,
    this._userStateService, {
    FriendItem? friendInfo, // null = 自己,非 null = 好友
  }) : _initialFriendInfo = friendInfo;

  final PayApi _payApi;
  final VipApi _vipApi;
  final HealthDataSource _healthApi;
  final FriendApi _friendApi;
  final UserStateService _userStateService;
  final AppHealthKitHostApi _hostApi = AppHealthKitHostApi();
  final HealthRawDataCoreService _healthRawDataCoreService =
      Get.find<HealthRawDataCoreService>();

  /// 好友的信息;null 表示查看自己的数据,非 null 表示查看好友的数据。
  final FriendItem? _initialFriendInfo;
  final targetFriendInfo = Rxn<FriendItem>();

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

  UserStateService get userStateService => _userStateService;

  Rx<DateTime> firstSelectableDay = DateTime(
          DateTime.now().year, DateTime.now().month - 6, DateTime.now().day)
      .obs;
  Rx<DateTime> lastSelectableDay = DateUtils.dateOnly(DateTime.now()).obs;
  final selectedDate = DateTime.now().obs;
  final focusedDay = DateTime.now().obs;
  final scrollOffset = 0.0.obs;
  final scrollController = ScrollController();

  final isLoadingToday = false.obs;
  final showHealthDataAuthCardStatus = 1.obs;
  final stressSubtitle = ''.obs;
  bool _isFirstLoad = true;
  bool _isHandlingHealthAuthorizationTap = false;

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

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

  Future<void> dismissPartnerAdBanner() async {
    final userId =
        Get.find<UserPreferencesStorage>().preferences.value.meUserInfo?.id ??
            0;
    await Get.find<UserAccountStorage>()
        .saveLastAddFriendBannerShowTime(userId);
    showPartnerAdBanner.value = false;
  }

  final environmentConfig = Get.find<AppEnvironmentConfig>();

  // ── HRV 趋势图 ────────────────────────────
  final hrvChartData = <V2HrvTrendItem>[].obs;
  final stressChartData = <V2RealtimeStressItem>[].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>();
  final v2ActivityTarget = Rxn<V2ActivityTarget>();

  HealthAuthorizationStatus _currentStatus =
      HealthAuthorizationStatus.notDetermined;

  @override
  void onReady() {
    super.onReady();
    ta.track(
      'enter_doublefeel_today_status',
      properties: {'user_role': isFriend ? '好友的' : '我的'},
    );
  }

  @override
  void onInit() {
    super.onInit();
    WidgetsBinding.instance.addObserver(this);

    targetFriendInfo.value = _initialFriendInfo;
    final today = DateUtils.dateOnly(DateTime.now());
    firstSelectableDay.value = DateUtils.dateOnly(
      DateTime(today.year, today.month - 6, today.day),
    );
    selectedDate.value = today;
    focusedDay.value = today;

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

    unawaited(loadDataForDate(today));

    // _checkHealthAuthStatus();

    checkAddFriendVisible();
    checkHrvAdBannerVisible();
    checkHealthDataAuthCardVisible(shouldCaculateAndUpload: true);
    checkNotificationAuthorizationBannerVisible();
    checkNotificationCardVisible();
    if (!Get.find<UserStateService>().isVip) {
      getProductList();
    }
    _healthApi.getHealthDataEverUploaded().then((data) {
      switch (data) {
        case AppSuccess(:final data):
          if (data.startTime != null && data.startTime! > 0) {
            final firstDayTime = DateUtils.dateOnly(
              DateTime.fromMillisecondsSinceEpoch(data.startTime! * 1000),
            );
            if (firstDayTime.isBefore(firstSelectableDay.value)) {
              firstSelectableDay.value = firstDayTime;
            }
          }
        case AppFailure():
      }
    });
  }

  Future<void> checkHrvAdBannerVisible() async {
    if (isFriend) {
      showHrvAdBanner.value = false;
    } else {
      try {
        AppWearEngineHostApi()
            .hasInstalledWatchSurface()
            .then((hasInstalledWatchSurface) {
          showHrvAdBanner.value = !hasInstalledWatchSurface;
        });
      } on Exception catch (e) {
        AppLogger.e(e);
      }
    }
  }

  Future<void> checkNotificationAuthorizationBannerVisible() async {
    if (isFriend) {
      showNotificationAuthorizationBanner.value = false;
    } else {
      try {
        final status = await _platformHostApi.getApnsAuthStatus();
        if (status == 1) {
          showNotificationAuthorizationBanner.value = false;
        } else {
          showNotificationAuthorizationBanner.value = true;
        }

        Permission.notification.status.then((status) {
          if (status.isGranted) {
            showNotificationAuthorizationBanner.value = false;
          } else {
            showNotificationAuthorizationBanner.value = true;
          }
        });
      } on Exception catch (e) {
        AppLogger.e(e);
      }
    }
  }

  void checkAddFriendVisible() {
    if (isFriend) {
      showPartnerAdBanner.value = false;
    } else {
      _refreshFriendList(onFriendListUpdated: () {
        if (friendsList.isNotEmpty || friendsList.length >= friendsListLimit) {
          showPartnerAdBanner.value = false;
          return;
        }
        // 关闭后 3 天内不再显示
        final userId = Get.find<UserPreferencesStorage>()
                .preferences
                .value
                .meUserInfo
                ?.id ??
            0;
        final lastShowTime = Get.find<UserAccountStorage>()
            .getLastAddFriendBannerShowTime(userId);
        if (lastShowTime != null) {
          final diff = DateTime.now()
              .difference(DateTime.fromMillisecondsSinceEpoch(lastShowTime));
          if (diff.inDays < 3) {
            showPartnerAdBanner.value = false;
            return;
          }
        }
        showPartnerAdBanner.value = true;
      });
    }
  }

  void changeDate(DateTime date, {DateTime? focused}) {
    final normalizedDate = _clampDate(date);
    if (!DateUtils.isSameDay(date, lastSelectableDay.value) &&
        !_userStateService.isVip) {
      toPremiumPage('今日-查看非当日数据');
      return;
    }
    selectedDate.value = normalizedDate;
    focusedDay.value = _clampDate(focused ?? normalizedDate);
  }

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

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

  Future<bool> _checkHealthAuthStatus(
      {bool isPullToRefresh = false,
      bool shouldCaculateAndUpload = false}) async {
    final result = await _hostApi.checkHealthAppAuthorization();
    _currentStatus = result.status;
    _refreshHealthDataAuthCardStatus(status: _currentStatus);
    if (_currentStatus != HealthAuthorizationStatus.authorized) {
      return false;
    }
    if (!shouldCaculateAndUpload) {
      return false;
    }
    return _performCaculateAndUpload(isPullToRefresh: isPullToRefresh);
  }

  Future<bool> _performCaculateAndUpload({
    bool isPullToRefresh = false,
  }) {
    _performHealthDataUpload();
    return _calculateHealthDataWithoutLoading(
      uploaded: () async {
        _refreshHealthDataAuthCardStatus(
            status: HealthAuthorizationStatus.authorized);
      },
      isPullToRefresh: isPullToRefresh,
    );
  }

  Future<void> _showHuaweiHealthRegistrationDialog() async {
    final confirmed = await HuaweiHealthRegistrationDialog.show();
    if (confirmed) {
      await _platformHostApi.nativeHandleUrl(
        'huaweischeme://healthapp/home/main',
      );
    }
  }

  Future<bool> requestHealthAuthorization(
      {bool isFromNoPermissionPage = false}) async {
    if (isOhos()) {
      try {
        await _checkHealthAuthStatus();
        AppLogger.d("checkHealthAppAuthorization : $_currentStatus");
        if (_currentStatus == HealthAuthorizationStatus.authorized) {
          _refreshHealthDataAuthCardStatus(
              status: HealthAuthorizationStatus.authorized);
          if (isFromNoPermissionPage) {
            Get.back();
          }
          return true;
        } else if (_currentStatus ==
            HealthAuthorizationStatus.activationRequired) {
          await _showHuaweiHealthRegistrationDialog();
          return false;
        } else {
          final result = await _hostApi.requestHealthClientAuthorization();
          AppLogger.d("requestHealthClientAuthorization : $result");
          if (result == HealthAuthorizationStatus.activationRequired) {
            await _showHuaweiHealthRegistrationDialog();
            // Registration does not grant access to health data yet.
            return false;
          }
          if (result == HealthAuthorizationStatus.authorized) {
            _currentStatus = HealthAuthorizationStatus.authorized;
            _refreshHealthDataAuthCardStatus(
                status: HealthAuthorizationStatus.authorized);
            // await LoadingService.instance.run(() async {
            _performCaculateAndUpload();
            // });
            // result.status = 1;
            // AppToast.show('刷新完成');
            if (isFromNoPermissionPage) {
              Get.back();
            }
            return true;
          } else {
            // Get.to(NoHealthDataPage(
            //   onRefresh: _performDataUpload,
            // ));
          }
          return false;
        }
      } catch (e) {
        AppToast.show(e.toString());
      }
    } else {
      try {
        await _checkHealthAuthStatus();
        AppLogger.d("checkHealthAppAuthorization : $_currentStatus");
        if (_currentStatus == HealthAuthorizationStatus.notDetermined) {
          final result = await _hostApi.requestHealthClientAuthorization();
          AppLogger.d("requestHealthClientAuthorization : $result");
          if (result == HealthAuthorizationStatus.authorized) {
            _currentStatus = HealthAuthorizationStatus.authorized;
            _refreshHealthDataAuthCardStatus(
                status: HealthAuthorizationStatus.authorized);
            // await LoadingService.instance.run(() async {
            _performCaculateAndUpload();
            // });
            // result.status = 1;
            // AppToast.show('刷新完成');
            if (isFromNoPermissionPage) {
              Get.back();
            }
            return true;
          } else {
            // Get.to(NoHealthDataPage(
            //   onRefresh: _performDataUpload,
            // ));
          }
          return false;
        } else if (_currentStatus == HealthAuthorizationStatus.authorized) {
          _refreshHealthDataAuthCardStatus(
              status: HealthAuthorizationStatus.authorized);
          if (isFromNoPermissionPage) {
            Get.back();
          }
          return true;
        }
        // 打开苹果健康
        _platformHostApi.nativeHandleUrl('x-apple-health://');
      } catch (e) {
        AppToast.show(e.toString());
      }
    }
    return false;
  }

  Future<void> onAuthorizeTap() async {
    if (_isHandlingHealthAuthorizationTap) {
      AppLogger.d('TodayController.onAuthorizeTap ignored: handling');
      return;
    }
    _isHandlingHealthAuthorizationTap = true;
    ta.track('click_doublefeel_today_status', properties: {'ita': '授权访问健康数据'});
    try {
      if (isOhos()) {
        if (_currentStatus != HealthAuthorizationStatus.authorized) {
          final success = await requestHealthAuthorization();
          if (success) {
            _currentStatus = HealthAuthorizationStatus.authorized;
            _refreshHealthDataAuthCardStatus(
                status: HealthAuthorizationStatus.authorized);
          }
        } else {
          if (hrvChartData.isNotEmpty) {
            return;
          }
          await Get.to(() => NoHealthDataPage(
                onRefresh: () {
                  refreshTab();
                  Future.delayed(const Duration(milliseconds: 800), () {
                    AppToast.show(l10n.refreshComplete);
                  });
                },
                onHelp: () {
                  if (environmentConfig.region.value == AppRegion.china) {
                    Get.toNamed(Routes.HELP);
                  } else {
                    final userId = Get.find<UserPreferencesStorage>()
                            .preferences
                            .value
                            .meUserInfo
                            ?.id ??
                        0;
                    sendFeedbackEmail(
                      userId: userId.toString(),
                      pageName: 'No heart rate data available page',
                    );
                  }
                },
              ));
          checkHealthDataAuthCardVisible();
        }
      } else {
        if (_currentStatus == HealthAuthorizationStatus.authorized &&
            hrvChartData.isNotEmpty) {
          return;
        } else if (_currentStatus == HealthAuthorizationStatus.notDetermined) {
          final success = await requestHealthAuthorization();
          if (success) {
            _currentStatus = HealthAuthorizationStatus.authorized;
            _refreshHealthDataAuthCardStatus(
                status: HealthAuthorizationStatus.authorized);
          }
        } else {
          await Get.to(() => NoHealthDataPage(
                onRefresh: () {
                  refreshTab();
                  Future.delayed(const Duration(milliseconds: 800), () {
                    AppToast.show(l10n.refreshComplete);
                  });
                },
                onHelp: () {
                  if (environmentConfig.region.value == AppRegion.china) {
                    Get.toNamed(Routes.HELP);
                  } else {
                    final userId = Get.find<UserPreferencesStorage>()
                            .preferences
                            .value
                            .meUserInfo
                            ?.id ??
                        0;
                    sendFeedbackEmail(
                      userId: userId.toString(),
                      pageName: 'No heart rate data available page',
                    );
                  }
                },
              ));
          checkHealthDataAuthCardVisible();
        }
      }
    } finally {
      _isHandlingHealthAuthorizationTap = false;
    }
  }

  _refreshHealthDataAuthCardStatus(
      {required HealthAuthorizationStatus status}) {
    if (isFriend) {
      showHealthDataAuthCardStatus.value = 1;
      return;
    }
    if (status != HealthAuthorizationStatus.authorized) {
      showHealthDataAuthCardStatus.value = status.code;
    }
    showHealthDataAuthCardStatus.value =
        hrvChartData.isEmpty ? -1 : status.code;
  }

  Future<void> checkHealthDataAuthCardVisible(
      {bool isPullToRefresh = false,
      bool shouldCaculateAndUpload = false}) async {
    final firstTime = DateUtils.dateOnly(
      DateTime(lastSelectableDay.value.year, lastSelectableDay.value.month - 6,
          lastSelectableDay.value.day),
    );
    if (isFriend) {
      showHealthDataAuthCardStatus.value = 1;
      firstSelectableDay.value = firstTime;
    } else {
      try {
        final didCalculateAndReload = await _checkHealthAuthStatus(
            isPullToRefresh: isPullToRefresh,
            shouldCaculateAndUpload: shouldCaculateAndUpload);
        ta.setSuperProperties({
          'health_data_permission':
              _currentStatus == HealthAuthorizationStatus.authorized ? 1 : 0,
        });
        // When a pull-to-refresh asks OHOS to recalculate health data,
        // _calculateHealthDataWithoutLoading already reloads the page after
        // the calculation. Starting another load here caused a second visible
        // refresh shortly after the first one completed.
        if (!didCalculateAndReload) {
          await loadDataForDate(
            selectedDate.value,
            isPullToRefresh: isPullToRefresh,
          );
        }
      } catch (error, stackTrace) {
        AppLogger.e(
          'TodayController.checkHealthDataAuthCardVisible failed',
          error,
          stackTrace,
        );
      }
    }
  }

  Future<void> checkUploadedStatus(
      DateTime firstTime, AppHealthAuthorization result) async {
    bool hasUploaded = false;
    switch (await _healthApi.getHealthDataEverUploaded()) {
      case AppSuccess(:final data):
        hasUploaded = data.flag ?? false;
        if (hasUploaded && data.startTime != null && data.startTime! > 0) {
          final firstDayTime = DateUtils.dateOnly(
            DateTime.fromMillisecondsSinceEpoch(data.startTime! * 1000),
          );
          if (firstDayTime.isBefore(firstTime)) {
            firstSelectableDay.value = firstDayTime;
          }
        }
      case AppFailure():
    }
    _refreshHealthDataAuthCardStatus(status: result.status);
  }

  Future<bool> _calculateHealthDataWithoutLoading(
      {Future<void> Function()? uploaded,
      bool isPullToRefresh = false,
      bool refreshAfterComplete = false}) async {
    try {
      await _healthRawDataCoreService.startCoreCaculate();
      await loadDataForDate(
        selectedDate.value,
        isPullToRefresh: isPullToRefresh,
      );
      await uploaded?.call();
      if (refreshAfterComplete) {
        await loadDataForDate(selectedDate.value);
      }
      return true;
    } catch (error, stackTrace) {
      AppLogger.e('Apple Health calculate failed', error, stackTrace);
      return false;
    }
  }

  void _performHealthDataUpload() {
    unawaited(
      _healthRawDataCoreService
          .performHealthDataUpload()
          .catchError((Object error, StackTrace stackTrace) {
        AppLogger.e('Apple Health raw upload failed', error, stackTrace);
        return false;
      }),
    );
  }

  Future<void> checkNotificationCardVisible() async {
    try {
      final status = await _platformHostApi.getApnsAuthStatus();

      ta.setSuperProperties({'notification_permission': status == 1 ? 1 : 0});
      // if (status.isGranted) {
      //   return;
      // }

      // if (status.isPermanentlyDenied) {
      //   // await openAppSettings();
      //   return;
      // }

      // final result = await Permission.notification.request();
    } catch (error) {
      AppLogger.e('Notification authorization failed: $error');
    }
  }

  Future<void> _refreshHealthDataForDate(DateTime date) async {
    _clearRealTimeData();
    final intDate = int.parse(DateFormat('yyyyMMdd').format(date));
    final isToday = DateUtils.isSameDay(date, lastSelectableDay.value);
    stressSubtitle.value = environmentConfig.region.value == AppRegion.china
        ? 'Hi, ${isFriend ? 'Ta' : ''}${isToday ? l10n.overallStressLevelToday : l10n.stressLevelsOnThatDay}'
        : isFriend
            ? isToday
                ? l10n.stressLevelsToday
                : l10n.stressLevelsOnThatDay
            : 'Hi, ${l10n.overallStressLevelToday}';
    switch (await _healthApi.getV2HealthData(friendUserId, intDate)) {
      case AppSuccess(:final data):
        v2HealthData.value = data;
      case AppFailure():
        v2HealthData.value = null;
    }

    switch (await _healthApi.getV2HrvTrend(friendUserId, intDate)) {
      case AppSuccess(:final data):
        v2HrvTrend.value = data;
        hrvChartData.assignAll(data.list ?? []);
      case AppFailure():
        v2HrvTrend.value = null;
        hrvChartData.clear();
    }

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

    switch (await _healthApi.getV2StressScore(friendUserId, intDate)) {
      case AppSuccess(:final data):
        {
          if (hrvChartData.isNotEmpty) {
            v2StressScore.value = data;
          } else {
            v2StressScore.value = V2StressScore(state: 0);
          }
        }
      case AppFailure():
        v2StressScore.value = null;
    }

    switch (await _healthApi.getV2RealtimeStress(friendUserId, intDate)) {
      case AppSuccess(:final data):
        if (hrvChartData.isNotEmpty) {
          stressChartData.assignAll(data.list ?? []);
        } else {
          stressChartData.clear();
        }
      case AppFailure():
        stressChartData.clear();
    }
    switch (await _healthApi.getV2ActivityTarget(friendUserId, intDate)) {
      case AppSuccess(:final data):
        v2ActivityTarget.value = data;
      case AppFailure():
        v2ActivityTarget.value = null;
    }
  }

  void _clearRealTimeData() {
    v2HrvTrend.value = null;
    hrvChartData.clear();
    stressChartData.clear();
    hrvAnnotations.clear();

    v2HealthData.value = null;
    v2ActivityTarget.value = null;
    // v2StressScore.value = null;
  }

  toTrendHrvPage() {
    if (isFriend) {
      Get.toNamed(
        Routes.FRIEND_TREND,
        arguments: getFriendTrendArguments(TrendType.hrv),
      );
    } else {
      Get.find<HomeController>().openTrend(TrendType.hrv,
          period: ReportPeriod.week, date: selectedDate.value);
    }
  }

  toTrendSleepPage() {
    if (isFriend) {
      Get.toNamed(
        Routes.FRIEND_TREND,
        arguments: getFriendTrendArguments(TrendType.sleep),
      );
    } else {
      Get.find<HomeController>().openTrend(TrendType.sleep,
          period: ReportPeriod.day, date: selectedDate.value);
    }
  }

  toTrendActivityPage() {
    if (isFriend) {
      Get.toNamed(
        Routes.FRIEND_TREND,
        arguments: getFriendTrendArguments(TrendType.activity),
      );
    } else {
      Get.find<HomeController>().openTrend(TrendType.activity,
          period: ReportPeriod.day, date: selectedDate.value);
    }
  }

  FriendTrendArguments getFriendTrendArguments(TrendType type) {
    return FriendTrendArguments(
        friendItem: targetFriendInfo.value,
        initialTypeIndex: type.tabIndex,
        initialDate: selectedDate.value);
  }

  void selectFriend(FriendItem friendInfo) {
    if (friendInfo.friendUserId != targetFriendInfo.value?.friendUserId) {
      targetFriendInfo.value = friendInfo;
      _clearRealTimeData();
      loadDataForDate(selectedDate.value);
    }
  }

  showFriendListBottomSheet() async {
    _refreshFriendList();

    Get.bottomSheet(
      DraggableScrollableSheet(
        maxChildSize: 0.6,
        initialChildSize: 0.6,
        expand: false,
        snap: true,
        builder: (context, scrollController) {
          return FriendSelectBottomSheet(
              scrollController: scrollController, controller: this);
        },
      ),
      barrierColor: Colors.black.withValues(alpha: 0.7),
      enableDrag: true,
      isScrollControlled: true,
      persistent: false,
    );
  }

  void _refreshFriendList({VoidCallback? onFriendListUpdated}) {
    _friendApi.friendList(false).then(
      (res) {
        switch (res) {
          case AppSuccess(:final data):
            friendsList.assignAll(data.list);
            friendsListLimit = data.limit ?? 10;
            onFriendListUpdated?.call();
          case AppFailure():
        }
      },
    );
  }

  RxList<FriendItem> friendsList = RxList.empty();
  int friendsListLimit = 10;

  Future<void> toPremiumPage(String channelType) async {
    await Get.toNamed(
      Routes.PURCHASE,
      arguments: {IntentKeys.channelType: channelType},
    );
    final vipResult = await _vipApi.getVipInfo();
    if (vipResult case AppSuccess(data: final vip)) {
      try {
        final vipPrefs = UserPreferencesVipInfo.fromVipInfo(vip);
        await Get.find<UserPreferencesStorage>().updateVipInfo(vipPrefs);
      } on Exception catch (error, stackTrace) {
        AppLogger.e('Update VIP info failed', error, stackTrace);
      }
    }
  }

  Future<void> toPremiumDiscoutPage(String s) async {
    await Get.toNamed(Routes.MEMBERSHIP_OFFER, arguments: {'channel_type': s});
    final vipResult = await _vipApi.getVipInfo();
    if (vipResult case AppSuccess(data: final vip)) {
      try {
        final vipPrefs = UserPreferencesVipInfo.fromVipInfo(vip);
        await Get.find<UserPreferencesStorage>().updateVipInfo(vipPrefs);
      } on Exception catch (error, stackTrace) {
        AppLogger.e('Update VIP info failed', error, stackTrace);
      }
    }
  }

  final yearlyProduct = Rxn<PayProduct>();
  final yearlyProductAppleInfo = Rxn<AppleProductInfo>();
  final AppPlatformHostApi _platformHostApi = AppPlatformHostApi();

  Future<void> getProductList() async {
    final result = await _payApi.getProductList();
    if (result is! AppSuccess<PayProductListResponse>) return;

    final products = isIOS()
        ? (result.data.productList ?? const <PayProduct>[])
            .where((product) => _nonEmpty(product.appleId) != null)
            .toList()
        : (result.data.productList ?? const <PayProduct>[]);
    yearlyProduct.value =
        products.firstWhereOrNull((p) => p.content?.isDiscountOffer == 1);
    // AppLogger.e(yearlyProduct);
    if (yearlyProduct.value != null) {
      final appleProductId = _nonEmpty(yearlyProduct.value!.appleId);
      if (appleProductId == null) return;

      yearlyProductAppleInfo.value = await _requestAppleProductInfo(
          productId: appleProductId,
          baseUnit: yearlyProduct.value!.content?.baseUnit() ?? 1);
    }
  }

  Future<AppleProductInfo?> _requestAppleProductInfo({
    required String productId,
    required int baseUnit,
  }) async {
    try {
      return await _platformHostApi.requestAppleProductInfo(
        productId,
        baseUnit,
      );
    } catch (_) {
      return null;
    }
  }

  String? _nonEmpty(String? value) {
    final trimmed = value?.trim();
    if (trimmed == null || trimmed.isEmpty) return null;
    return trimmed;
  }

  String originDisplayPrice() {
    if (isIOS()) {
      final appleInfo = yearlyProductAppleInfo.value;
      if (appleInfo == null) return '';
      final actual =
          appleInfo.price > 0 ? appleInfo.price : appleInfo.originPrice;
      final inflated = actual / 100.0 * 1.2;
      // 保留两位小数,单位与 currencyCode 一致
      return '${appleInfo.currencyCode}${inflated.toStringAsFixed(2)}';
    } else if (isOhos()) {
      final actual = yearlyProduct.value?.price ?? 0;
      final inflated = actual / 100.0 * 1.2;
      // 保留两位小数,单位与 currencyCode 一致
      return ${inflated.toStringAsFixed(2)}';
    } else {
      return '';
    }
  }

  String displayPrice() {
    if (isIOS()) {
      final appleInfo = yearlyProductAppleInfo.value;
      if (appleInfo == null) return '';
      final price = appleInfo.price;
      if (price > 0) {
        final priceDescription = appleInfo.priceDescription.trim();
        if (priceDescription.isNotEmpty) {
          return priceDescription;
        }
      }
      return appleInfo.originPriceDescription;
    } else if (isOhos()) {
      final actual = (yearlyProduct.value?.price ?? 0) / 100.0;
      return ${actual.toStringAsFixed(2)}';
    } else {
      return '';
    }
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    super.didChangeAppLifecycleState(state);

    if (state == AppLifecycleState.resumed && _userStateService.isLoggedIn) {
      var today = DateUtils.dateOnly(DateTime.now());
      lastSelectableDay.value = today;
      changeDate(today);
      checkAddFriendVisible();
      checkHrvAdBannerVisible();
      checkHealthDataAuthCardVisible(shouldCaculateAndUpload: true);
      checkNotificationAuthorizationBannerVisible();
      _performHealthDataUpload();
      // unawaited(loadDataForDate(selectedDate.value));
    }
  }

  @override
  void onClose() {
    WidgetsBinding.instance.removeObserver(this);
    super.onClose();
  }

  Future<void> refreshTab({bool isPullToRefresh = false}) async {
    if (_isFirstLoad) {
      _isFirstLoad = false;
      return;
    }
    // var today = DateUtils.dateOnly(DateTime.now());
    // lastSelectableDay.value = today;
    // changeDate(today);
    checkAddFriendVisible();
    checkHrvAdBannerVisible();
    final isSelectedToday = DateUtils.isSameDay(
      DateUtils.dateOnly(selectedDate.value),
      DateUtils.dateOnly(DateTime.now()),
    );
    await checkHealthDataAuthCardVisible(
      isPullToRefresh: isPullToRefresh,
      shouldCaculateAndUpload: isOhos() && isSelectedToday,
    );
    checkNotificationAuthorizationBannerVisible();
    // await loadDataForDate(selectedDate.value);
  }

  Future<void> requestNotificationAuthorization() async {
    try {
      final status = await _platformHostApi.getApnsAuthStatus();

      if (status == 1) {
        // 已授权,无需再请求
        return;
      }

      if (status == -1) {
        // 用户永久拒绝(Android),引导去设置
        await openAppSettings();
        return;
      }

      // 未决定 → 弹出系统授权弹窗
      await _platformHostApi.requestNotificationAuth();
      // AppLogger.d(result.isGranted
      //     ? 'Notification authorization granted'
      //     : 'Notification authorization skipped');
    } catch (error) {
      AppLogger.e('Notification authorization failed: $error');
    }
  }
}