//
//  HWMInitViewController.m
//  HWMUISDKNativeDemo
//
//  Created by guomeng on 2020/10/24.
//  Copyright © 2020 Huawei Technologies Co. Ltd. All rights reserved.
//

#import "HWMInitViewController.h"
#import "HWMInputView.h"
#import <HWMUISDK/HWMUISDK.h>
#import "HWMSelectContactViewController.h"
#import "HWMAppKeyManager.h"
#import "HWMContactInfoModel.h"
#import "HWMToolBarConfigDataSource.h"
#import "HWMSettingConfigDataSource.h"
#import "HWMAttendeeManager.h"
#import "HWMDataModel.h"
#import "HWME2EEHandlerImpl.h"
#import "SDKEnvConfig.h"
@interface HWMInitViewController ()<HWMInputViewDelegate, HWMConfSettingHandler, HWMNotifyHandler, HWMContactUIHandler,HWMContactApiHandler, HWMConfUIHandler, HWMBizNotificationHandler, HWMIncomingAnswerHandler>

/// id
@property (nonatomic, strong) HWMInputView *inputView;
/// 日志天数
@property (nonatomic, strong) HWMInputView *logDaysInputView;
@property (nonatomic, assign) NSInteger logDays;
/// 日志级别
@property (nonatomic, strong) HWMInputView *logLevelInputView;
@property (nonatomic, assign) NSInteger logLevel;
/// 中国站点
@property (nonatomic, strong) NSButton *chBtn;
/// 国际
@property (nonatomic, strong) NSButton *inteBtn;
/// 中文
@property (nonatomic, strong) NSButton *zhBtn;
/// 英文
@property (nonatomic, strong) NSButton *enBtn;
/// 自定义语言按钮
@property (nonatomic, strong) NSButton *customBtn;
@property (nonatomic, strong) HWMInputView *langKeyView;

@property (nonatomic, assign) HWMSdkLanguageType language;
/// 同终端多应用登录
@property (nonatomic, strong) NSButton *multiAppLoginBtn;
@property (nonatomic, assign) BOOL isSupportMultiAppLogin;
/// 初始化按钮
@property (nonatomic, strong) NSButton *confirmBtn;
/// 站点类型
@property (nonatomic, assign) HWMSiteType siteType;
/// appKey
@property (nonatomic, copy) NSString *appId;

@property (nonatomic, strong) HWMSelectContactViewController *selectContactVC;

@end

@implementation HWMInitViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupUI];
    ///  默认估计站点
    self.siteType = HWMSiteTypeChina;
    self.language = HWMSdkLanguageTypeZH;

    self.appId = [HWMAppKeyManager shareInstance].appId;
    self.inputView.textField.stringValue = self.appId;
}

- (void)dealloc {
    HWMOpenSDKConfig *config = [HWMSdk getSdkConfig];
    [config unsubscribeGlobalNotificationHandler:self];
    [config unsubscribeBizNotificationHandler:self];
}

#pragma mark - UI
- (void)setupUI {
    [self.view addSubview:self.inputView];
    [self.view addSubview:self.logDaysInputView];
    [self.view addSubview:self.logLevelInputView];
    [self.view addSubview:self.chBtn];
    [self.view addSubview:self.inteBtn];
    [self.view addSubview:self.zhBtn];
    [self.view addSubview:self.enBtn];
    [self.view addSubview:self.customBtn];
    [self.view addSubview:self.langKeyView];
    [self.view addSubview:self.multiAppLoginBtn];
    [self.view addSubview:self.confirmBtn];

    [self.inputView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view).offset(70);
        make.centerX.equalTo(self.view);
        make.height.mas_equalTo(50);
        make.width.mas_equalTo(350);
    }];
    
    [self.logDaysInputView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.inputView.mas_bottom).offset(15);
        make.centerX.equalTo(self.inputView);
        make.height.mas_equalTo(50);
        make.width.mas_equalTo(350);
    }];
    
    [self.logLevelInputView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.logDaysInputView.mas_bottom).offset(15);
        make.centerX.equalTo(self.logDaysInputView);
        make.height.mas_equalTo(50);
        make.width.mas_equalTo(350);
    }];

    [self.chBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.equalTo(self.logLevelInputView.mas_leading);
        make.top.equalTo(self.logLevelInputView.mas_bottom).offset(15);
    }];

    [self.inteBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.equalTo(self.chBtn.mas_trailing).offset(15);
        make.top.equalTo(self.logLevelInputView.mas_bottom).offset(15);
    }];

    [self.zhBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.equalTo(self.inputView.mas_leading);
        make.top.equalTo(self.chBtn.mas_bottom).offset(30);
    }];

    [self.enBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.equalTo(self.zhBtn.mas_trailing).offset(15);
        make.top.equalTo(self.inteBtn.mas_bottom).offset(30);
    }];
    
    [self.customBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.equalTo(self.enBtn.mas_trailing).offset(15);
        make.top.equalTo(self.inteBtn.mas_bottom).offset(30);
    }];
    [self.langKeyView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.width.equalTo(self.customBtn);
        make.bottom.equalTo(self.customBtn.mas_top).offset(-2);
        make.height.mas_equalTo(30);
    }];
    
    [self.multiAppLoginBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.equalTo(self.zhBtn.mas_leading);
        make.top.equalTo(self.zhBtn.mas_bottom).offset(30);
    }];

    [self.confirmBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view);
        make.top.equalTo(self.zhBtn.mas_bottom).offset(80);
        make.height.mas_equalTo(35);
        make.width.mas_equalTo(250);
    }];
}

#pragma mark - Event

- (void)changeSite:(NSButton *)sender {
    if (self.inteBtn.state == NSControlStateValueOn) {
        self.siteType = HWMSiteTypeAP;
    } else {
        self.siteType = HWMSiteTypeChina;
    }
}

- (void)changeLanguage:(NSButton *)sender {
    if (self.zhBtn.state == NSControlStateValueOn) {
        self.language = HWMSdkLanguageTypeZH;
        self.langKeyView.hidden = YES;
    } else if (self.enBtn.state == NSControlStateValueOn){
        self.language = HWMSdkLanguageTypeEN;
        self.langKeyView.hidden = YES;
    } else {
        self.language = HWMSdkLanguageTypeCustomized;
        self.langKeyView.hidden = NO;
    }
}

- (void)supportMultiAppLogin:(NSButton *)sender {
    self.isSupportMultiAppLogin = sender.state == NSControlStateValueOn;
}

- (void)setAppLanguage {
    [HWMSdk setLanguage:self.language languageCode:self.langKeyView.textField.stringValue];
}

- (void)initSDK {
    if (self.appId.length == 0) {
        [HWMConsoleManager shareInstance].console = @"please input app id";
        return;
    }

    if ([HWMSdk hasInit]) {
        [HWMConsoleManager shareInstance].console = @"has init";
        return;
    }

    HWMOpenSDKConfig *config = [[HWMOpenSDKConfig alloc] init];
    config.appId = self.appId;
    config.siteType = self.siteType;
    config.logKeepDays = self.logDays;
    config.logLevel = (HWMUISDKLogLevel)self.logLevel;
    config.isSupportMultiAppLogin = self.isSupportMultiAppLogin;
    config.logPath = [[SDKEnvConfig sharedInstance] logPath];
    BOOL success = [HWMSdk initWithConfig:config];
    [HWMConsoleManager shareInstance].console = [NSString stringWithFormat:@"%@", [config yy_modelDescription]];
    [HWMConsoleManager shareInstance].console = [NSString stringWithFormat:@"%lu", self.siteType];
    if (success) {
        [HWMConsoleManager shareInstance].console = [NSString stringWithFormat:@"appId: %@", self.appId];
    } else {
        [HWMConsoleManager shareInstance].console = @"init failed";
    }

    [self setAppLanguage];
    [self configDelegate];
    [HWME2EEHandlerImpl shareInstance];

    // 关闭CA证书校验
    [[HWMSdk getPrivateApi] enableCAVerification:NO];
}

- (void)configDelegate {
    HWMOpenSDKConfig *config = [HWMSdk getSdkConfig];
    config.contactUIHandler = self;
    config.contactApiHandler = self;
    config.confSettingHandler = self;
    config.confUIHandler = self;
    [config subscribeGlobalNotificationHandler:self];
    [config subscribeBizNotificationHandler:self];
    config.incomingAnswerHandler = self;
    config.toolbarItemHandler = [HWMToolBarConfigDataSource shareInstance];
    config.settingHandler = [HWMSettingConfigDataSource sharedInstance];
}

#pragma mark - Delegate

- (void)textFieldDidChanged:(NSTextField *)field {
    if (field == self.inputView.textField) {
        self.appId = field.stringValue;
        if (self.appId.length > 0) {
            [HWMAppKeyManager shareInstance].appId = field.stringValue;
        }
    } else if (field == self.logDaysInputView.textField) {
        self.logDays = [field.stringValue integerValue];
    } else if (field == self.logLevelInputView.textField) {
        self.logLevel = [field.stringValue integerValue];
    }
}

- (BOOL)isOpenCameraIncoming {
    return YES;
}

- (BOOL)isOpenMicrophoneIncoming {
    return YES;
}

- (void)onCorpConfigNotify:(HWMCorpConfigInfo *)corpConfig {
    if (corpConfig.hasSMSPerm) {
        [HWMConsoleManager shareInstance].console = @"有发送短信通知权限";
    }
    if (corpConfig.hasRecordPerm) {
        [HWMConsoleManager shareInstance].console = @"有会议录制权限";
    }
    if (corpConfig.hasPstnPerm) {
        [HWMConsoleManager shareInstance].console = @"有PSTN外呼权限";
    }

    if (corpConfig.pstnNumber.length) {
        [HWMConsoleManager shareInstance].console = [NSString stringWithFormat:@"PSTN呼叫接入号:%@", corpConfig.pstnNumber];
    }
}

/// 被挤下线
- (void)onKickedOut {
    [HWMConsoleManager shareInstance].console = @"Your account has been used to log in elsewhere";
    NSAlert *alert = [[NSAlert alloc] init];
    alert.window.title = @"提示";
    alert.messageText = @"您的账号已在其他设备登录，当前设备已下线";
    alert.alertStyle = NSAlertStyleWarning;
    [alert setInformativeText:@""];
    [alert addButtonWithTitle:@"确定"];
    [alert runModal];
}

- (void)onUserCorpInfoNotify:(HWMUserCorpInfoNotifyType)type {
    if (type == HWMUserCorpInfoNotifyTypeUserDelete) {
        [HWMConsoleManager shareInstance].console = @"帐号已注销";
        [[HWMSdk getOpenApi] logout:^(NSError * _Nullable error, HWMLogoutResult * _Nullable result) {
        }];
    }
}

- (void)onLoginStateChangeNotify:(HWMLoginState)loginState {
    [HWMConsoleManager shareInstance].console = [NSString stringWithFormat:@"登录状态变化通知 onLoginStateChangeNotify, loginState: %ld", loginState];
}

- (void)onLoginError:(NSError *)error {
    // 登录过期，需重新调用登录接口
    [HWMConsoleManager shareInstance].console = @"Your account has been used to log in elsewhere";
}

/// 自定义联系人
- (void)openContactSelectWindow:(NSArray<HWMAttendeeInfo *> *)param scene:(HWMSelectedContactScene)scene completeHander:(void (^)(NSArray<HWMAttendeeInfo *> *_Nullable))handler {
    [HWMAttendeeManager logAttendees:param];

    HWMSelectContactViewController *contact = [[HWMSelectContactViewController alloc] init];
    [contact setSelectAttendeeInfoHandler:^(NSArray *attendees) {
        NSMutableArray *arr = @[].mutableCopy;
        for (HWMContactInfoModel *model in attendees) {
            HWMAttendeeInfo *info = [[HWMAttendeeInfo alloc] init];
            info.accountId = model.accountId;
            info.name = model.name;
            info.aliasCN = model.aliasCN;
            info.aliasEN = model.aliasEN;
            info.number = model.number;
            info.thirdUserId = model.thirdUserId;
            info.email = model.email;
            info.mute = model.mute;
            info.role = model.role;
            info.sms = model.sms;
            info.orgId = model.corpId;
            info.isAutoInvite = YES;
            [arr addObject:info];
        }
        if (handler) {
            handler(arr);
        }
    }];
    self.selectContactVC = contact;
    [self presentViewControllerAsModalWindow:contact];
}

/// 关闭窗口
- (void)closeContactSelectWindow {
    if (self.selectContactVC) {
        [self.selectContactVC.view.window close];
        [NSApp stopModal];
    }
}

/// 设置视频通话时 视频窗口最小化dock栏图标 以及共享情况下吸附窗口显示的图标
- (NSImage *)videoWindowDockIcon {
    return [NSImage imageNamed:@"iconMeeting"];
}

/// 会议基本信息
- (void)onMeetingInfoChanged:(HWMSDKMeetingInfoModel *)meetingInfo {
    [HWMConsoleManager shareInstance].console = [NSString stringWithFormat:@"会议基本信息更新通知 onMeetingInfoChanged: %@", [meetingInfo yy_modelDescription]];
}

/// 添加与会者结果通知
- (void)onAddAttendeeNotify:(HWMSDKAddAttendeeResultListModel *)resultList {
    [HWMConsoleManager shareInstance].console = [NSString stringWithFormat:@"添加与会者结果通知 onAddAttendeeNotify: %@", [resultList yy_modelDescription]];
}

/// 本地录制状态通知
- (void)onSelfLocalRecordStateNotify:(HWMUISDKLocalRecordStateInfoModel *)lcoalRecordStateInfo {
    [HWMConsoleManager shareInstance].console = [NSString stringWithFormat:@"本地录制状态通知 onSelfLocalRecordStateNotify: %@", [lcoalRecordStateInfo yy_modelDescription]];
}

/// 等候室列表更新通知
- (void)onWaitingListChanged:(NSArray<HWMAttendeeInfo *> *)waitingInfoList {
    [HWMConsoleManager shareInstance].console = [NSString stringWithFormat:@"等候室列表更新通知 onWaitingListChanged: %@", [waitingInfoList yy_modelDescription]];
}

/// 与会者列表更新通知
- (void)onAttendeeListChanged:(NSArray<HWMAttendeeInfo *> *)attendeeList {
    [HWMConsoleManager shareInstance].console = [NSString stringWithFormat:@"与会者列表更新通知 onAttendeeListChanged: %@", [attendeeList yy_modelDescription]];
}

/// 字幕状态变更通知
- (void)onSubtitleStateChanged:(BOOL)isOpen {
    [HWMConsoleManager shareInstance].console = [NSString stringWithFormat:@"字幕状态变更通知 onSubtitleStateChanged: %d", isOpen];
}

/// 等候室状态变更通知
- (void)onWaitingRoomStateChanged:(BOOL)isOpen {
    [HWMConsoleManager shareInstance].console = [NSString stringWithFormat:@"等候室状态变更通知 onWaitingRoomStateChanged: %d", isOpen];
}

/// 会议结束通知
- (void)onConfEndedNotify:(HWMUISDKConfEndInfoModel *)confEndInfo {
    [HWMConsoleManager shareInstance].console = [NSString stringWithFormat:@"会议结束通知 onConfEndedNotify: %@", [confEndInfo yy_modelDescription]];
}

- (void)onShareStateChanged:(HWMUISDKShareStateInfoModel *)shareStateInfo {
    [HWMConsoleManager shareInstance].console = [NSString stringWithFormat:@"共享状态上报 onShareState share type: %ld, state: %ld, nickname: %@", shareStateInfo.shareType, shareStateInfo.state, shareStateInfo.nickName];
}

- (void)onLoginTokenRefreshNotify:(HWMLoginStatusInfo *)loginInfo {
    [HWMConsoleManager shareInstance].console = [NSString stringWithFormat:@"login token: %@", loginInfo.loginToken];
}

- (void)onConfIncoming:(HWMConfIncomingInfo *)confIncomingInfo {
    NSString *info = [confIncomingInfo yy_modelDescription];
    [HWMConsoleManager shareInstance].console = [NSString stringWithFormat:@"conf incoming: %@", info];
}

- (void)queryUserDetailByNumbers:(NSArray<NSString *> *)numbers completionBlock:(void (^)(NSError * _Nullable, NSArray<HWMEnterpriseContact *> * _Nullable))completionBlock {
    NSArray *data = [self searchContactsWithKeys:numbers isNumber:YES];
    completionBlock(nil,data);
    NSString *info = [data yy_modelDescription];
    [HWMConsoleManager shareInstance].console = [NSString stringWithFormat:@"attendeeInfo: %@", info];
}

- (NSArray *)searchContactsWithKeys:(NSArray *)keys isNumber:(BOOL)isNumber{
    NSArray *contacts = [HWMDataModel sharedInstance].contacts.copy;
    NSMutableArray *arr = @[].mutableCopy;
    for (NSString *key in keys) {
        for (HWMEnterpriseContact *contact in contacts) {
            if (isNumber && [contact.number isEqualToString:key]) {
                [arr addObject:contact];
                break;
            } else if (!isNumber && [contact.account isEqualToString:key]) {
                [arr addObject:contact];
                break;
            }
        }
    }
    return arr;
}

- (void)onP2PConfRecord:(HWMP2PConfRecordInfoModel *)recordInfo {
    [HWMConsoleManager shareInstance].console = [NSString stringWithFormat:@"onP2PConfRecord:%@", [recordInfo yy_modelDescription]];
}

/// 个人角色是否是主持人变化通知
- (void)onSelfRoleChanged:(HWMConfRoleType)confRole {
    NSString *str = @"个人角色变更通知：";
    switch (confRole) {
        case HWMConfRoleTypeAttendee:
            str = [str stringByAppendingString:@"与会者"];
            break;
        case HWMConfRoleTypeAudience:
            str = [str stringByAppendingString:@"观众"];
            break;
        case HWMConfRoleTypeChairman:
            str = [str stringByAppendingString:@"主持人"];
            break;
        case HWMConfRoleTypeCohost:
            str = [str stringByAppendingString:@"联席主持人"];
            break;
        default:
            break;
    }
    [HWMConsoleManager shareInstance].console = str;
}

#pragma mark - Lazy

- (HWMInputView *)inputView {
    if (!_inputView) {
        _inputView = [[HWMInputView alloc] init];
        _inputView.title = @"AppId:";
        _inputView.placeholder = @"请输入appId";
        _inputView.delegate = self;
    }
    return _inputView;
}

-(HWMInputView *)logDaysInputView {
    if (!_logDaysInputView) {
        _logDaysInputView = [[HWMInputView alloc] init];
        _logDaysInputView.title = @"日志天数:";
        _logDaysInputView.placeholder = @"默认0，其它0-30";
        _logDaysInputView.delegate = self;
    }
    return _logDaysInputView;
}

-(HWMInputView *)logLevelInputView {
    if (!_logLevelInputView) {
        _logLevelInputView = [[HWMInputView alloc] init];
        _logLevelInputView.title = @"日志级别:";
        _logLevelInputView.placeholder = @"默认0，其它0-2";
        _logLevelInputView.delegate = self;
    }
    return _logLevelInputView;
}

- (NSButton *)chBtn {
    if (!_chBtn) {
        _chBtn = [[NSButton alloc] init];
        _chBtn.bordered = NO;
        _chBtn.font = [NSFont systemFontOfSize:12];
        _chBtn.bezelStyle = NSBezelStyleRegularSquare;
        _chBtn.state = NSControlStateValueOn;
        [_chBtn setButtonType:NSButtonTypeRadio];
        [_chBtn setTitle:@"中国站点"];
        _chBtn.target = self;
        _chBtn.action = @selector(changeSite:);
        _chBtn.tag = 0;
    }
    return _chBtn;
}

- (NSButton *)inteBtn {
    if (!_inteBtn) {
        _inteBtn = [[NSButton alloc] init];
        _inteBtn.bordered = NO;
        _inteBtn.font = [NSFont systemFontOfSize:12];
        [_inteBtn setBezelStyle:NSBezelStyleRegularSquare];
        [_inteBtn setButtonType:NSButtonTypeRadio];
        [_inteBtn setState:NSControlStateValueOff];
        [_inteBtn setTitle:@"国际站点"];
        _inteBtn.target = self;
        _inteBtn.action = @selector(changeSite:);
        _inteBtn.tag = 1;
    }
    return _inteBtn;
}

- (NSButton *)zhBtn {
    if (!_zhBtn) {
        _zhBtn = [[NSButton alloc] init];
        _zhBtn.bordered = NO;
        _zhBtn.font = [NSFont systemFontOfSize:12];
        _zhBtn.bezelStyle = NSBezelStyleRegularSquare;
        _zhBtn.state = NSControlStateValueOn;
        [_zhBtn setButtonType:NSButtonTypeRadio];
        [_zhBtn setTitle:@"中文（会中界面）"];
        _zhBtn.target = self;
        _zhBtn.action = @selector(changeLanguage:);
        _zhBtn.tag = 0;
    }
    return _zhBtn;
}

- (NSButton *)enBtn {
    if (!_enBtn) {
        _enBtn = [[NSButton alloc] init];
        _enBtn.bordered = NO;
        _enBtn.font = [NSFont systemFontOfSize:12];
        [_enBtn setBezelStyle:NSBezelStyleRegularSquare];
        [_enBtn setButtonType:NSButtonTypeRadio];
        [_enBtn setState:NSControlStateValueOff];
        [_enBtn setTitle:@"英文（会中界面）"];
        _enBtn.target = self;
        _enBtn.action = @selector(changeLanguage:);
        _enBtn.tag = 1;
    }
    return _enBtn;
}

- (NSButton *)customBtn {
    if (!_customBtn) {
        _customBtn = [[NSButton alloc] init];
        _customBtn.bordered = NO;
        _customBtn.font = [NSFont systemFontOfSize:12];
        [_customBtn setBezelStyle:NSBezelStyleRegularSquare];
        [_customBtn setButtonType:NSButtonTypeRadio];
        [_customBtn setState:NSControlStateValueOff];
        [_customBtn setTitle:@"自定义（会中界面）"];
        _customBtn.target = self;
        _customBtn.action = @selector(changeLanguage:);
        _customBtn.tag = 2;
    }
    return _customBtn;
}

- (HWMInputView *)langKeyView {
    if (!_langKeyView) {
        _langKeyView = [[HWMInputView alloc] init];
        _langKeyView.title = @"langKey:";
        _langKeyView.placeholder = @"langKey";
        _langKeyView.hidden = YES;
    }
    return _langKeyView;
}

- (NSButton *)confirmBtn {
    if (!_confirmBtn) {
        _confirmBtn = [NSButton buttonWithTitle:@"初始化" font:nil fontColor:[NSColor whiteColor] target:self action:@selector(initSDK)];
        _confirmBtn.layer.backgroundColor = [NSColor colorWithRGB:0x0D94FF].CGColor;
        _confirmBtn.layer.cornerRadius = 4.0;
        _confirmBtn.layer.masksToBounds = YES;
    }
    return _confirmBtn;
}

- (NSButton *)multiAppLoginBtn {
    if (!_multiAppLoginBtn) {
        _multiAppLoginBtn = [[NSButton alloc] init];
        _multiAppLoginBtn.bordered = NO;
        _multiAppLoginBtn.font = [NSFont systemFontOfSize:12];
        _multiAppLoginBtn.bezelStyle = NSBezelStyleRegularSquare;
        _multiAppLoginBtn.buttonType = NSButtonTypeSwitch;
        _multiAppLoginBtn.state = NSControlStateValueOff;
        _multiAppLoginBtn.title = @"isSupportMultiAppLogin";
        _multiAppLoginBtn.target = self;
        _multiAppLoginBtn.action = @selector(supportMultiAppLogin:);
    }
    return _multiAppLoginBtn;
}

- (HWMIncomingAnswerType)onIncomingCallAnswer {
    return HWMIncomingAnswerNormal;
}

@end
