//
//  HWMLoginIdViewController.m
//  HWMUISDKNativeDemo
//
//

#import "HWMLoginIdViewController.h"
#import "HWMInputInfoTitleCell.h"
#import "HWMLoginInputInfoModel.h"
#import <HWMUISDK/HWMUISDK.h>
#import "HWMAppIdLoginModel.h"
#import <CommonCrypto/CommonCrypto.h>
#import "HWMAppKeyManager.h"
#import "HWMSDKTableView.h"

@interface HWMLoginIdViewController ()<HWMSDKTableViewDataSourse, HWMSDKTableViewDelegate, HWMInputInfoTitleCellDelegate>
/// tableView
@property (nonatomic, strong) HWMSDKTableView *listView;
/// 按钮
@property (nonatomic, strong) NSButton *loginBtn;
/// 数据源
@property (nonatomic, strong) NSMutableArray *dataArr;
/// model
@property (nonatomic, strong) HWMAppIdLoginModel *loginParam;

@end

@implementation HWMLoginIdViewController

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

- (void)viewWillAppear {
    [super viewWillAppear];
    [self setupData];
}

#pragma mark - Data
- (void)setupData {
    if (self.dataArr.count > 0) {
        return;
    }
    NSString *appID = [HWMAppKeyManager shareInstance].appId;
    NSArray *data = @[@{ @"title": @"APPID:", @"place": @"请输入APPID（必填）", @"content":
                         appID},
                      @{ @"title": @"Signature:", @"place": @"请输入Signature（必填）", @"content": @""},
                      @{ @"title": @"过期时间:", @"place": @"请输入过期时间（必填）", @"content": @"0" },
                      @{ @"title": @"随机数(nonce):", @"place": @"请输入随机数（32~64位）（必填）", @"content": @"" },
                      @{ @"title": @"账号:", @"place": @"请输入账号（必填）", @"content": @"" },
                      @{ @"title": @"昵称:", @"place": @"请输入昵称（选填）", @"content": @"" },
                      @{ @"title": @"手机号:", @"place": @"请输入手机号（选填）", @"content": @"" },
                      @{ @"title": @"邮箱:", @"place": @"请输入邮箱（选填）", @"content": @"" },
                      @{ @"title": @"corpId:", @"place": @"请输入corpId（选填）", @"content": @"" },
                      @{ @"title": @"deptCode:", @"place": @"请输入deptCode（选填）", @"content": @"" }];

    for (NSDictionary *dic in data) {
        HWMLoginInputInfoModel *model = [[HWMLoginInputInfoModel alloc] init];
        model.title = dic[@"title"];
        model.placeholder = dic[@"place"];
        model.content = dic[@"content"];
        [self.dataArr addObject:model];
    }

    self.loginParam = [[HWMAppIdLoginModel alloc] init];
    self.loginParam.appId = appID;
    self.loginParam.expireTime = 0;
    self.loginParam.nonce = @"";
    [self.listView reloadData];
}

#pragma mark - UI
- (void)setupUI {
    
    self.listView = [[HWMSDKTableView alloc] initTableViewClomuIdentifier:@"loginIDView"];
    self.listView.delegate = self;
    self.listView.dataSource = self;
    [self.view addSubview:self.listView];
    [self.listView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.and.top.equalTo(self.view).offset(15);
        make.trailing.equalTo(self.view).offset(-15);
        make.bottom.equalTo(self.view).offset(-100);
    }];

    [self.view addSubview:self.loginBtn];
    [self.loginBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view);
        make.bottom.equalTo(self.view).offset(-20);
        make.height.mas_equalTo(35);
        make.width.mas_equalTo(250);
    }];
}

#pragma mark - Delegate

- (NSInteger)numberOfRowsInTableView:(NSTableView *)tableView {
    return self.dataArr.count;
}

- (NSView *)tableView:(NSTableView *)tableView viewForTableColumn:(NSTableColumn *)tableColumn row:(NSInteger)row {
    HWMInputInfoTitleCell *cell = [tableView makeViewWithIdentifier:NSStringFromClass([HWMInputInfoTitleCell class]) owner:self];
    if (!cell) {
        cell = [[HWMInputInfoTitleCell alloc] initWithFrame:NSMakeRect(0, 0, 200, 50)];
        cell.identifier = NSStringFromClass([HWMInputInfoTitleCell class]);
    }
    cell.index = row;
    cell.model = self.dataArr[row];
    cell.delegate = self;
    return cell;
}

- (CGFloat)tableView:(NSTableView *)tableView heightOfRow:(NSInteger)row {
    return 50.0;
}

- (void)inputInfoCellDidEdite:(NSString *)content index:(NSInteger)index {
    if (index == 0) {
        self.loginParam.appId = content;
        if (content.length > 0) {
            [HWMAppKeyManager shareInstance].appId = content;
        }
    } else if (index == 1) {
        self.loginParam.signature = content;
    } else if (index == 2) {
        if (content.length > 0) {
            if ([self isAllNumber:content]) {
                self.loginParam.expireTime = content.integerValue > 0 ? content.integerValue : -1;
            }
        } else {
            self.loginParam.expireTime = -1;
        }
    } else if (index == 3) {
        self.loginParam.nonce = content;
    } else if (index == 4) {
        self.loginParam.thirdUserId = content;
    } else if (index == 5) {
        self.loginParam.userName = content;
    } else if (index == 6) {
        self.loginParam.userPhone = content;
    } else if (index == 7) {
        self.loginParam.userEmail = content;
    } else if (index == 8) {
        self.loginParam.corpId = content;
    } else if (index == 9) {
        self.loginParam.deptCode = content;
    }
}

#pragma mark - Event
- (void)login {
    
    if (![HWMSdk hasInit]) {
        [HWMConsoleManager shareInstance].console = @"no init";
        return;
    }

    if (self.loginParam.appId.length == 0) {
        [HWMConsoleManager shareInstance].console = @"请输入APPID";
        return;
    }

    if (self.loginParam.signature.length == 0) {
        [HWMConsoleManager shareInstance].console = @"请输入signature";
        return;
    }

    if (self.loginParam.expireTime < 0) {
        [HWMConsoleManager shareInstance].console = @"请输入过期时间";
        return;
    }

    if (self.loginParam.nonce.length == 0) {
        [HWMConsoleManager shareInstance].console = @"请输入随机数(nonce)";
        return;
    }

    if (self.loginParam.thirdUserId.length == 0) {
        [HWMConsoleManager shareInstance].console = @"请输入账号";
        return;
    }

    HWMAppIDLoginParam *loginModel = [self convertFromLoginModel:self.loginParam];
    [[HWMSdk getOpenApi] login:loginModel callback:^(NSError *_Nullable error, HWMLoginResult *_Nullable result) {
        if (error) {
            [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];
        }
    }];
}


- (HWMAppIDLoginParam *)convertFromLoginModel:(HWMAppIdLoginModel*)model
{
    HWMAppIDLoginParam *appidModel = [HWMAppIDLoginParam new];
    appidModel.signature = model.signature;
    appidModel.thirdUserId = model.thirdUserId;
    appidModel.expireTime = model.expireTime;
    appidModel.nonce = model.nonce;
    appidModel.userName = model.userName;
    appidModel.userEmail = model.userEmail;
    appidModel.userPhone = model.userPhone;
    appidModel.corpId = model.corpId;
    appidModel.deptCode = model.deptCode;
    
    return appidModel;
}

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

#pragma mark - Login
- (NSButton *)loginBtn {
    if (!_loginBtn) {
        _loginBtn = [NSButton buttonWithTitle:@"登录" 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;
}

- (NSMutableArray *)dataArr {
    if (!_dataArr) {
        _dataArr = [NSMutableArray array];
    }
    return _dataArr;
}

@end
