import 'package:fis_jsonrpc/rpc.dart';
import 'package:get/get.dart';
import 'package:vnoteapp/architecture/types/index.dart';
import 'package:vnoteapp/managers/interfaces/template.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;

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

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

  /// 用户Code
  String? get userCode => _userInfo?.code;

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

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

  /// 负责医生
  String get principalName => _userInfo?.principalName ?? "";

  /// 医生电话
  String get principalPhone => _userInfo?.principalPhone ?? "";

  /// 机构名称
  String get organizationName => _userInfo?.organizationName ?? "";

  /// 机构电话
  String get organizationPhone => _userInfo?.organizationPhone ?? "";

  /// 医生签名
  String get signature => _userInfo?.signature ?? "";

  /// 负责区域(村)集合
  List<StringKVModel> get residence =>
      _userInfo?.residence
          ?.map((e) => StringKVModel(e.code!, e.name!))
          .toList() ??
      [];

  /// 用户信息
  UserDTO? _userInfo;

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

    // await _fetchFeatures();// TODO:

    await Store.persistent();
    await Get.find<ITemplateManager>().saveTemplate();
  }

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

    await Store.persistent();
  }

  /// 更新用户信息
  Future<void> updateUserInfo(UserDTO dto) async {
    _userInfo = dto;
    await Store.persistent();
  }

  /// 更新用户签名
  Future<void> updateSignature(String value) async {
    if (_userInfo != null) {
      _userInfo!.signature = value;
      await Store.persistent();
    }
  }

  @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,
    });
    map.pickPersistentProp(
      'userInfo',
      (x) {
        if (x != null) {
          _userInfo = UserDTO.fromJson(x);
        }
      },
    );
  }

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

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

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