/********* cordova-plugin-shanyan-sdk.m Cordova Plugin Implementation *******/

#import <Cordova/CDV.h>
#import <CL_ShanYanSDK/CL_ShanYanSDK.h>

@interface OneKeyLogin : CDVPlugin {
  // Member variables go here.
}

- (void)openLogin:(CDVInvokedUrlCommand*)command;
@end

@implementation OneKeyLogin
{
    CDVInvokedUrlCommand *_command;
    NSString *appKey;
}

- (void)pluginInitialize {
    appKey = [self.commandDelegate settings][@"ios_app_key"];
}

- (void)openLogin:(CDVInvokedUrlCommand*)command
{
    UIViewController *selfVC = [self getCurrentVC];
    _command = command;
    //初始化
    [CLShanYanSDKManager initWithAppId:appKey complete:^(CLCompleteResult * _Nonnull completeResult) {
        if (completeResult.error == nil) {
            [CLShanYanSDKManager preGetPhonenumber:^(CLCompleteResult * _Nonnull completeResult) {
                if (completeResult.error == nil) {

                    CGFloat screenScale = [UIScreen mainScreen].bounds.size.width/375.0;

                    CLUIConfigure * baseUIConfigure = [CLUIConfigure new];
                    baseUIConfigure.viewController = selfVC;
                                        
                    //layout 布局
                    baseUIConfigure.clLogoImage = [UIImage imageNamed:@"avatar.png"];
                    baseUIConfigure.clLogoCornerRadius = @((80 / 2) * screenScale);
//                    baseUIConfigure.clNavigationBackBtnImage = [UIImage imageWithNameInBundle:@"login_close.png"];
                    // 是否需要手动销毁授权页面，默认自动销毁， YES->手动销毁
                    baseUIConfigure.manualDismiss = @(YES);
                    baseUIConfigure.clLoginBtnBgColor = [UIColor colorWithRed:62/255.0 green:103/255.0 blue:240/255.0 alpha:1.0];
                    baseUIConfigure.clLoginBtnTextColor = [UIColor whiteColor];
                    baseUIConfigure.clLoginBtnCornerRadius = @(25);
                    baseUIConfigure.customAreaView = ^(UIView * _Nonnull customAreaView) {
                         UIButton * button = [[UIButton alloc]init];
                         button.center = CGPointMake(customAreaView.center.x,  customAreaView.center.y + 100 * screenScale);
                         button.bounds = CGRectMake(0, 0, 200* screenScale, 40 * screenScale);
                         
                         [button setTitle:@"其他登录方式" forState:(UIControlStateNormal)];
                         button.titleLabel.font = [UIFont systemFontOfSize:12];
                         [button setTitleColor:[UIColor colorWithRed:62/255.0 green:103/255.0 blue:240/255.0 alpha:1.0] forState:(UIControlStateNormal)];
                         [button addTarget:self action:@selector(otherLoginWayBtnClicked:) forControlEvents:(UIControlEventTouchUpInside)];
                         [customAreaView addSubview:button];
                    };
                    baseUIConfigure.clAppPrivacyNormalDesTextFirst = @"营销通行证\n畅通SGMW服务，在众多产品中直接使用\n免去重复注册，重复登录的步骤\n";
                    baseUIConfigure.clAppPrivacyLineSpacing = @(3.0);
                    
                    //layout 布局
                    CLOrientationLayOut * clOrientationLayOutPortrait = [CLOrientationLayOut new];
                    clOrientationLayOutPortrait.clLayoutLogoWidth = @(80 * screenScale);
                    clOrientationLayOutPortrait.clLayoutLogoHeight = @(80 * screenScale);
                    clOrientationLayOutPortrait.clLayoutLogoCenterX = @(0);
                    clOrientationLayOutPortrait.clLayoutLogoCenterY = @(-170*screenScale);
                    clOrientationLayOutPortrait.clLayoutPhoneCenterY = @(-100*screenScale);
                    clOrientationLayOutPortrait.clLayoutPhoneCenterX = @(0*screenScale);
                    clOrientationLayOutPortrait.clLayoutLoginBtnCenterY = @(30*screenScale);
                    clOrientationLayOutPortrait.clLayoutLoginBtnCenterX = @(0*screenScale);
                    clOrientationLayOutPortrait.clLayoutLoginBtnWidth = @(300*screenScale);
                    clOrientationLayOutPortrait.clLayoutLoginBtnHeight = @(50*screenScale);
                    clOrientationLayOutPortrait.clLayoutSloganCenterY= @(-70*screenScale);
                    clOrientationLayOutPortrait.clLayoutSloganCenterX = @(0*screenScale);
                    clOrientationLayOutPortrait.clLayoutShanYanSloganCenterY= @(50*screenScale);
                    clOrientationLayOutPortrait.clLayoutShanYanSloganCenterX = @(0*screenScale);
                    clOrientationLayOutPortrait.clLayoutAppPrivacyBottom = @(-30*screenScale);
                    clOrientationLayOutPortrait.clLayoutAppPrivacyCenterX= @(0*screenScale);
                    baseUIConfigure.clOrientationLayOutPortrait = clOrientationLayOutPortrait;

                    //闪验一键登录接口（将拉起授权页）
                    [CLShanYanSDKManager quickAuthLoginWithConfigure:baseUIConfigure openLoginAuthListener:^(CLCompleteResult * _Nonnull completeResult) {
                            // hide loading...
                            if (completeResult.error) {
                                //拉起授权页失败
                                NSLog(@"openLoginAuthListener:%@",completeResult.error.userInfo);
                                NSDictionary *dic = @{@"err":completeResult.message,@"code":[NSNumber numberWithInt:-1]};
                                NSString *json = [self changeToJson:dic];
                                CDVPluginResult* pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:json];
                                [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
                            }else{
                               //拉起授权页成功
                                NSLog(@"openLoginAuthListener:%@",completeResult.message);
                            }
                        } oneKeyLoginListener:^(CLCompleteResult * _Nonnull completeResult) {
                            if (completeResult.error) {
                                //一键登录失败
                                NSLog(@"oneKeyLoginListener:%@",completeResult.error.description);
                                
                                //提示：错误无需提示给用户，可以在用户无感知的状态下直接切换登录方式
                                if (completeResult.code == 1011){
                                    //用户取消登录（点返回）
                                    //处理建议：如无特殊需求可不做处理，仅作为交互状态回调，此时已经回到当前用户自己的页面
                                    //点击sdk自带的返回，无论是否设置手动销毁，授权页面都会强制关闭
                                    [CLShanYanSDKManager finishAuthControllerCompletion:^{
                                        NSDictionary *dic = @{@"err":completeResult.message,@"code":[NSNumber numberWithInt:2]};
                                        NSString *json = [self changeToJson:dic];
                                        CDVPluginResult* pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:json];
                                        [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
                                    }];
                                }  else{
                                    //处理建议：其他错误代码表示闪验通道无法继续，可以统一走开发者自己的其他登录方式，也可以对不同的错误单独处理
                                    //关闭授权页，如果授权页还未拉起，此调用不会关闭当前用户vc，即不执行任何代码
                                    [CLShanYanSDKManager finishAuthControllerCompletion:^{
                                        NSDictionary *dic = @{@"err":completeResult.message,@"code":[NSNumber numberWithInt:1]};
                                        NSString *json = [self changeToJson:dic];
                                        CDVPluginResult* pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:json];
                                        [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
                                    }];
                                }
                            }else{
                                //SDK成功获取到Token
                                /** token置换手机号
                                code
                                */
                                NSLog(@"oneKeyLoginListenerData:%@",completeResult.data);
                                [CLShanYanSDKManager finishAuthControllerCompletion:^{
                                    NSDictionary *dic = @{@"err":completeResult.message,@"code":[NSNumber numberWithInt:0],@"data":[completeResult.data objectForKey:@"token"]};
                                    NSString *json = [self changeToJson:dic];
                                    CDVPluginResult* pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:json];
                                    [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
                                }];
                            }
                        }];
                }
                else
                {
                    NSLog(@"%@",completeResult.message);
                    NSDictionary *dic = @{@"err":completeResult.message,@"code":[NSNumber numberWithInt:-1]};
                    NSString *json = [self changeToJson:dic];
                    CDVPluginResult* pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:json];
                    [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
                }
            }];
//            pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:@"成功美滋滋"];
//            [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
        }
        else{
            NSLog(@"%@",completeResult.error);
            NSDictionary *dic = @{@"err":completeResult.message,@"code":[NSNumber numberWithInt:-1]};
            NSString *json = [self changeToJson:dic];
            CDVPluginResult* pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:json];
            [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
        }
    }];

}

-(void)otherLoginWayBtnClicked:(UIButton*)btn {
    [CLShanYanSDKManager finishAuthControllerCompletion:^{
        NSDictionary *dic = @{@"err":@"用户选择其他登录方式",@"code":[NSNumber numberWithInt:1]};
        NSString *json = [self changeToJson:dic];
        CDVPluginResult* pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:json];
        [self.commandDelegate sendPluginResult:pluginResult callbackId:self->_command.callbackId];
    }];
}

//获取当前屏幕显示的viewcontroller
- (UIViewController *)getCurrentVC
{
    UIViewController *result = nil;
    
    UIWindow * window = [[UIApplication sharedApplication] keyWindow];
    if (window.windowLevel != UIWindowLevelNormal)
    {
        NSArray *windows = [[UIApplication sharedApplication] windows];
        for(UIWindow * tmpWin in windows)
        {
            if (tmpWin.windowLevel == UIWindowLevelNormal)
            {
                window = tmpWin;
                break;
            }
        }
    }
    
    UIView *frontView = [[window subviews] objectAtIndex:0];
    id nextResponder = [frontView nextResponder];
    
    if ([nextResponder isKindOfClass:[UIViewController class]])
        result = nextResponder;
    else
        result = window.rootViewController;
    
    return result;
}

-(NSString*)changeToJson:(NSDictionary*)dic{
    NSError *error = nil;
    NSData *jsonData = nil;
    if (!self) {
        return nil;
    }
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    [dic enumerateKeysAndObjectsUsingBlock:^(id  _Nonnull key, id  _Nonnull obj, BOOL * _Nonnull stop) {
        NSString *keyString = nil;
        NSString *valueString = nil;
        if ([key isKindOfClass:[NSString class]]) {
            keyString = key;
        }else{
            keyString = [NSString stringWithFormat:@"%@",key];
        }

        if ([obj isKindOfClass:[NSString class]]) {
            valueString = obj;
        }else{
            valueString = [NSString stringWithFormat:@"%@",obj];
        }

        [dict setObject:valueString forKey:keyString];
    }];
    jsonData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&error];
    if ([jsonData length] == 0 || error != nil) {
        return nil;
    }
    NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    return jsonString;
}

@end
