import 'package:domain/repository/auth_repository.dart';
import 'package:plugin_basic/constants/app_constant.dart';
import 'package:plugin_basic/provider/user_config/user_config_service.dart';
import 'package:plugin_platform/engine/toast/toast_engine.dart';
import 'package:plugin_platform/http/dio/dio_cancelable_mixin.dart';
import 'package:riverpod_annotation/riverpod_annotation.dart';
import 'package:shared/utils/event_bus.dart';
import 'package:shared/utils/log_utils.dart';
import 'main_state.dart';
import 'package:plugin_basic/fcm/fcm_utils.dart';

part 'main_view_model.g.dart';

@riverpod
class MainViewModel extends _$MainViewModel with DioCancelableMixin {
  late final AuthRepository _authRepository;

  @override
  MainState build() {
    _authRepository = ref.read(authRepositoryProvider);
    final state = MainState();

    registerEventBus();
    registerCancellation(callback: () {
      unregisterEventBus();
    });

    _registerFCM();
    return state;
  }

  /// 获取用户信息
  void _fetchUserInfo() {
    UserConfigService.getInstance().refreshUserInfo();
  }

  // EventBus 的事件接收
  Subscription? subscribe;

  void registerEventBus() {
    subscribe = bus.on(AppConstant.eventProfileRefresh, (arg) {
      Log.d("收到消息刷新用户信息");
      _fetchUserInfo();
    });
  }

  void unregisterEventBus() {
    bus.off(AppConstant.eventProfileRefresh, subscribe);
  }

  void _registerFCM() {
    //获取token,并初始化监听
    FcmUtils().initNotifications(onToken: (fcmToken) {
      Log.d("准备注册FCM Token :$fcmToken");
      _doRegisterFCM(fcmToken);
    });
  }

  /// 调用接口注册FCM
  void _doRegisterFCM(String fcmToken) async {
    final result = await _authRepository.registerFCMToken(fcmToken: fcmToken, cancelToken: cancelToken);

    //请求成功去首页
    if (result.isSuccess) {
      Log.d("注册FCM Token 成功！");
    } else {
      ToastEngine.show(result.errorMsg ?? "UnKnow Error");
    }
  }
}
