trend_controller.dart 1.94 KB
import 'package:get/get.dart';

import '../../../health_trend/controllers/health_trend_analytics.dart';
import '../../../health_trend/controllers/health_trend_control.dart';
import '../../../report_common/models/health_report_query.dart';
import '../../../report_common/models/report_period.dart';

enum TrendType {
  hrv,
  activity,
  sleep;

  int get tabIndex => index;
}

/// 趋势页顶层 Controller,仅负责:
/// 顶层 HRV / 活动 / 睡眠 类型切换 (selectedTypeIndex)
class TrendController extends GetxController with HealthTrendControl {
  bool _isPageVisible = false;

  // 当前查看的用户。null 表示查看自己;非 null 表示查看指定用户。
  final targetUserId = RxnInt();

  HealthReportQuery get query => HealthReportQuery(
        targetUserId: targetUserId.value,
        period: selectedPeriod.value,
        date: selectedDate.value,
      );

  HealthReportQuery queryForType(int typeIndex) => HealthReportQuery(
        targetUserId: targetUserId.value,
        period: periodForType(typeIndex),
        date: dateForType(typeIndex),
      );

  @override
  void changeType(int index) {
    final previousIndex = selectedTypeIndex.value;
    super.changeType(index);
    if (_isPageVisible && selectedTypeIndex.value != previousIndex) {
      _trackEnterPage();
    }
  }

  void selectType(TrendType type, {DateTime? date, ReportPeriod? period}) {
    changeType(type.tabIndex);
    if (period != null) {
      changePeriod(period);
    }
    if (date != null) {
      changeDate(date);
    }
  }

  void changeTargetUser(int? userId) {
    if (userId == targetUserId.value) return;
    targetUserId.value = userId;
  }

  void markPageVisible() {
    if (_isPageVisible) return;
    _isPageVisible = true;
    _trackEnterPage();
  }

  void markPageHidden() {
    _isPageVisible = false;
  }

  void _trackEnterPage() {
    HealthTrendAnalytics.trackEnterPage(
      selectedTypeIndex.value,
      userRole: '我的',
    );
  }
}