import 'package:aliyun_face_plugin/face_auth_plugins.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/services.dart';

class FaceAuthUtils {
  factory FaceAuthUtils() => _singleton;

  static final FaceAuthUtils _singleton = FaceAuthUtils._();

  FaceAuthUtils._() {
    _faceAuthPlugin = AliyunFacePlugin();
  }

  static FaceAuthUtils get instance => _singleton;

  static late AliyunFacePlugin _faceAuthPlugin;

  /// 初始化刷脸认证
  void initFaceAuth() {
    _faceAuthPlugin.init();
  }

  /// 获取metaInfo
  Future<String?> getMetaInfo() async {
    String? metaInfo;
    try {
      // 获取客户端metaInfo，将信息发送到服务器端，调用服务器端相关接口获取认证ID，即CertifyId。
      metaInfo = await _faceAuthPlugin.getMetaInfos();
      debugPrint("FaceAuthUtils getMetaInfo: $metaInfo");
    } on PlatformException {
      debugPrint("FaceAuthUtils getMetaInfo: PlatformException");
    }
    return metaInfo;
  }

  /// 开始认证
  /// useVideo 是否返回活体认证视频 0不返 1返回
  Future<String?> startVerify(
      {required String certifyId, int useVideo = 0}) async {
    String? verifyResult;

    Map<String, String> params = {
      "certifyId": certifyId,
      "ext_params_key_use_video": useVideo.toString()
    };

    try {
      // 调用认证接口，CertifyId需要调用服务器端接口获取。
      // 每个CertifyId只能使用一次，否则会返回code: "2002(iOS), 1001(Android)"。
      verifyResult = await _faceAuthPlugin.verify(params);
      debugPrint("FaceAuthUtils startVerify: $verifyResult");
    } on PlatformException {
      debugPrint("FaceAuthUtils startVerify: PlatformException");
    }
    return verifyResult;
  }
}
