import 'package:plugin_basic/constants/app_constant.dart';
import 'package:plugin_basic/provider/user_config/user_config_service.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';

part 'main_view_model.g.dart';

@riverpod
class MainViewModel extends _$MainViewModel with DioCancelableMixin {
  @override
  MainState build() {
    final state = MainState();

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

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

}
