//
//  SsoLoginViewController.m
//  HWMSDKDemo
//
//

#import "SsoLoginViewController.h"
#import "SDKEnvConfig.h"
#import "LoginUtil.h"

@interface SsoLoginViewController ()
@property (weak, nonatomic) IBOutlet UIButton *getSsoUrlBtn;
@property (weak, nonatomic) IBOutlet UIButton *ssoLoginBtn;
@property (weak, nonatomic) IBOutlet UITextField *urlTextField;
@property (weak, nonatomic) IBOutlet UITextField *ssoDomainTextField;
@property (weak, nonatomic) IBOutlet UITextField *codeTextField;

@end

@implementation SsoLoginViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self initViews];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateSsoLoginInfo) name:@"updateSsoLoginInfo" object:nil];
    self.getSsoUrlBtn.accessibilityIdentifier = HWMSsoLoginGetSsoUrl;
    self.ssoLoginBtn.accessibilityIdentifier = HWMSsoLoginSsoLogin;
    self.urlTextField.accessibilityIdentifier = HWMSsoLoginUrl;
    self.ssoDomainTextField.accessibilityIdentifier = HWMSsoLoginSsoDomain;
    self.codeTextField.accessibilityIdentifier = HWMSsoLoginCode;
}

- (void)updateSsoLoginInfo {
    self.ssoDomainTextField.text = [SDKEnvConfig sharedInstance].domain;
    self.codeTextField.text = [SDKEnvConfig sharedInstance].code;
}

- (void)initViews {
    [self.getSsoUrlBtn setDefaultButton];
    [self.ssoLoginBtn setDefaultButton];
    [self updateSsoLoginInfo];
}

- (IBAction)getSsoUrlBtnClick:(UIButton *)sender {
    NSLog(@"点击获取了url");
    if (self.urlTextField.text.length == 0) {
        [UIUtil showMessage:@"请输入获取url域名"];
        return;
    }
    [[HWMBizSdk getBizOpenApi] getSsoAuthUrlWithDomain:self.urlTextField.text callback:^(NSError * _Nullable error, NSString * _Nullable ssoAuthUrl) {
        if (!error) {
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:ssoAuthUrl]];
        } else {
            [UIUtil showMessageWithError:error];
        }
    }];
}

- (IBAction)ssoLoginBtnClick:(UIButton *)sender {
    NSLog(@"点击sso登录");
    if (self.ssoDomainTextField.text.length == 0) {
        [UIUtil showMessage:@"请输入sso登录域名"];
        return;
    }
    if (self.codeTextField.text.length == 0) {
        [UIUtil showMessage:@"请输入sso登录code"];
        return;
    }
    HWMSSOLoginParam * ssoLoginParam = [[HWMSSOLoginParam alloc] init];
    ssoLoginParam.domain = self.ssoDomainTextField.text;
    ssoLoginParam.userTicket = self.codeTextField.text;
    ssoLoginParam.authServerType = HWMSDKAuthServerTypeOauth2;
    [[HWMSdk getOpenApi] loginBySSO:ssoLoginParam callback:^(NSError * _Nullable error, HWMLoginResult * _Nullable result) {
        if (error) {
            // 412100044:服务器降级，接入方收到该错误码可以继续调用入会接口离线入会
            [UIUtil showMessageWithError:error];
        } else {
            NSString * msg = [NSString stringWithFormat:@"登录成功\nuuid:%@\naccount:%@\nthirdAccount:%@", result.userUuid, result.account, result.thirdAccount];
            [UIUtil showMessage:msg vc:self];
        }
    }];
}

@end
