account_repository.dart 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. import 'dart:async';
  2. import 'package:electronic_assistant/data/api/atmob_api.dart';
  3. import 'package:electronic_assistant/utils/event_bus.dart';
  4. import 'package:electronic_assistant/utils/mmkv_util.dart';
  5. import 'package:flutter/cupertino.dart';
  6. import 'package:get/get.dart';
  7. import '../../resource/string.gen.dart';
  8. import '../../utils/http_handler.dart';
  9. import '../api/request/login_request.dart';
  10. import '../api/request/verification_code_request.dart';
  11. import '../api/response/login_response.dart';
  12. const String EventUserLogin = 'EventUserLogin';
  13. const String EventUserLogout = 'EventUserLogout';
  14. class AccountRepository {
  15. final ACCOUNT_TOKEN = 'account_token';
  16. final ACCOUNT_PHONE = 'account_phone';
  17. String? _token;
  18. String? _phone;
  19. final isLogin = false.obs;
  20. AccountRepository._() {
  21. debugPrint('AccountRepository init');
  22. _token = KVUtil.getString(ACCOUNT_TOKEN, null);
  23. _phone = KVUtil.getString(ACCOUNT_PHONE, null);
  24. if (_token != null && _token!.isNotEmpty) {
  25. isLogin.value = true;
  26. }
  27. }
  28. String? get phone => _phone;
  29. String? get token => _token;
  30. Future<void> getVerificationCode(String phone) {
  31. return atmobApi
  32. .getVerificationCode(VerificationCodeRequest(phone))
  33. .then(HttpHandler.handle(true));
  34. }
  35. Future<LoginResponse> login(String phone, String code) {
  36. return atmobApi
  37. .login(LoginRequest(phone, code))
  38. .then(HttpHandler.handle(false))
  39. .then((response) {
  40. onLoginSuccess(phone, response.authToken);
  41. refreshUserInfo();
  42. return response;
  43. });
  44. }
  45. void onLoginSuccess(String phone, String? token) {
  46. this._token = token;
  47. this._phone = phone;
  48. KVUtil.putString(ACCOUNT_TOKEN, token);
  49. KVUtil.putString(ACCOUNT_PHONE, phone);
  50. isLogin.value = true;
  51. eventBus.emit(EventUserLogin);
  52. }
  53. void logout() {
  54. _phone = null;
  55. _phone = null;
  56. KVUtil.putString(ACCOUNT_TOKEN, null);
  57. KVUtil.putString(ACCOUNT_PHONE, null);
  58. isLogin.value = false;
  59. eventBus.emit(EventUserLogout);
  60. }
  61. void cleanLoginInfo() {
  62. _phone = null;
  63. _phone = null;
  64. KVUtil.putString(ACCOUNT_TOKEN, null);
  65. KVUtil.putString(ACCOUNT_PHONE, null);
  66. isLogin.value = false;
  67. }
  68. void refreshUserInfo() {}
  69. getUserSubName(String? phone) {
  70. String name = StringName.account.tr;
  71. if (phone == null) {
  72. return name;
  73. }
  74. //后4位
  75. if (phone.length > 4) {
  76. phone = phone.substring(phone.length - 4);
  77. }
  78. return '$name$phone';
  79. }
  80. }
  81. final accountRepository = AccountRepository._();