import 'package:fis_jsonrpc/rpc.dart';
import 'package:get/get.dart';

import '../defines.dart';
import '../store.dart';

class UserState extends StateModuleBase {
  String? _token;
  String? _account;
  final RxString _displayName = ''.obs;
  final RxList<String> _features = RxList<String>();

  /// 登录令牌
  String? get token => _token;

  /// 登录账号
  String? get account => _account;

  /// 外显名称
  String get displayName => _userInfo?.realName ?? _userInfo?.userName ?? "";

  /// 团队名称
  String get teamName => _userInfo?.teamName ?? "";

  /// 是否登录中
  bool get isLogOn => token != null && token!.isNotEmpty;

  /// 用户信息
  UserDTO? _userInfo;

  /// 处理登录
  Future<void> handleLogin(
    String account,
    String token,
  ) async {
    _token = token;
    _account = account;

    // await _fetchFeatures();// TODO:

    await Store.persistent();
  }

  /// 处理登出
  Future<void> handleLogOut() async {
    _token = null;

    await Store.persistent();
  }

  /// 更新用户信息
  void updateUserInfo(UserDTO dto) {
    _userInfo = dto;
  }

  @override
  Future<void> acceptPersistenceJson(Map<String, dynamic> map) async {
    // key对应值不为空时，给相应字段赋值
    map.pickPersistentProp('token', (x) => _token = x);
    map.pickPersistentProp(
      'features',
      (x) => _updateFeatures((x as List).cast<String>()),
    );
    map.pickPersistentProps({
      'account': (x) => _account = x,
      'displayName': (x) => _displayName.value = x,
    });
  }

  @override
  Map<String, dynamic> toPersistenceJson() {
    return {
      "token": token,
      "account": account,
      "displayName": displayName,
    };
  }

  void _updateFeatures(Iterable<String> keys) {
    _features.value = List.unmodifiable(keys);
  }

  void _clearFeatures() => _features.value = [];
}
