//
//  XMQuickOneKeyLoginManager.m
//  XinMai
//
//  Created by mac on 2020/10/19.
//

#import "XMQuickOneKeyLoginManager.h"
#import <ATAuthSDK/ATAuthSDK.h>
#import "PNSBuildModelUtils.h"

#import <React/RCTBridge.h>
#import <React/RCTEventDispatcher.h>

static XMQuickOneKeyLoginManager *shareManager = nil;
static NSString * const XMOTHERLOGIN = @"OTHERLOGIN";
static NSString * const XMONEKEYLOGIN = @"ONEKEYLOGIN";
static NSString * const XMERRORLOGIN = @"ERRORLOGIN";
@implementation XMQuickOneKeyLoginManager

@synthesize bridge = _bridge;

RCT_EXPORT_MODULE(OneKeyLogin);

+ (instancetype)shareManager
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        shareManager = [[super allocWithZone:NULL]init];
    });
    return shareManager;
}

+ (instancetype)allocWithZone:(struct _NSZone *)zone
{
    return [XMQuickOneKeyLoginManager shareManager];
}

- (instancetype)copyWithZone:(struct _NSZone *)zone
{
    return [XMQuickOneKeyLoginManager shareManager];
}
- (instancetype)mutableCopyWithZone:(struct _NSZone *)zone
{
    return [XMQuickOneKeyLoginManager shareManager];
}

RCT_EXPORT_METHOD(initAuthSDKInfo:(NSString *)authSDKkey){
    //阿里云一键登录
    [[TXCommonHandler sharedInstance] setAuthSDKInfo:authSDKkey
                                               complete:^(NSDictionary * _Nonnull resultDic) {
           NSLog(@"设置秘钥结果：%@", resultDic);
    }];
    
    [[TXCommonHandler sharedInstance] accelerateLoginPageWithTimeout:3.0 complete:^(NSDictionary * _Nonnull resultDic) {
            NSLog(@"为后面授权页拉起加个速，加速结果：%@", resultDic);
    }];
}

-(UIViewController*)getCurrentWindowVC
{
    UIViewController *result = nil;
    UIWindow * window = [[UIApplication sharedApplication] keyWindow];
    //app默认windowLevel是UIWindowLevelNormal，如果不是，找到它
    if (window.windowLevel != UIWindowLevelNormal) {
        NSArray *windows = [[UIApplication sharedApplication] windows];
        for(UIWindow * tmpWin in windows) {
            if (tmpWin.windowLevel == UIWindowLevelNormal) {
                window = tmpWin;
                break;
            }
        }
    }
    id nextResponder = nil;
    UIViewController *appRootVC = window.rootViewController;
    //1、通过present弹出VC，appRootVC.presentedViewController不为nil
    if (appRootVC.presentedViewController) {
        nextResponder = appRootVC.presentedViewController;
    }else{
        //2、通过navigationcontroller弹出VC
        UIView *frontView = [[window subviews] objectAtIndex:0];
        nextResponder = [frontView nextResponder];
        if ([nextResponder isKindOfClass:[UIViewController class]])
        {
            result = nextResponder;
        }
        else
        {
            result = window.rootViewController;
        }
        return result;
    }
    return nextResponder;
}

RCT_EXPORT_METHOD(showOneKeyLogin:(NSString *)logoImageName registerPrivacyUrl:(NSString *)registerPrivacyUrl protectPrivacyUrl:(NSString *)protectPrivacyUrl checkBoxImage:(NSString *)checkBoxImage sloganText:(NSString *)sloganText loginBtnText:(NSString *)loginBtnText changeBtnTitle:(NSString *)changeBtnTitle loginBtnBgImgs:(NSArray *)loginBtnBgImgs){
  dispatch_async(dispatch_get_main_queue(), ^{
    TXCustomModel *model = [PNSBuildModelUtils buildSheetPortraitModelWithLogoImageName:logoImageName registerPrivacyUrl:registerPrivacyUrl protectPrivacyUrl:protectPrivacyUrl checkBoxImage:checkBoxImage sloganText:sloganText loginBtnText:loginBtnText changeBtnTitle:changeBtnTitle loginBtnBgImgs:loginBtnBgImgs];
    __weak typeof(self) weakSelf = self;
    [[TXCommonHandler sharedInstance] getLoginTokenWithTimeout:3.0
                                                    controller:[self getCurrentWindowVC]
                                                         model:model
                                                      complete:^(NSDictionary * _Nonnull resultDic) {
         __weak typeof(weakSelf) strongSelf = weakSelf;
        NSString *resultCode = [resultDic objectForKey:@"resultCode"];
        NSLog(@"getLoginTokenWithTimeoutcomplete：%@", resultDic);
        if([PNSCodeLoginControllerPresentSuccess isEqualToString:resultCode]) {
            
            
        }else if ([PNSCodeLoginControllerClickCancel isEqualToString:resultCode]) {
          
        }else if ([PNSCodeLoginControllerClickChangeBtn isEqualToString:resultCode]){
            [[TXCommonHandler sharedInstance] cancelLoginVCAnimated:YES complete:^{
                NSMutableDictionary *resultData = @{@"way":@(1)}.mutableCopy;
                [resultData addEntriesFromDictionary:resultDic];
                [strongSelf.bridge.eventDispatcher sendAppEventWithName:XMOTHERLOGIN body:resultData];
            }];
        }else if ([PNSCodeLoginControllerClickLoginBtn isEqualToString:resultCode]){
          
        }else if ([PNSCodeLoginControllerClickCheckBoxBtn isEqualToString:resultCode]){
          
        }else if ([PNSCodeLoginControllerClickProtocol isEqualToString:resultCode]){
          NSString *url = [resultDic objectForKey:@"url"];
          [strongSelf.bridge.eventDispatcher sendAppEventWithName:url body:resultDic];
          
        }else if ([PNSCodeSuccess isEqualToString:resultCode]) {
          [[TXCommonHandler sharedInstance] cancelLoginVCAnimated:YES complete:^{
            [strongSelf.bridge.eventDispatcher sendAppEventWithName:XMONEKEYLOGIN body:resultDic];
          }];
        } else {
            [[TXCommonHandler sharedInstance] cancelLoginVCAnimated:NO complete:^{
                
            }];
            [strongSelf.bridge.eventDispatcher sendAppEventWithName:XMERRORLOGIN body:resultDic];
            NSLog(@"获取LoginToken或拉起授权页失败回调：%@", resultDic);
        }
    }];
  });
  
}

@end
