//
//  HWMLoginBySSOViewController.m
//  HWMUISDKNativeDemo
//
//  Created by guomeng on 2021/8/17.
//  Copyright © 2021 Huawei Technologies Co. Ltd. All rights reserved.
//

#import "HWMLoginBySSOViewController.h"
#import "HWMInputView.h"
#import <HWMUISDK/HWMUISDK.h>

@interface HWMLoginBySSOViewController ()
/// 输入框
@property (nonatomic, strong) HWMInputView *domainView;
/// 密码
@property (nonatomic, strong) HWMInputView *codeView;
/// 获取code
@property (nonatomic, strong) NSButton *codeBtn;
/// 登录
@property (nonatomic, strong) NSButton *loginBtn;

@end

@implementation HWMLoginBySSOViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupUI];
    [self addObserver];
}

#pragma mark - UI
- (void)setupUI {
    [self.view addSubview:self.domainView];
    [self.view addSubview:self.codeView];
    [self.view addSubview:self.codeBtn];
    [self.view addSubview:self.loginBtn];

    [self.domainView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view).offset(100);
        make.centerX.equalTo(self.view);
        make.height.mas_equalTo(50);
        make.width.mas_equalTo(300);
    }];

    [self.codeView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.domainView.mas_bottom).offset(10);
        make.centerX.equalTo(self.view);
        make.height.mas_equalTo(50);
        make.width.mas_equalTo(300);
    }];

    [self.codeBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.equalTo(self.codeView.mas_leading);
        make.top.equalTo(self.codeView.mas_bottom).offset(60);
        make.height.mas_equalTo(35);
        make.width.mas_equalTo(100);
    }];

    [self.loginBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.trailing.equalTo(self.codeView.mas_trailing);
        make.top.equalTo(self.codeView.mas_bottom).offset(60);
        make.height.mas_equalTo(35);
        make.width.mas_equalTo(100);
    }];
}

#pragma mark - Event

- (void)addObserver {
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(getSSOUrl:) name:@"com.huawei.uisdkdemo.linkConf" object:nil];
}

- (void)getCode {
    if (![HWMSdk hasInit]) {
        [HWMConsoleManager shareInstance].console = @"no init";
        return;
    }
    NSString *domain = self.domainView.textField.stringValue;
    if (domain.length == 0) {
        [HWMConsoleManager shareInstance].console = @"please enter domain.";
        return;
    }
    [[HWMBizSdk getBizOpenApi] getSsoAuthUrl:domain callback:^(NSError *_Nullable error, id _Nullable result) {
        if (error == nil) {
            NSString *ossUrl = (NSString *)result;
            if (ossUrl.length > 0) {
                [[NSWorkspace sharedWorkspace] openURL:[NSURL URLWithString:ossUrl]];
            }
        } else {
            [HWMConsoleManager shareInstance].error = error;
        }
    }];
}

- (void)login {
    if (![HWMSdk hasInit]) {
        [HWMConsoleManager shareInstance].console = @"no init";
        return;
    }
    NSString *domain = self.domainView.textField.stringValue;
    if (domain.length == 0) {
        [HWMConsoleManager shareInstance].console = @"please enter domain.";
        return;
    }
    NSString *code = self.codeView.textField.stringValue;
    if (code.length == 0) {
        [HWMConsoleManager shareInstance].console = @"please enter code";
        return;
    }
    
    HWMSSOLoginParam *ssoParam = [[HWMSSOLoginParam alloc] init];
    ssoParam.domain = domain;
    ssoParam.code = code;
    ssoParam.authServerType = HWMOpenAuthServerTypeOauth2;
    [[HWMSdk getOpenApi] loginBySSO:ssoParam callback:^(NSError * _Nullable error, HWMLoginResult * _Nullable result) {
        if (error) {
            if (error.code == HWMSDKSdkLoginEErrMngFailed) {
                // 服务器降级，该错误码可以继续调用入会接口
            }
            [HWMConsoleManager shareInstance].error = error;
        }else {
            [HWMConsoleManager shareInstance].console = @"login successful.";
            [HWMConsoleManager shareInstance].console = [NSString stringWithFormat:@"login result: %@", result.description];
            [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"login"];
            [[NSUserDefaults standardUserDefaults] synchronize];
        }
    }];
}

- (void)getSSOUrl:(NSNotification *)noti {
    [self.view.window makeKeyAndOrderFront:nil];
    NSString *ssoUrl = (NSString *)noti.object;
    NSDictionary *params = [self getParamsWithUrl:ssoUrl];
    NSString *code = params[@"code"];
    self.codeView.textField.stringValue = code.length > 0 ? code : @"";
    [HWMConsoleManager shareInstance].console = [params yy_modelToJSONString];
}

- (NSDictionary *)getParamsWithUrl:(NSString *)url {
    NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
    NSArray<NSString *> *p1 = [url componentsSeparatedByString:@"?"];
    NSString *lastObject = [p1 lastObject];
    if (lastObject != nil) {
        for (NSString *param in [lastObject componentsSeparatedByString:@"&"]) {
            NSArray *elts = [param componentsSeparatedByString:@"="];
            if ([elts count] < 2) {
                continue;
            }
            [params setObject:[elts lastObject] forKey:[elts firstObject]];
        }
    }

    return params;
}

#pragma mark - Lazy

- (HWMInputView *)domainView {
    if (!_domainView) {
        _domainView = [[HWMInputView alloc] init];
        _domainView.title = @"企业域名:";
        _domainView.placeholder = @"请输入";
    }
    return _domainView;
}

- (HWMInputView *)codeView {
    if (!_codeView) {
        _codeView = [[HWMInputView alloc] init];
        _codeView.title = @"code:";
        _codeView.placeholder = @"请输入";
    }
    return _codeView;
}

- (NSButton *)loginBtn {
    if (!_loginBtn) {
        _loginBtn = [NSButton buttonWithTitle:@"SSO登录" font:nil fontColor:[NSColor whiteColor] target:self action:@selector(login)];
        _loginBtn.layer.backgroundColor = [NSColor colorWithRGB:0x0D94FF].CGColor;
        _loginBtn.layer.cornerRadius = 4.0;
        _loginBtn.layer.masksToBounds = YES;
    }
    return _loginBtn;
}

- (NSButton *)codeBtn {
    if (!_codeBtn) {
        _codeBtn = [NSButton buttonWithTitle:@"获取CODE" font:nil fontColor:[NSColor whiteColor] target:self action:@selector(getCode)];
        _codeBtn.layer.backgroundColor = [NSColor colorWithRGB:0x0D94FF].CGColor;
        _codeBtn.layer.cornerRadius = 4.0;
        _codeBtn.layer.masksToBounds = YES;
    }
    return _codeBtn;
}

@end
