//
//  HWMLoginByNonceViewController.m
//  HWMUISDKNativeDemo
//
//  Created by guomeng on 2022/2/14.
//  Copyright © 2022 Huawei Technologies Co. Ltd. All rights reserved.
//

#import "HWMLoginByNonceViewController.h"
#import "HWMInputInfoTitleCell.h"
#import "HWMSDKTableView.h"
#import "HWMLoginInputInfoModel.h"
#import "HWMNonceManager.h"

@interface HWMLoginByNonceViewController ()<HWMSDKTableViewDataSourse, HWMSDKTableViewDelegate, HWMInputInfoTitleCellDelegate>
/// tableView
@property (nonatomic, strong) HWMSDKTableView *listView;
/// 按钮
@property (nonatomic, strong) NSButton *joinBtn;
/// 数据源
@property (nonatomic, strong) NSMutableArray *dataArr;

@property (nonatomic, copy) NSString *nickName;
@property (nonatomic, copy) NSString *userID;
@property (nonatomic, copy) NSString *nonce;
@property (nonatomic, copy) NSString *signature;

@end

@implementation HWMLoginByNonceViewController

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

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

#pragma mark - Data
- (void)setupData {
    //self.corpId = @"188503804";
    if (self.dataArr.count > 0) {
        return;
    }
    NSArray *data = @[
        @{ @"title": @"昵称:", @"place": @"请输入昵称（必填）", @"content": @"" },
        @{ @"title": @"用户ID:", @"place": @"请输入用户ID（必填）", @"content": @"" },
        @{ @"title": @"nonce:", @"place": @"请输入nonce（必填）", @"content": @"" },
        @{ @"title": @"signature:", @"place": @"请输入Signature（必填）", @"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.listView reloadData];
}

#pragma mark - UI
- (void)setupUI {
    self.listView = [[HWMSDKTableView alloc] initTableViewClomuIdentifier:@"loginNonceView"];
    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(-200);
    }];

    [self.view addSubview:self.joinBtn];
    [self.joinBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view);
        make.bottom.equalTo(self.listView.mas_bottom).offset(50);
        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 {
    HWMLoginInputInfoModel *model = self.dataArr[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 = model;
    cell.delegate = self;
    return cell;
}

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

- (void)inputInfoCellDidEdite:(NSString *)content index:(NSInteger)index {
    HWMLoginInputInfoModel *model = self.dataArr[index];
    model.content = content;
    if (index == 0) {
        self.nickName = content;
    } else if (index == 1) {
        self.userID = content;
    } else if (index == 2) {
        self.nonce = content;
    } else if (index == 3) {
        self.signature = content;
    }
}


#pragma mark - Event
- (void)loginByNonce {
    if (self.nickName.length == 0) {
        [HWMConsoleManager shareInstance].console = @"请输入昵称";
        return;
    }

    if (self.userID.length == 0) {
        [HWMConsoleManager shareInstance].console = @"请输入用户ID";
        return;
    }

    if (!HWMSafeString(self.signature)) {
        [HWMConsoleManager shareInstance].console = @"请输入Signature";
        return;
    }
    
    if (!HWMSafeString(self.nonce)) {
        [HWMConsoleManager shareInstance].console = @"请输入nonce";
        return;
    }
    
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"userName"] = self.nickName;
    params[@"userId"] = self.userID;
    params[@"nonce"] = self.nonce;
    params[@"signature"] = self.signature;
    
    [HWMNonceManager getNonceWithParams:params success:^(NSString * _Nonnull nonce) {
        if (nonce.length > 0) {
            NSString *baseUrl = @"cloudlink://welinksoftclient/h5page?page=launch";

            NSString *url = [NSString stringWithFormat:@"%@&nonce=%@", baseUrl,nonce];
            NSURL *schemeUrl = [[NSURL alloc] initWithString:[url stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]]];
            BOOL isOpen = [[NSWorkspace sharedWorkspace] openURL:schemeUrl];

            [HWMConsoleManager shareInstance].console = [NSString stringWithFormat:@"huawei cloud url : %@", url];
            if (isOpen) {
                [HWMConsoleManager shareInstance].console = @"已打开华为云会议";
            }else {
                [HWMConsoleManager shareInstance].console = @"无法打开华为云会议";
            }
        } else {
            [HWMConsoleManager shareInstance].console = @"获取的nonce不正确";
        }
    } failure:^(NSError * _Nonnull error) {
        [HWMConsoleManager shareInstance].error = error;
    }];
}


#pragma mark - Login
- (NSButton *)joinBtn {
    if (!_joinBtn) {
        _joinBtn = [NSButton buttonWithTitle:@"登录" font:nil fontColor:[NSColor whiteColor] target:self action:@selector(loginByNonce)];
        _joinBtn.layer.backgroundColor = [NSColor colorWithRGB:0x0D94FF].CGColor;
        _joinBtn.layer.cornerRadius = 4.0;
        _joinBtn.layer.masksToBounds = YES;
    }
    return _joinBtn;
}

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