import 'dart:convert';

import 'package:app_business/generated/base.pb.dart' as pb;
import 'package:app_business/service/api.dart';
import 'package:get/get.dart';
import 'package:track_common/track_common.dart';
import 'package:track_common/view.dart';

class LoginControllerImp extends LoginController {
  final _api = Get.find<ApiService>();

  @override
  Future<void> authSendCodeToPhone(String phone) async {
    return _api.authSendCodeToPhone(phone, SmsType.Login);
  }

  @override
  Future<Duration> getCodeLifeTime(String phone) {
    return _api.getSmsSendLeftTime(phone);
  }

  @override
  Future<void> signIn(String phone, String code) async {
    return _api.signIn(phone, code, '');
  }

  @override
  Future<(String, String)> getQrCode() async {
    final r = await _api.stub.toGetSignInQrCode(DefaultRequest());
    final json = const JsonEncoder().convert({'KeyType': 2, 'code': r.qrCode});
    return (json, r.qrCode);
  }

  @override
  Future<bool> isQrCodeOk(String codeValue) async {
    if (codeValue.isEmpty) {
      return false;
    }
    final r =
        await _api.stub.toQrCodeSignIn(pb.QrCodeInfo()..qrCode = qrCodeValue);
    final token = r.token.replaceAll("\"", "").trim();
    if (token.isEmpty) {
      return false;
    }
    debug('token: $token');
    _api.token = token;
    return true;
  }
}
