import 'dart:core'; import 'package:domain/entity/response/hotel_info_entity.dart'; import 'package:domain/repository/auth_repository.dart'; import 'package:flutter_smart_dialog/flutter_smart_dialog.dart'; import 'package:get/get.dart'; import 'package:plugin_platform/engine/sp/sp_util.dart'; import 'package:shared/utils/event_bus.dart'; import 'package:shared/utils/log_utils.dart'; import 'package:shared/utils/util.dart'; import '../constants/app_constant.dart'; /// 用户相关的单例服务,保存了Token,UserProfile等信息 class UserService extends GetxService { static UserService get to => Get.find(); final AuthRepository _authRepository; UserService(this._authRepository); //用户登录Token String? token; //用户是否已经登录 - 可变字段 Rx haslogin = false.obs; //用户详情信息 - 可变字段 Rx hotelInfo = HotelInfoEntity().obs; //极光推送的 registrationId - 可变字段 RxString registrationId = ''.obs; //当前用户的未读消息数量 RxInt unreadNotificationsCount = 0.obs; bool get hasToken => token?.isNotEmpty ?? false; bool get isLogin => haslogin.value; HotelInfoEntity get getHotelInfo => hotelInfo.value; String get getRegistrationId => registrationId.value; int get getUnreadNotificationsCount => unreadNotificationsCount.value; /// 设置全局的Token,同时更新 hasLogin 的值,赋值时机如下 /* 1. 在登录或注册成功的时候赋值 2. 在main.dart中初始化的时候查询是否有Token,如果有的话需要赋值 3. 退出登录的时候需要赋值 */ void setToken(String? token) { this.token = token; if (Utils.isEmpty(token)) { haslogin.value = false; SPUtil.remove(AppConstant.storageToken); } else { haslogin.value = true; SPUtil.putString(AppConstant.storageToken, token!); } Log.d('UserService =========> 设置Token为:$token'); } // /// 请求接口获取用户详情 // Future fetchHotelInfo() async { // //获取到数据 // var result = await _authRepository.fetchHotelInfo(); // // //处理数据 // if (result.isSuccess) { // final userProfile = result.data; // if (userProfile != null) { // //赋值给Rx对象 // this.hotelInfo.value = userProfile; // bus.emit(AppConstant.eventHotelInfoRefreshFinish, true); // // return userProfile; // } else { // bus.emit(AppConstant.eventHotelInfoRefreshFinish, true); // return null; // } // } else { // SmartDialog.showToast(result.errorMsg ?? ''); // bus.emit(AppConstant.eventHotelInfoRefreshFinish, true); // return null; // } // // } /// 处理退出登录之后的数据清除 void handleLogoutParams() { SPUtil.remove(AppConstant.storageToken); haslogin.value = false; hotelInfo.value = HotelInfoEntity(); } @override void onInit() { super.onInit(); String? token = SPUtil.getString(AppConstant.storageToken); Log.d('UserService - 查询SP token:$token 并赋值' ); setToken(token); } }