//
//  APPIDLoginViewController.m
//  HWMSDKDemo
//
//  Created by l00465337 on 2020/8/10.
//  Copyright © 2020 HuaWei. All rights reserved.
//

#import "APPIDLoginViewController.h"
#import <HWMUISDK/HWMUISDK.h>
#import "UIUtil.h"
#import "LoginUtil.h"
#import "LoginInputView.h"
#import "SDKEnvConfig.h"
#import <AFNetworking/AFNetworking.h>
#import "SchemeLinkViewController.h"
#import "LoginManager.h"

static NSString * tokenUrl = @"https://api.meeting.huaweicloud.com/v2/usg/acs/auth/appauth";
static NSString * nonceURL = @"https://api.meeting.huaweicloud.com/v1/usg/acs/auth/portal-ref-nonce";


@interface APPIDLoginViewController ()

@property (nonatomic, weak) LoginInputView *appidView;
@property (nonatomic, weak) LoginInputView *signatureView;
@property (nonatomic, weak) LoginInputView *expireTimeView;
@property (nonatomic, weak) LoginInputView *nonceView;
@property (nonatomic, weak) LoginInputView *accountView;
@property (nonatomic, weak) LoginInputView *nameView;
@property (nonatomic, weak) LoginInputView *phoneView;
@property (nonatomic, weak) LoginInputView *emailView;
@property (nonatomic, weak) LoginInputView *corpIdView;
@property (nonatomic, weak) LoginInputView *deptCodeView;
@property (nonatomic, strong) UIScrollView *scrollView;

@end

@implementation APPIDLoginViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = self.isGetNonce ? @"获取nonce" : @"APPID登录";
    NSLog(@"%@", [self class]);
}

- (void)setupViews {
    [super setupViews];
    
    UIScrollView *scrollView = [[UIScrollView alloc] init];
    [scrollView setContentSize:CGSizeMake(0, 600)];
    [self.view addSubview:scrollView];
    [scrollView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.width.mas_equalTo(self.view);
        make.top.mas_equalTo(100);
        make.bottom.mas_equalTo(-100);
    }];
    [scrollView addTapAction:@selector(scrollViewTap) target:self];
    self.scrollView = scrollView;
    
    /// APPID
    LoginInputView *appidView = [[LoginInputView alloc] init];
    [scrollView addSubview:appidView];
    [appidView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.width.mas_equalTo(self.view);
        make.top.mas_equalTo(20);
        make.height.mas_equalTo(50);
    }];
    appidView.title = @"APPID\t:";
    appidView.placeholder = @"请到全局设置->设置AppId和Key";
    appidView.userInteractionEnabled = NO;
    self.appidView = appidView;
    
    // Signature
    LoginInputView *signatureView = [[LoginInputView alloc] init];
    [scrollView addSubview:signatureView];
    [signatureView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.width.mas_equalTo(self.view);
        make.top.mas_equalTo(appidView.mas_bottom);
        make.height.mas_equalTo(50);
    }];
    signatureView.title = @"Signature:";
    signatureView.placeholder = @"请输入Signature(必填*)";
    self.signatureView = signatureView;
    
    /// 过期时间
    LoginInputView *expireTimeView = [[LoginInputView alloc] init];
    [scrollView addSubview:expireTimeView];
    [expireTimeView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.width.mas_equalTo(self.view);
        make.top.mas_equalTo(signatureView.mas_bottom);
        make.height.mas_equalTo(50);
    }];
    expireTimeView.title = @"过期时间:";
    expireTimeView.placeholder = @"请输入过期时间(必填*)";
    self.expireTimeView = expireTimeView;
    self.expireTimeView.inputTextField.accessibilityIdentifier = HWMAppIDLoginExpireTime;
    
    /// 随机数
    LoginInputView *nonceView = [[LoginInputView alloc] init];
    [scrollView addSubview:nonceView];
    [nonceView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.width.mas_equalTo(self.view);
        make.top.mas_equalTo(expireTimeView.mas_bottom);
        make.height.mas_equalTo(50);
    }];
    nonceView.title = @"随机数\t:";
    nonceView.placeholder = @"请输入随机数(必填*)";
    self.nonceView = nonceView;
    
    /// 账号
    LoginInputView *accountView = [[LoginInputView alloc] init];
    [scrollView addSubview:accountView];
    [accountView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.width.mas_equalTo(self.view);
        make.top.mas_equalTo(nonceView.mas_bottom);
        make.height.mas_equalTo(50);
    }];
    accountView.title = @"账号\t:";
    accountView.placeholder = @"请输入账号(必填*)";
    self.accountView = accountView;
    self.accountView.inputTextField.accessibilityIdentifier = HWMAppIDLoginAccount;
    
    /// 昵称
    LoginInputView *nameView = [[LoginInputView alloc] init];
    [scrollView addSubview:nameView];
    [nameView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.width.mas_equalTo(self.view);
        make.top.mas_equalTo(accountView.mas_bottom);
        make.height.mas_equalTo(50);
    }];
    nameView.title = @"昵称\t:";
    nameView.placeholder = @"请输入昵称(选填)";
    self.nameView = nameView;
    self.nameView.inputTextField.accessibilityIdentifier = HWMAppIDLoginName;
    
    /// 手机号
    LoginInputView *phoneView = [[LoginInputView alloc] init];
    [scrollView addSubview:phoneView];
    [phoneView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.width.mas_equalTo(self.view);
        make.top.mas_equalTo(nameView.mas_bottom);
        make.height.mas_equalTo(50);
    }];
    phoneView.title = @"手机号\t:";
    phoneView.placeholder = @"请输入手机号(选填)";
    self.phoneView = phoneView;
    self.phoneView.inputTextField.accessibilityIdentifier = HWMAppIDLoginPhone;
    
    /// 邮箱
    LoginInputView *emailView = [[LoginInputView alloc] init];
    [scrollView addSubview:emailView];
    [emailView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.width.mas_equalTo(self.view);
        make.top.mas_equalTo(phoneView.mas_bottom);
        make.height.mas_equalTo(50);
    }];
    emailView.title = @"邮箱\t:";
    emailView.placeholder = @"请输入邮箱(选填)";
    self.emailView = emailView;
    self.emailView.inputTextField.accessibilityIdentifier = HWMAppIDLoginEmail;
    
    /// corpId
    LoginInputView *corpIdView = [[LoginInputView alloc] init];
    [scrollView addSubview:corpIdView];
    [corpIdView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.width.mas_equalTo(self.view);
        make.top.mas_equalTo(emailView.mas_bottom);
        make.height.mas_equalTo(50);
    }];
    corpIdView.title = @"corpId\t:";
    corpIdView.placeholder = @"请输入corpId(选填)";
    self.corpIdView = corpIdView;
    self.corpIdView.inputTextField.accessibilityIdentifier = HWMAppIDLoginCorpId;
    
    /// deptCode
    LoginInputView *deptCodeView = [[LoginInputView alloc] init];
    [scrollView addSubview:deptCodeView];
    [deptCodeView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.width.mas_equalTo(self.view);
        make.top.mas_equalTo(corpIdView.mas_bottom);
        make.height.mas_equalTo(50);
    }];
    deptCodeView.title = @"deptCode\t:";
    deptCodeView.placeholder = @"请输入deptCode(选填)";
    self.deptCodeView = deptCodeView;
    self.deptCodeView.inputTextField.accessibilityIdentifier = HWMAppIDLoginDeptCode;
    
    UIButton * loginBtn = [UIButton newButtonWithTitle:self.isGetNonce ? @"获取nonce" : @"登录"];
    loginBtn.accessibilityIdentifier = HWMAppIDLoginLogin;
    [self.view addSubview:loginBtn];
    [loginBtn addTarget:self action:@selector(loginClick) forControlEvents:UIControlEventTouchUpInside];
    [loginBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(scrollView.mas_bottom).mas_offset(20);
        make.left.mas_equalTo(50);
        make.height.mas_equalTo(50);
        make.right.mas_equalTo(-50);
    }];
    
    /**
     * 以下为 Mock 数据，供演示使用，具体接入时：
     * 1.调试演示 Demo 时，可以在客户端写死以下 Mock 字段，进行开发调试；
     * 2.正式版本，以下 Mock 字段均由服务端生成，尤其是 signature 的加密，是由服务端加密生成的；
     * 3.正式版本，需要接收的有效字段参见 HWMAppIDLoginParam ，appKey 需要保持在服务端，该字段不要下发到客户端；
     * 4.APPID 字段此处可缺省，在配置 HWMOpenSDKConfig 时配置的 APPID 是相同的。
     */
    // MOCK - Start
    appidView.content = [SDKEnvConfig sharedInstance].appId;
    expireTimeView.content = @"0";
    // MOCK - End
}

- (void)loginClick {
    [self.view endEditing:YES];
    if (![HWMSdk hasInit]) {
        [UIUtil showMessage:@"请先初始化"];
        return;
    }
    NSString *account = self.accountView.content;
    NSString *appId = self.appidView.content;
    NSString *signature = self.signatureView.content;
    NSString *expireTime = self.expireTimeView.content;
    NSString *nonce = self.nonceView.content;
    NSString *phone = self.phoneView.content;
    NSString *email = self.emailView.content;
    NSString *corpId = self.corpIdView.content;
    NSString *nickname = self.nameView.content;
    NSString *deptCode = self.deptCodeView.content;
    if (expireTime.length == 0) {
        [UIUtil showMessage:@"请输入过期时间"];
        return;
    }
    if (![self isAllNumber:expireTime]) {
        [UIUtil showMessage:@"过期时间只能是数字"];
        return;
    }
    
    if (![self isLettersAndNumbers:nonce]) {
        [UIUtil showMessage:@"随机数只能是数字和字母"];
        return;
    }
    
    if (account.length == 0) {
        [UIUtil showMessage:@"请输入账号"];
        return;
    }
    
    if (![self isAllNumber:corpId]) {
        [UIUtil showMessage:@"corpId只能是数字"];
        return;
    }
    [self showLoading];

    if (self.isGetNonce) {
        NSMutableDictionary * param = [NSMutableDictionary dictionary];
        [param setValue:[self getSafeString:appId] forKey:@"appId"];
        [param setValue:@(72) forKey:@"clientType"];
        [param setValue:[self getSafeString:corpId] forKey:@"corpId"];
        [param setValue:expireTime forKey:@"expireTime"];
        [param setValue:nonce forKey:@"nonce"];
        [param setValue:[self getSafeString:email] forKey:@"userEmail"];
        [param setValue:account forKey:@"userId"];
        [param setValue:[self getSafeString:nickname] forKey:@"userName"];
        [param setValue:[self getSafeString:phone] forKey:@"userPhone"];

        AFHTTPSessionManager *session = [AFHTTPSessionManager manager];
        session.requestSerializer = [AFJSONRequestSerializer serializer];
        session.responseSerializer = [AFJSONResponseSerializer serializer];
        [session.requestSerializer setValue:@"application/json;charset=utf-8" forHTTPHeaderField:@"Content-Type"];
        
        NSDictionary * headerParam = @{@"Authorization":[NSString stringWithFormat:@"HMAC-SHA256 signature=%@",signature]};
        
        [session POST:tokenUrl parameters:param headers:headerParam progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            [self getNonce:responseObject[@"accessToken"]];
 
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            [UIUtil showMessage:[NSString stringWithFormat:@"token获取失败 %zd", error.code]];
            [self hideLoading];
        }];
        return;
    }
    
    HWMAppIDLoginParam *appidInfo = [[HWMAppIDLoginParam alloc] init];
    appidInfo.thirdUserId     = account;
    appidInfo.expireTime = expireTime.integerValue;
    appidInfo.nonce      = nonce;
    appidInfo.userName   = nickname;
    appidInfo.signature  = signature;
    appidInfo.userPhone  = phone;
    appidInfo.userEmail  = email;
    appidInfo.corpId = corpId;
    appidInfo.deptCode = deptCode;
    [self appidLogin:appidInfo];
   
}

- (void)appidLogin:(HWMAppIDLoginParam *)appidInfo {
    [[HWMSdk getOpenApi] login:appidInfo callback:^(NSError * _Nullable error, HWMLoginResult * _Nullable result) {
        [self hideLoading];
        if (error == nil) {
            [[LoginManager sharedInstance] updateHasLogin:YES];
            NSString * msg = [NSString stringWithFormat:@"登录成功\nuuid:%@\naccount:%@\nthirdAccount:%@", result.userUuid, result.account, result.thirdAccount];
            [UIUtil showMessage:msg vc:self];
        }else{
            // 1.查找登录错误码
            // 412100044:服务器降级，接入方收到该错误码可以继续调用入会接口离线入会
            [UIUtil showMessageWithError:error];
        }
        
    }];
}


- (void)getNonce:(NSString *)token {
    AFHTTPSessionManager *session = [AFHTTPSessionManager manager];
    session.requestSerializer = [AFJSONRequestSerializer serializer];
    session.responseSerializer = [AFJSONResponseSerializer serializer];
    [session.requestSerializer setValue:@"application/json;charset=utf-8" forHTTPHeaderField:@"Content-Type"];
    
    NSDictionary * headerParam = @{@"X-Access-Token":token};
    
    [session POST:nonceURL parameters:nil headers:headerParam progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [self hideLoading];
        [self handleEventWithNonce:responseObject[@"nonce"]];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [self hideLoading];
        [UIUtil showMessage:[NSString stringWithFormat:@"nonce获取失败 %zd", error.code]];
    }];
}

- (void)handleEventWithNonce:(NSString *)nonce {
    if (self.isNonceLogin) {
        NSString * schemeStr = [NSString stringWithFormat:@"cloudlink://welinksoftclient/h5page?page=launch&nonce=%@", nonce];
        NSLog(@"schemeStr:%@", schemeStr);
        NSURL *schemUrl = [[NSURL alloc] initWithString:[schemeStr stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]]];
        [[UIApplication sharedApplication] openURL:schemUrl];
    } else {
        SchemeLinkViewController * vc = [[SchemeLinkViewController alloc] init];
        vc.nonce = nonce;
        [self.navigationController pushViewController:vc animated:YES];
    }
}

// 是否只有数字和字母
- (BOOL)isLettersAndNumbers:(NSString *)str {
    NSString * regex = @"^[A-Za-z0-9]*$";
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
    return [pred evaluateWithObject:str];
}

- (BOOL)isAllNumber:(NSString *)str {
    NSString *regex = @"[0-9]*";
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",regex];
    return [pred evaluateWithObject:str];
}

- (NSString *)getSafeString:(NSString * __nullable)str {
    return str.length > 0 ? str : @"";
}

- (void)scrollViewTap {
    [self.scrollView endEditing:YES];
}

@end
