import 'dart:async';

import 'package:electronic_assistant/data/api/atmob_api.dart';
import 'package:electronic_assistant/utils/event_bus.dart';
import 'package:electronic_assistant/utils/mmkv_util.dart';
import 'package:flutter/cupertino.dart';
import 'package:get/get.dart';

import '../../resource/string.gen.dart';
import '../../utils/http_handler.dart';
import '../api/request/login_request.dart';
import '../api/request/verification_code_request.dart';
import '../api/response/login_response.dart';

const String EventUserLogin = 'EventUserLogin';
const String EventUserLogout = 'EventUserLogout';

class AccountRepository {
  final ACCOUNT_TOKEN = 'account_token';
  final ACCOUNT_PHONE = 'account_phone';

  String? _token;
  String? _phone;
  final isLogin = false.obs;

  AccountRepository._() {
    debugPrint('AccountRepository init');
    _token = KVUtil.getString(ACCOUNT_TOKEN, null);
    _phone = KVUtil.getString(ACCOUNT_PHONE, null);
    if (_token != null && _token!.isNotEmpty) {
      isLogin.value = true;
    }
  }

  String? get phone => _phone;

  String? get token => _token;

  Future<void> getVerificationCode(String phone) {
    return atmobApi
        .getVerificationCode(VerificationCodeRequest(phone))
        .then(HttpHandler.handle(true));
  }

  Future<LoginResponse> login(String phone, String code) {
    return atmobApi
        .login(LoginRequest(phone, code))
        .then(HttpHandler.handle(false))
        .then((response) {
      onLoginSuccess(phone, response.authToken);
      refreshUserInfo();
      return response;
    });
  }

  void onLoginSuccess(String phone, String? token) {
    this._token = token;
    this._phone = phone;
    KVUtil.putString(ACCOUNT_TOKEN, token);
    KVUtil.putString(ACCOUNT_PHONE, phone);
    isLogin.value = true;

    eventBus.emit(EventUserLogin);
  }

  void logout() {
    _phone = null;
    _phone = null;
    KVUtil.putString(ACCOUNT_TOKEN, null);
    KVUtil.putString(ACCOUNT_PHONE, null);
    isLogin.value = false;

    eventBus.emit(EventUserLogout);
  }

  void cleanLoginInfo() {
    _phone = null;
    _phone = null;
    KVUtil.putString(ACCOUNT_TOKEN, null);
    KVUtil.putString(ACCOUNT_PHONE, null);
    isLogin.value = false;
  }

  void refreshUserInfo() {}

  getUserSubName(String? phone) {
    String name = StringName.account.tr;
    if (phone == null) {
      return name;
    }
    //后4位
    if (phone.length > 4) {
      phone = phone.substring(phone.length - 4);
    }
    return '$name$phone';
  }
}

final accountRepository = AccountRepository._();
