//
//  HWMJoinConfByNonceViewController.m
//  HWMUISDKNativeDemo
//
//  Created by guomeng on 2021/6/11.
//  Copyright © 2021 Huawei Technologies Co. Ltd. All rights reserved.
//

#import "HWMJoinConfByNonceViewController.h"
#import "HWMInputInfoTitleCell.h"
#import <CommonCrypto/CommonCrypto.h>
#import "HWMAppKeyManager.h"
#import "HWMSDKTableView.h"
#import "HWMLoginInputInfoModel.h"
#import "HWMSwitchCell.h"
#import "HWMNonceManager.h"

#define HTTP_URL @"https://api.meeting.huaweicloud.com/"

@interface HWMJoinConfByNonceViewController ()<HWMSDKTableViewDataSourse, HWMSDKTableViewDelegate, HWMInputInfoTitleCellDelegate, HWMSwitchCellDelegate>
/// tableView
@property (nonatomic, strong) HWMSDKTableView *listView;
/// 按钮
@property (nonatomic, strong) NSButton *joinBtn;
/// 数据源
@property (nonatomic, strong) NSMutableArray *dataArr;
///
@property (nonatomic, assign) BOOL isCamOn;
@property (nonatomic, assign) BOOL isMicOn;
@property (nonatomic, copy) NSString *nickName;
@property (nonatomic, copy) NSString *userID;
@property (nonatomic, copy) NSString *confId;
@property (nonatomic, copy) NSString *password;
@property (nonatomic, copy) NSString *nonce;
@property (nonatomic, copy) NSString *corpId;
@property (nonatomic, copy) NSString *signature;

@end

@implementation HWMJoinConfByNonceViewController

- (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": @"会议ID:", @"place": @"请输入会议ID（必填）", @"content": @"" },
        @{ @"title": @"会议密码", @"place": @"请输入密码（选填）", @"content": @"" },
        @{ @"title": @"昵称:", @"place": @"请输入昵称（必填）", @"content": @"" },
        @{ @"title": @"用户ID:", @"place": @"请输入用户ID（必填）", @"content": @"" },
        @{ @"title": @"nonce:", @"place": @"请输入nonce（必填）", @"content": @"" },
        @{ @"title": @"signature:", @"place": @"请输入Signature（必填）", @"content": @"" },
        @{ @"title": @"麦克风:", @"place": @"", @"content": @"" },
        @{ @"title": @"摄像头:", @"place": @"", @"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.password = @"";
    [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.joinBtn];
    [self.joinBtn 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 {
    HWMLoginInputInfoModel *model = self.dataArr[row];

    if (row < 6) {
        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;
    }

    HWMSwitchCell *cell = [HWMSwitchCell initSwitchCell:tableView ower:self];
    cell.index = row;
    cell.delegate = self;
    cell.title = model.title;
    if (row == 6) {
        cell.state = self.isMicOn;
    } else if (row == 7){
        cell.state = self.isCamOn;
    }
    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.confId = content;
    } else if (index == 1) {
        self.password = content;
    } else if (index == 2){
        self.nickName = content;
    }else if (index == 3){
        self.userID = content;
    } else if (index == 4) {
        self.nonce = content;
    } else if (index == 5) {
        self.signature = content;
    }
}

- (void)switchStateChanged:(BOOL)state index:(NSInteger)index {
    if (index == 6) {
        self.isMicOn = state;
    } else if (index == 7){
        self.isCamOn = state;
    }
}

#pragma mark - Event
- (void)joinConf {
    if (!HWMSafeString(self.confId)) {
        [HWMConsoleManager shareInstance].console = @"请输入会议ID";
        return;
    }

    if (!HWMSafeString(self.nickName)) {
        [HWMConsoleManager shareInstance].console = @"请输入会议昵称";
        return;
    }
    
    if (!HWMSafeString(self.signature)) {
        [HWMConsoleManager shareInstance].console = @"请输入Signature";
        return;
    }
    
    if (!HWMSafeString(self.nonce)) {
        [HWMConsoleManager shareInstance].console = @"请输入nonce";
        return;
    }
    
    [self appAuth];
}

#pragma mark - HTTP

- (void)appAuth {
    
    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=LoginAndJoinConf&server_url=bmeeting.huaweicloud.com&port=8443&";

            NSString *openMic = self.isMicOn ? @"ture" : @"false";
            NSString *openCma = self.isCamOn ? @"ture" : @"false";
            NSString *signature = self.signature;

            NSString *url = [NSString stringWithFormat:@"%@&conf_id=%@&enter_code=%@&name=%@&open_mic=%@&open_camera=%@&signature=%@&appid=%@&userid=%@&nonce=%@&expiretime=0", baseUrl, self.confId, self.password, self.nickName, openMic, openCma, signature, [HWMAppKeyManager shareInstance].appId, self.userID, 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 {

        }
    } 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(joinConf)];
        _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
