//
//  SignInApple.m
//  SignInAppleDemo
//
//  Created by Yostar on 2019/11/25.
//  Copyright © 2019 Yostar. All rights reserved.
//

#import "SignInApple.h"
#import <AuthenticationServices/AuthenticationServices.h>

#define KEYCHAIN_IDENTIFIER(a) ([NSString stringWithFormat:@"%@_%@",[[NSBundle mainBundle] bundleIdentifier],a])

@interface SignInApple () <ASAuthorizationControllerDelegate, ASAuthorizationControllerPresentationContextProviding>

@end

@implementation SignInApple

// 处理授权
- (void)handleAuthorizationAppleIDButtonPress{
    NSLog(@"////////");
    
    if (@available(iOS 13.0, *)) {
        // 基于用户的Apple ID授权用户，生成用户授权请求的一种机制
        ASAuthorizationAppleIDProvider *appleIDProvider = [[ASAuthorizationAppleIDProvider alloc] init];
        // 创建新的AppleID 授权请求
        ASAuthorizationAppleIDRequest *appleIDRequest = [appleIDProvider createRequest];
        // 在用户授权期间请求的联系信息
        appleIDRequest.requestedScopes = @[ASAuthorizationScopeFullName, ASAuthorizationScopeEmail];
        // 由ASAuthorizationAppleIDProvider创建的授权请求 管理授权请求的控制器
        ASAuthorizationController *authorizationController = [[ASAuthorizationController alloc] initWithAuthorizationRequests:@[appleIDRequest]];
        // 设置授权控制器通知授权请求的成功与失败的代理
        authorizationController.delegate = self;
        // 设置提供 展示上下文的代理，在这个上下文中 系统可以展示授权界面给用户
        authorizationController.presentationContextProvider = self;
        // 在控制器初始化期间启动授权流
        [authorizationController performRequests];
    }else{
        // 处理不支持系统版本
        NSLog(@"该系统版本不可用Apple登录");
    }
}

// 如果存在iCloud Keychain 凭证或者AppleID 凭证提示用户
- (void)perfomExistingAccountSetupFlows{
    NSLog(@"///已经认证过了/////");
    
    if (@available(iOS 13.0, *)) {
        // 基于用户的Apple ID授权用户，生成用户授权请求的一种机制
        ASAuthorizationAppleIDProvider *appleIDProvider = [[ASAuthorizationAppleIDProvider alloc] init];
        // 授权请求AppleID
        ASAuthorizationAppleIDRequest *appleIDRequest = [appleIDProvider createRequest];
        // 为了执行钥匙串凭证分享生成请求的一种机制
        ASAuthorizationPasswordProvider *passwordProvider = [[ASAuthorizationPasswordProvider alloc] init];
        ASAuthorizationPasswordRequest *passwordRequest = [passwordProvider createRequest];
        // 由ASAuthorizationAppleIDProvider创建的授权请求 管理授权请求的控制器
        ASAuthorizationController *authorizationController = [[ASAuthorizationController alloc] initWithAuthorizationRequests:@[appleIDRequest, passwordRequest]];
        // 设置授权控制器通知授权请求的成功与失败的代理
        authorizationController.delegate = self;
        // 设置提供 展示上下文的代理，在这个上下文中 系统可以展示授权界面给用户
        authorizationController.presentationContextProvider = self;
        // 在控制器初始化期间启动授权流
        [authorizationController performRequests];
    }else{
        // 处理不支持系统版本
        NSLog(@"该系统版本不可用Apple登录");
    }
}

#pragma mark - delegate
//@optional 授权成功地回调
- (void)authorizationController:(ASAuthorizationController *)controller didCompleteWithAuthorization:(ASAuthorization *)authorization API_AVAILABLE(ios(13.0)){
    NSLog(@"授权完成:::%@", authorization.credential);
    NSLog(@"%s", __FUNCTION__);
    NSLog(@"%@", controller);
    NSLog(@"%@", authorization);
    
    if ([authorization.credential isKindOfClass:[ASAuthorizationAppleIDCredential class]]) {
        // 用户登录使用ASAuthorizationAppleIDCredential
        ASAuthorizationAppleIDCredential *appleIDCredential = authorization.credential;
        NSString *user = appleIDCredential.user;
        // 使用过授权的，可能获取不到以下三个参数
//        NSString *familyName = appleIDCredential.fullName.familyName;
//        NSString *givenName = appleIDCredential.fullName.givenName;
//        NSString *email = appleIDCredential.email;
        
        NSData *identityToken = appleIDCredential.identityToken;
        NSData *authorizationCode = appleIDCredential.authorizationCode;
        
        // 服务器验证需要使用的参数
        NSString *identityTokenStr = [[NSString alloc] initWithData:identityToken encoding:NSUTF8StringEncoding];
        NSString *authorizationCodeStr = [[NSString alloc] initWithData:authorizationCode encoding:NSUTF8StringEncoding];
        NSLog(@"identityTokenStr:%@\n\nauthorizationCodeStr:%@ :userid:%ld", identityTokenStr, authorizationCodeStr,[getPeopleID PeopleID]);
        
        //[self getUserInfoWithToken:identityTokenStr uid:user];
        
        
       
          [self signInWithApple:[self getRandomNameStr] defaultPic:@"https://i.rensheju.com/userPhoto/defaultPhoto.png" uid:user];
        

        
        // Create an account in your system.
        // For the purpose of this demo app, store the userIdentifier in the keychain.
        //  需要使用钥匙串的方式保存用户的唯一信息
//        [YostarKeychain save:KEYCHAIN_IDENTIFIER(@"userIdentifier") data:user];
        
    }else if ([authorization.credential isKindOfClass:[ASPasswordCredential class]]){
        // 这个获取的是iCloud记录的账号密码，需要输入框支持iOS 12 记录账号密码的新特性，如果不支持，可以忽略
        // Sign in using an existing iCloud Keychain credential.
        // 用户登录使用现有的密码凭证
//        ASPasswordCredential *passwordCredential = authorization.credential;
//        // 密码凭证对象的用户标识 用户的唯一标识
//        NSString *user = passwordCredential.user;
//        // 密码凭证对象的密码
//        NSString *password = passwordCredential.password;
        
    }else{
        NSLog(@"授权信息均不符");
        
    }
}

//获取月日
- (NSString *)getRandomNameStr
{
    NSDate *date = [NSDate date];
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    //获取当前时间日期展示字符串 如：2019-05-23-13:58:59
//    NSString *str = [formatter stringFromDate:date];

    //下面是单独获取每项的值
    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    NSDateComponents *comps = [[NSDateComponents alloc] init];
    NSInteger unitFlags = NSYearCalendarUnit |NSMonthCalendarUnit |NSDayCalendarUnit |NSWeekdayCalendarUnit |NSHourCalendarUnit |NSMinuteCalendarUnit |NSSecondCalendarUnit;
    comps = [calendar components:unitFlags fromDate:date];
    //月
    
    
    NSString*monthStr = nil;
    NSString*dayStr = nil;
    
    NSInteger month = [comps month];
    if (month < 10) {
        monthStr = [NSString stringWithFormat:@"0%ld",month];
    }else{
        monthStr = [NSString stringWithFormat:@"%ld",month];
    }
    
    //日
    NSInteger day = [comps day];
    if (day < 10) {
        dayStr = [NSString stringWithFormat:@"0%ld",day];
    }else{
        dayStr = [NSString stringWithFormat:@"%ld",day];
    }
    NSString*dateStr = [NSString stringWithFormat:@"%@%@",monthStr,dayStr];
    
    int num = (arc4random() % 9000) + 1000;
   NSString* randomNumber = [NSString stringWithFormat:@"%d", num];
    NSString*nameStr = [NSString stringWithFormat:@"apple%@%@",dateStr,randomNumber];
    return nameStr;
}

#pragma mark - 常的接口获取姓名和头像
- (NSDictionary *)getUserInfoParaWithToken:(NSString*)token
{
    NSDictionary*params = @{
        @"identifyToken":token
    };
    return params;
}

- (void)getUserInfoWithToken:(NSString *)token uid:(NSString *)uid
{
    NSString* url = [IPDIZHI stringByAppendingString:@"/socialsecurity/apple/third_login"];
    
    [KKLoadingAnimationView show];
    [NetworkRequest SBAuthPost:url Params:[self getUserInfoParaWithToken:token] Success:^(id _Nonnull objc) {
        
        NSLog(@"objc:%@",objc);
        NSString* code = [NSString stringWithFormat:@"%@",objc[@"code"]];
        NSString* des = [NSString stringWithFormat:@"%@",objc[@"des"]];
        if ([code isEqualToString:@"0"]) {
            NSDictionary*result = objc[@"result"];
            NSString*cusname = [NSString validBlankStr:result[@"cusname"]];
            NSString*defaultPic = [NSString validBlankStr:result[@"defaultPic"]];
            [self signInWithApple:cusname defaultPic:defaultPic uid:uid];
        }else{
            [KKLoadingAnimationView dismiss];
            [SVProgressHUD showErrorWithStatus:des];
        }
    } Failure:^(NSError* error) {
        [KKLoadingAnimationView dismiss];
        NSLog(@"error:%@",error);
        [SVProgressHUD showErrorWithStatus:@"网络异常"];
    }];
}

- (void)signInWithApple:(NSString *)cusname defaultPic:(NSString *)defaultPic uid:(NSString *)uid
{
    NSString * url =[IPDIZHI stringByAppendingString:@"/socialsecurity/kankan/login"];
    NSString * encodeUrl =  [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
   
    NSString*sign = [NSString stringWithFormat:@"accountName=%@&authName=kkanface&loginType=2&uid=%@&KkweInfo23255625",cusname,uid];
    sign =  [MyMD5 md5:sign];
   
   NSDictionary*params = @{
    @"loginType":@(2),
    @"uid":uid ? uid :@"",
    @"authName":@"kkanface",
    @"sign":sign,
    @"accountName":cusname,
    };
   
   
   [NetworkRequest SBAuthPost:encodeUrl Params:params Success:^(id _Nonnull objc) {
       [KKLoadingAnimationView dismiss];
       
       NSLog(@"objc:%@",objc);
       
       NSString*status = [NSString stringWithFormat:@"%@",objc[@"status"]];
       if ([status isEqualToString:@"0"] || [status isEqualToString:@"1031"]) {
           if (self.SignInApple) {
               self.SignInApple(objc,uid);
           }
       }else{
           //错误码提示
           codeSelected *code = [codeSelected MustTakeReturn:[status intValue]];
           [code returnCodeMethod];
       }
       
   } Failure:^(NSError* error) {
       [KKLoadingAnimationView dismiss];
       
       [SVProgressHUD showErrorWithStatus:@"网络异常"];
       
       NSLog(@"error:%@",error);
   }];
}

// 授权失败的回调
- (void)authorizationController:(ASAuthorizationController *)controller didCompleteWithError:(NSError *)error API_AVAILABLE(ios(13.0)){
    // Handle error.
    NSLog(@"Handle error：%@", error);
    NSString *errorMsg = nil;
    switch (error.code) {
        case ASAuthorizationErrorCanceled:
            errorMsg = @"用户取消了授权请求";
            break;
        case ASAuthorizationErrorFailed:
            errorMsg = @"授权请求失败";
            break;
        case ASAuthorizationErrorInvalidResponse:
            errorMsg = @"授权请求响应无效";
            break;
        case ASAuthorizationErrorNotHandled:
            errorMsg = @"未能处理授权请求";
            break;
        case ASAuthorizationErrorUnknown:
            errorMsg = @"授权请求失败未知原因";
            break;
            
        default:
            break;
    }
    [SVProgressHUD showErrorWithStatus:errorMsg];
    NSLog(@"%@", errorMsg);
}

// 告诉代理应该在哪个window 展示内容给用户
- (ASPresentationAnchor)presentationAnchorForAuthorizationController:(ASAuthorizationController *)controller API_AVAILABLE(ios(13.0)){
    NSLog(@"88888888888");
    // 返回window
    return [UIApplication sharedApplication].windows.lastObject;
}

@end
