//
//  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);
    }];
}


- (UIWindow *)getKeyWindow{
    UIWindow *keyWindow = [UIApplication sharedApplication].keyWindow;
    if (keyWindow.windowLevel != UIWindowLevelNormal){
        NSArray *windows = [[UIApplication sharedApplication] windows];
        for (UIWindow *window in windows) {
            if (window.isKeyWindow || window.windowLevel == UIWindowLevelNormal) {
                keyWindow = window;
                break;
            }
        }
    }
    if (!keyWindow || keyWindow.windowLevel != UIWindowLevelNormal) {
        id appDelegate = [UIApplication sharedApplication].delegate;
        if (appDelegate && [appDelegate respondsToSelector:@selector(window)]) {
            keyWindow = [appDelegate window];
        }
    }
    return keyWindow;
}


//获取Window当前显示的ViewController
- (UIViewController*)currentViewController{
    //获得当前活动窗口的根视图
    UIViewController *viewController = [self getKeyWindow].rootViewController;
    if(!viewController){
        viewController = [UIApplication sharedApplication].delegate.window.rootViewController;
    }
    while (1)
    {
        //根据不同的页面切换方式，逐步取得最上层的viewController
        if ([viewController isKindOfClass:[UITabBarController class]]) {
            viewController = ((UITabBarController*)viewController).selectedViewController;
        }
        if ([viewController isKindOfClass:[UINavigationController class]]) {
            viewController = ((UINavigationController*)viewController).visibleViewController;
        }
        if (viewController.presentedViewController) {
            viewController = viewController.presentedViewController;
        }else{
            break;
        }
    }
    return viewController;
}



// 弹框 一键登录
RCT_EXPORT_METHOD(showAlertOneKeyLogin:(NSString *)logoImageName registerPrivacyUrl:(NSString *)registerPrivacyUrl protectPrivacyUrl:(NSString *)protectPrivacyUrl registerTitle:(NSString *)registerTitle protectTitle:(NSString *)protectTitle sloganText:(NSString *)sloganText loginBtnText:(NSString *)loginBtnText loginBtnColor:(NSString *)loginBtnColor){
  dispatch_async(dispatch_get_main_queue(), ^{
      __weak typeof(self) weakSelf = self;
      TXCustomModel *model = [PNSBuildModelUtils buildSheetAlertModelWithLogoImageName:logoImageName registerPrivacyUrl:registerPrivacyUrl protectPrivacyUrl:protectPrivacyUrl checkBoxImage:@"" sloganText:sloganText loginBtnText:loginBtnText changeBtnTitle:@"" loginBtnBgImgs:@[]];
    [[TXCommonHandler sharedInstance] getLoginTokenWithTimeout:3.0
                                                    controller:[self currentViewController]
                                                         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":@(5)}.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);
        }
    }];
  });
  
}

// 竖直全屏
RCT_EXPORT_METHOD(showFullPortraitOneKeyLogin:(NSString *)logoImageName registerPrivacyUrl:(NSString *)registerPrivacyUrl protectPrivacyUrl:(NSString *)protectPrivacyUrl registerTitle:(NSString *)registerTitle protectTitle:(NSString *)protectTitle sloganText:(NSString *)sloganText loginBtnText:(NSString *)loginBtnText loginBtnColor:(NSString *)loginBtnColor){
  dispatch_async(dispatch_get_main_queue(), ^{
      __weak typeof(self) weakSelf = self;
      TXCustomModel *model = [PNSBuildModelUtils buildSheetPortraitModelWithLogoImageName:logoImageName registerPrivacyUrl:registerPrivacyUrl protectPrivacyUrl:protectPrivacyUrl registerTitle:registerTitle protectTitle:protectTitle sloganText:sloganText loginBtnText:loginBtnText loginBtnColor:loginBtnColor actionBlock:^(PNSOtherActionType type) {
          __weak typeof(weakSelf) strongSelf = weakSelf;
          if ([[TXCommonHandler sharedInstance] queryCheckBoxIsChecked]) {
              [[TXCommonHandler sharedInstance] cancelLoginVCAnimated:YES complete:^{
                  NSDictionary *resultData = @{@"way":@(type),@"checkBox":@"1"};
                  [strongSelf.bridge.eventDispatcher sendAppEventWithName:XMOTHERLOGIN body:resultData];
              }];
          } else {
              NSDictionary *resultData = @{@"way":@(type),@"checkBox":@"0"};
              [strongSelf.bridge.eventDispatcher sendAppEventWithName:XMOTHERLOGIN body:resultData];
          }
      }];
    [[TXCommonHandler sharedInstance] getLoginTokenWithTimeout:3.0
                                                    controller:[self currentViewController]
                                                         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":@(5)}.mutableCopy;
                [resultData addEntriesFromDictionary:resultDic];
                [strongSelf.bridge.eventDispatcher sendAppEventWithName:XMOTHERLOGIN body:resultData];
            }];
        }else if ([PNSCodeLoginControllerClickLoginBtn isEqualToString:resultCode]){
            if (![[TXCommonHandler sharedInstance] queryCheckBoxIsChecked]) {
                NSDictionary *resultData = @{@"way":@(0),@"checkBox":@"0"};
                [strongSelf.bridge.eventDispatcher sendAppEventWithName:XMOTHERLOGIN body:resultData];
            }
          
        }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 if ([PNSCodeLoginControllerDeallocVC isEqualToString:resultCode]) {
            [[TXCommonHandler sharedInstance] cancelLoginVCAnimated:NO complete:^{
                
            }];
        } else {
            [[TXCommonHandler sharedInstance] cancelLoginVCAnimated:NO complete:^{
                
            }];
            [strongSelf.bridge.eventDispatcher sendAppEventWithName:XMERRORLOGIN body:resultDic];
            
            NSLog(@"获取LoginToken或拉起授权页失败回调：%@", resultDic);
        }
    }];
  });
  
}

@end
