//
//  ViewController.m
//  FaceVerify
//
//  Created by zhuxun.lx on 2022/11/7.
//

#import "ViewController.h"
#import <AliyunIdentityManager/AliyunIdentityPublicApi.h>
#import "FaceVerifyClient.h"

@interface ViewController ()
@property(nonatomic,strong)UILabel *nameLabel;
@property(nonatomic,strong)UITextField *nameTF;
@property(nonatomic,strong)UILabel *cardLabel;
@property(nonatomic,strong)UITextField *cardIdTF;
@property(nonatomic,strong) UIButton *submitInfoBtn;
@property(nonatomic,strong) UIImageView *headerView;
@end

@implementation ViewController

// 不支持动态切换横竖屏。
- (BOOL)shouldAutorotate{
    return NO;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self createUI];
    // SDK初始化，这个函数应该尽可能早调用。
    [AliyunSdk init];
}

- (void)createUI {
    self.nameLabel = [[UILabel alloc] initWithFrame:CGRectMake(30, 90, 80, 30)];
    self.nameLabel.backgroundColor = [UIColor clearColor];
    self.nameLabel.font = [UIFont fontWithName:@"Helvetica-Bold"size:18];
    self.nameLabel.text = @"姓名";
    self.nameLabel.textColor = [UIColor blackColor];
    [self.view addSubview:self.nameLabel];
    
    self.nameTF = [[UITextField alloc] initWithFrame:CGRectMake(120, 90, 220, 30)];
    self.nameTF.placeholder = @"请输入姓名";
    [self.nameTF setBorderStyle:UITextBorderStyleRoundedRect];
    [self.view addSubview:self.nameTF];
    
    self.cardLabel = [[UILabel alloc] initWithFrame:CGRectMake(30, 140, 80, 30)];
    self.cardLabel.backgroundColor = [UIColor clearColor];
    self.cardLabel.font = [UIFont fontWithName:@"Helvetica-Bold"size:18];
    self.cardLabel.text = @"身份证号";
    self.cardLabel.textColor = [UIColor blackColor];
    [self.view addSubview:self.cardLabel];
    
    self.cardIdTF = [[UITextField alloc] initWithFrame:CGRectMake(120, 140, 220, 30)];
    self.cardIdTF.placeholder = @"请输入身份证";
    [self.cardIdTF setBorderStyle:UITextBorderStyleRoundedRect];
    [self.view addSubview:self.cardIdTF];
    
    self.submitInfoBtn = [UIButton buttonWithType:UIButtonTypeSystem];
    self.submitInfoBtn.frame = CGRectMake(140, 200, 80, 30);
    [self.submitInfoBtn setTitle:@"开始认证" forState:UIControlStateNormal];
    [self.submitInfoBtn addTarget:self action:@selector(beginVerify) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.submitInfoBtn];
    
    self.headerView = [UIImageView new];
    self.headerView.frame = CGRectMake(70, 240, 220, 300);
    [self.view addSubview:self.headerView];
}

/**
 * 开始认证
 */
- (void)beginVerify {
    [self.nameTF resignFirstResponder];
    [self.cardIdTF resignFirstResponder];
    if (self.nameTF.text.length==0) {
        [self alertInfomation:@"姓名不能为空"];
        return;
    }
    if (self.cardIdTF.text.length==0) {
        [self alertInfomation:@"身份证不能为空"];
        return;
    }
    
    NSString* certificateName = self.nameTF.text;
    NSString* certificateNumber = self.cardIdTF.text;
    NSString* metaInfo = [self jsonStringEncoded:[AliyunIdentityManager getMetaInfo]];
    
    //从服务端获取 verificationToken
    [FaceVerifyClient genRealPersonVerificationTokenWithCertificateName:certificateName andCertificateNumber:certificateNumber andMetaInfo:metaInfo responseBlock:^(NSString * _Nonnull verificationToken, NSError * _Nonnull error) {
        if (error) {
            if ([error.localizedDescription containsString:@"InvalidAccessKeyId.NotFound"]) {
                [self alertInfomation:@"请求报错，请检查您代码中的YOUR_ACCESS_KEY_ID和YOUR_ACCESS_KEY_SECRET是否已经修改正确。"];
            } else if([error.localizedDescription containsString:@"InvalidApi.NotPurchase"]) {
                [self alertInfomation:@"请求报错，您的账号未开通视觉智能开放平台-人脸人体，请进行开通：https://common-buy.aliyun.com/?commodityCode=viapi_facebody_public_cn#/open"];
            } else if([error.localizedDescription containsString:@"Unauthorized"]) {
                [self alertInfomation:@"请求报错，您的子账号未授予AliyunVIAPIFullAccess权限，请参考https://help.aliyun.com/document_detail/145025.html"];
            } else {
                [self alertInfomation:error.localizedDescription];
            }
        } else {
            [self verify:verificationToken];
        }
    }];
}

/**
 * 进入认证
 * @param verificationToken 认证唯一标识
 */
-(void)verify:(NSString*)verificationToken{
    [_submitInfoBtn setUserInteractionEnabled:NO];
    NSMutableDictionary  *extParams = [NSMutableDictionary new];
    [extParams setValue:self forKey:@"currentCtr"];
    
    [[AliyunIdentityManager sharedInstance] verifyWith:verificationToken extParams:extParams onCompletion:^(ZIMResponse *response) {
        dispatch_async(dispatch_get_main_queue(), ^{
            if (response.code == 1000) {
                // 刷脸成功
                self.headerView.image = [UIImage imageWithData:response.imageContent];
            }else if (response.code == 1003) {
                // 用户退出
            }else if (response.code == 2002){
                // 网络错误
            }else if (response.code == 2003){
                // 设备时间不准确
            }else if (response.code == 2006){
                // 刷脸失败
            }else{
                // 用户被动退出
            }
            
            // 端侧认证结束后需要去服务端查询结果
            [FaceVerifyClient getRealPersonVerificationResultWithVerificationToken:verificationToken responseBlock:^(BOOL isPassed, NSError * _Nonnull error) {
                if (error) {
                    [self alertInfomation:[NSString stringWithFormat:@"核身认证查询 error:%@", error.localizedDescription]];
                } else {
                    [self alertInfomation:isPassed == 1?@"核身认证查询通过":@"核身认证查询不通过"];
                }
            }];
            
            [self.submitInfoBtn setUserInteractionEnabled:YES];
        });
    }];
}

/**
 显示alert
 */
-(void)alertInfomation:(NSString*)msg {
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"警告" message:msg preferredStyle:UIAlertControllerStyleAlert];
    [alertController addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
    }]];
    [self presentViewController:alertController animated:YES completion:nil];
}

- (NSString *)jsonStringEncoded:(NSDictionary*)dic {
    if ([NSJSONSerialization isValidJSONObject:dic]) {
        NSError *error;
        NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:0 error:&error];
        NSString *json = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
        return json;
    }
    return nil;
}

@end
