import 'package:chat/models/user_info_model.dart';
import 'package:chat/providers/auth_provider.dart';
import 'package:chat/routes/auth_routes.dart';
import 'package:chat/services/tim/apply_service.dart';
import 'package:chat/services/tim/block_service.dart';
import 'package:chat/services/tim/conversation_service.dart';
import 'package:chat/services/tim/friend_service.dart';
import 'package:chat/services/tim/group_service.dart';
import 'package:chat/services/tim/message_service.dart';
import 'package:chat/services/tim_service.dart';
import 'package:chat/utils/hd_wallet.dart';
import 'package:get/get.dart';
import 'package:get_storage/get_storage.dart';
import 'package:tencent_im_sdk_plugin/tencent_im_sdk_plugin.dart';

class AuthService extends GetxService {
  static AuthService get to => Get.find<AuthService>();

  final _box = GetStorage();

  /// 供外部使用的，判断是否登录的状态
  get isUserLogin => isLogin.value;

  /// 登录状态记录,可监听的，这样ever才能监听到
  final RxBool isLogin = false.obs;

  /// 供请求时调用，载入内存，是为了每次使用的时候，不需要从磁盘获取
  late String userId = '';
  late String userSig = '';
  late String userToken = '';

  /// 获取存储的token，这个可以做到持久化存储
  String get _userId => _box.read('userId') ?? '';
  String get _userSig => _box.read('userSig') ?? '';
  String get _userToken => _box.read('userToken') ?? '';
  Map<String, dynamic> get _userInfo => _box.read('userInfo') ?? {};
  String get mnemonic => _box.read('mnemonic') ?? '';

  /// 用户信息，这个数据，在更新用户资料的时候，也应该更新
  Rx<UserInfoModel> userInfo = UserInfoModel.empty().obs;

  @override
  void onInit() {
    super.onInit();

    if (_userToken.isNotEmpty) {
      isLogin.value = true;
      userSig = _userSig;
      userId = _userId;
      userToken = _userToken;
      userInfo.value = UserInfoModel.fromJson(_userInfo);
    }
  }

  Future<bool> login(String mnemonic) async {
    String? address = HDWallet.mnemonicToAddress(mnemonic);

    if (address == null) {
      return false;
    }

    var result = await AuthProvider.login(address);

    if (result != null) {
      _box.write('mnemonic', mnemonic);
      _box.write('userId', result.userID);
      _box.write('userSig', result.userSig);
      _box.write('userToken', result.userToken);
      _box.write('userInfo', result.userInfo.toJson());

      userId = result.userID;
      userSig = result.userSig;
      userToken = result.userToken;
      userInfo.value = result.userInfo;

      isLogin.value = true;

      /// 登录IM
      await TimService.to.initSdk();

      return true;
    } else {
      return false;
    }
  }

  /// 退出登录
  Future<void> logout() async {
    await TencentImSDKPlugin.v2TIMManager.logout();
    _box.remove('userSig');
    _box.remove('userId');
    _box.remove('userToken');
    _box.remove('mnemonic');
    _box.remove('userInfo');

    userSig = '';
    userId = '';
    userToken = '';

    TimService.to.instance.logout();

    /// 移除这些服务
    Get.delete<TimConversationService>();
    Get.delete<TimFriendService>();
    Get.delete<TimGroupService>();
    Get.delete<TimBlockService>();
    Get.delete<TimApplyService>();
    Get.delete<TimMessageService>();

    userInfo.value = UserInfoModel.empty();
    isLogin.value = false;
    Get.offAllNamed(AuthRoutes.index);
  }

  Future<void> updateUserInfo(String key, String value) async {
    if (key == 'nickname') {
      userInfo.value.nickname = value;
    } else if (key == 'avatar') {
      userInfo.value.avatar = value;
    }

    userInfo.refresh();

    _box.write('userInfo', userInfo.toJson());
  }
}
