friend_trend_controller.dart 2.32 KB
import 'package:doublefeel_flutter/core/constants/event_const.dart';
import 'package:doublefeel_flutter/data/models/friend/friend_models.dart';
import 'package:get/get.dart';

import '../../../../core/network/api/click_event_api.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';

class FriendTrendArguments {
  const FriendTrendArguments({
    required this.friendItem,
    this.initialDate,
    this.initialPeriod,
    this.initialTypeIndex = 0,
  });

  final FriendItem? friendItem;
  final DateTime? initialDate;
  final ReportPeriod? initialPeriod;
  final int initialTypeIndex;
}

class FriendTrendController extends GetxController with HealthTrendControl {
  FriendTrendController({
    required this.friendItem,
    DateTime? initialDate,
    ReportPeriod? initialPeriod,
    int initialTypeIndex = 0,
  }) {
    changeType(initialTypeIndex);
    if (initialPeriod != null) changePeriod(initialPeriod);
    if (initialDate != null) changeDate(initialDate);
  }

  final FriendItem? friendItem;
  bool _isPageReady = false;

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

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

  @override
  void onReady() {
    super.onReady();
    _isPageReady = true;
    _trackEnterPage();
  }

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

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

  void _trackViewFriendSleepStatsIfNeeded() {
    if (selectedTypeIndex.value != 2) return;
    if (!Get.isRegistered<ClickEventApi>()) return;
    Get.find<ClickEventApi>().postClickEvent(EventConst.viewFriendSleepStats);
  }
}