account_repository.dart 2.1 KB

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