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

#import "HWMBookConfViewController.h"
#import <HWMUISDK/HWMUISDK.h>
#import "HWMInputInfoTitleCell.h"
#import "HWMConfTypeSelectCell.h"
#import "HWMSwitchCell.h"
#import "HWMJoinConfLimitCell.h"
#import "NSViewController+HWMNavigation.h"
#import "HWMSelectContactViewController.h"
#import "HWMSDKTableView.h"
#import "HWMContactInfoModel.h"
#import "HWMSelectVrmViewController.h"

typedef NS_ENUM (NSInteger, HWMBookConfCellType) {
    HWMBookConfCellTypeSubject = 0,         // 会议主题
    HWMBookConfCellTypeStartTime,           // 开始时间
    HWMBookConfCellTypeDuration,            // 会议时长
    HWMBookConfCellTypeShareVmr,            // 启用共享云会议室
    HWMBookConfCellTypeVmr,                 // 启用云会议室
    HWMBookConfCellTypeFixed,               // 使用个人会议ID（是否固定会议ID）
    HWMBookConfCellTypeNeedAttendee,        // 是否需要携带与会者
    HWMBookConfCellTypeAttendeesExcludeSelf,// 与会者列表是否排除自己
    HWMBookConfCellTypeAutoInvite,          // 会议开始自动呼叫与会者
    HWMBookConfCellTypeAllowJoin,           // 允许入会
    HWMBookConfCellTypeAllowRecord,         // 允许录制
    HWMBookConfCellTypeAutoRecord,          // 自动录制
    HWMBookConfCellTypeMail,                // 邮件通知
    HWMBookConfCellTypeSms,                 // 短信通知
    HWMBookConfCellTypeEmailCalender,       // 日历邮件通知
    HWMBookConfCellTypeNeedPassword,        // 是否设置来宾密码
    HWMBookConfCellTypePassword,            // 来宾密码
    HWMBookConfCellTypeAllowStartConf,      // 允许来宾在主持人之前入会
    HWMBookConfCellTypeAllowStartConfTime,  // 可在会议开始前多久入会
    HWMBookConfCellTypeWaitingRoom,         // 是否开启等候室
    HWMBookConfCellTypeAutoMute,            // 个人客户端入会自动静音
    HWMBookConfCellTypeHardTerminalAutoMute,// 会议室设备入会自动静音
    HWMBookConfCellTypeSupportWatermark,    // 是否支持水印
    HWMBookConfCellTypeDefaultSummaryState, // 录制时开启会议纪要
    HWMBookConfCellTypeAutoPublishSummary,  // 自动发布会议纪要
    HWMBookConfCellTypeCustomInfo,          // 自定义信息
    HWMBookConfCellTypeParticipants,        // 最大与会人数
    HWMBookConfCellTypeTimeZone             // 时区
};

@interface HWMBookConfViewController ()<HWMSDKTableViewDataSourse, HWMSDKTableViewDelegate, HWMInputInfoTitleCellDelegate, HWMSwitchCellDelegate>

/// 标题
@property (nonatomic, copy) NSDictionary<NSNumber *, NSString *> *titleDic;
/// tableView
@property (nonatomic, strong) HWMSDKTableView *listView;
/// Vmr
@property (nonatomic, copy) NSArray<HWMVmrInfoModel *> *vmrList;
/// 是否支持共享vmr
@property (nonatomic, assign) BOOL isEnableShareVmr;
/// 会议参数model
@property (nonatomic, strong) HWMOrderConfParam *confParam;
/// 确定按钮
@property (nonatomic, strong) NSButton *confirmBtn;
/// 是否携带与会者
@property (nonatomic, assign) BOOL needAttendee;
/// 是否自动外呼
@property (nonatomic, assign) BOOL isAutoInvite;
/// 与会者
@property (nonatomic, strong) NSMutableArray <HWMAttendeeInfo *> *attenteeArr;
/// 当前使用的vmr信息
@property (nonatomic, strong) HWMVmrInfoModel *vmrInfoModel;
/// 是否使用共享vmr
@property (nonatomic, assign) BOOL useShareVmr;
/// 是否使用云会议室
@property (nonatomic, assign) BOOL useCloudVmr;
/// 是否使用固定ID
@property (nonatomic, assign) BOOL useFixedId;

@end

@implementation HWMBookConfViewController

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

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

#pragma mark - Data

- (void)setupData {
    self.titleDic = @{
        @(HWMBookConfCellTypeSubject) : @"会议主题",
        @(HWMBookConfCellTypeStartTime) : @"开始时间",
        @(HWMBookConfCellTypeDuration) : @"会议时长",
        @(HWMBookConfCellTypeShareVmr) : @"启用共享云会议室",
        @(HWMBookConfCellTypeVmr) : @"启用云会议室",
        @(HWMBookConfCellTypeFixed) : @"使用个人会议ID",
        @(HWMBookConfCellTypeNeedAttendee) : @"是否需要携带与会者",
        @(HWMBookConfCellTypeAttendeesExcludeSelf) : @"与会者列表是否排除自己",
        @(HWMBookConfCellTypeAutoInvite) : @"会议开始自动呼叫与会者",
        @(HWMBookConfCellTypeAllowJoin) : @"允许入会",
        @(HWMBookConfCellTypeAllowRecord) : @"允许录制",
        @(HWMBookConfCellTypeAutoRecord) : @"自动录制",
        @(HWMBookConfCellTypeMail) : @"邮件通知",
        @(HWMBookConfCellTypeSms) : @"短信通知",
        @(HWMBookConfCellTypeEmailCalender) : @"日历邮件通知",
        @(HWMBookConfCellTypeNeedPassword) : @"是否设置来宾密码",
        @(HWMBookConfCellTypePassword) : @"来宾密码",
        @(HWMBookConfCellTypeAllowStartConf) : @"允许来宾在主持人之前入会",
        @(HWMBookConfCellTypeAllowStartConfTime) : @"可在会议开始前多久入会",
        @(HWMBookConfCellTypeWaitingRoom) : @"是否开启等候室",
        @(HWMBookConfCellTypeAutoMute) : @"个人客户端入会自动静音",
        @(HWMBookConfCellTypeHardTerminalAutoMute) : @"会议室设备入会自动静音",
        @(HWMBookConfCellTypeSupportWatermark) : @"是否支持水印",
        @(HWMBookConfCellTypeDefaultSummaryState) : @"录制时开启会议纪要",
        @(HWMBookConfCellTypeAutoPublishSummary) : @"自动发布会议纪要",
        @(HWMBookConfCellTypeCustomInfo) : @"自定义信息",
        @(HWMBookConfCellTypeParticipants) : @"最大与会人数",
        @(HWMBookConfCellTypeTimeZone) : @"时区"
    };
}

- (void)getVmrList {
    if (![HWMSdk hasInit]) {
        return;
    }
    @weakify(self)
    [[HWMBizSdk getBizOpenApi] getVmrInfoList:^(NSError * _Nullable error, HWMVmrInfoListModel * _Nullable result) {
        @strongify(self)
        if (error) {
            [HWMConsoleManager shareInstance].error = error;
        } else {
            self.isEnableShareVmr = result.isEnableShareVmr;
            if (!self.isEnableShareVmr) {
                self.useShareVmr = NO;
            }
            
            NSMutableArray *array = [NSMutableArray arrayWithCapacity:0];
            for (HWMVmrInfoModel *vmrInfo in result.vmrs) {
                if (vmrInfo.usable) {
                    [array addObject:vmrInfo];
                }
            }
            self.vmrList = array;

            HWMVmrInfoModel *personVmr = self.vmrList.firstObject;

            BOOL hasVmrId = NO;
            if (self.detailModel) {
                for (HWMVmrInfoModel *vmrInfo in self.vmrList) {
                    if ([vmrInfo.vmrId isEqualToString:self.detailModel.vmrId]) {
                        hasVmrId = YES;
                        self.vmrInfoModel = vmrInfo;
                        break;
                    }
                }
            }

            if (hasVmrId && ![self.vmrInfoModel.vmrId isEqualToString:personVmr.vmrId]) {
                self.useCloudVmr = YES;
                self.confParam.vmrId = self.vmrInfoModel.vmrId;
            } else {
                self.vmrInfoModel = personVmr;
                self.useCloudVmr = NO;
                self.confParam.vmrId = self.useFixedId ? personVmr.vmrId : @"";
            }

            [self.listView reloadData];
        }
    }];
}

- (void)setDetailModel:(HWMConfDetail *)detailModel {
    _detailModel = detailModel;
    [self.attenteeArr addObjectsFromArray:self.detailModel.attendee];
    self.confParam.confId = self.detailModel.confId;
    self.confParam.confSubject = self.detailModel.confSubject;
    self.confParam.isSmsOn = self.detailModel.sendSms;
    self.confParam.isMailOn = self.detailModel.sendEmailNotify;
    self.confParam.isEmailCalenderOn = self.detailModel.sendCalendarNotify;
    self.confParam.startTimeStamp = self.detailModel.startTimeStamp;
    self.confParam.callInRestrictionType = self.detailModel.callInRestriction;
    self.confParam.isAutoRecord = self.detailModel.isAutoRecord;
    self.confParam.vmrId = self.detailModel.vmrId;
    self.confParam.duration = (self.detailModel.endTimeStamp - self.detailModel.startTimeStamp) / 60;
    self.confParam.timeZone = [detailModel.timeZone integerValue];
    self.useFixedId = self.detailModel.vmrConferenceId.length;
    self.confParam.attendee = self.attenteeArr;
    self.confParam.guestPwd = self.detailModel.generalPwd;
    self.confParam.noPassword = self.detailModel.guestFreePwd;
    self.confParam.allowGuestStartConf = self.detailModel.allowGuestStartConf;
    self.confParam.allowGuestStartConfTime = self.detailModel.allowGuestStartConfTime;
    self.confParam.isOpenWaitingRoom = self.detailModel.isOpenWaitingRoom;
    self.confParam.autoMuteMode = self.detailModel.autoMuteMode;
    self.confParam.hardTerminalAutoMuteMode = self.detailModel.hardTerminalAutoMuteMode;
    self.confParam.supportWatermark = self.detailModel.supportWatermark;
    self.confParam.defaultSummaryState = self.detailModel.defaultSummaryState;
    self.confParam.autoPublishSummary = self.detailModel.autoPublishSummary;
    self.confParam.customInfo = self.detailModel.customInfo;
    self.confParam.concurrentParticipants = self.detailModel.concurrentParticipants;
    self.needAttendee = self.attenteeArr.count > 1 ? YES : NO;

    [self.listView reloadData];
}

- (void)resetAttendee {
    if (self.detailModel) {
        return;
    }
    self.needAttendee = NO;
    [self.attenteeArr removeAllObjects];
    [self.listView reloadData];
}

#pragma mark - UI

- (void)setupUI {
    self.listView = [[HWMSDKTableView alloc] initTableViewClomuIdentifier:@"bookConf"];
    self.listView.delegate = self;
    self.listView.dataSource = self;
    [self.view addSubview:self.listView];

    NSString *title = self.detailModel ? @"编辑会议" : @"预约会议";
    self.confirmBtn = [NSButton buttonWithTitle:title font:nil fontColor:[NSColor whiteColor] target:self action:@selector(confirmBtnClick)];
    self.confirmBtn.layer.backgroundColor = [NSColor colorWithRGB:0x0D94FF].CGColor;
    self.confirmBtn.layer.cornerRadius = 4.0;
    self.confirmBtn.layer.masksToBounds = YES;
    [self.view addSubview:self.confirmBtn];

    [self.confirmBtn 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);
    }];

    [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.confirmBtn.mas_top).offset(-15);
    }];
}

/// 可输入cell
- (HWMInputInfoTitleCell *)inputInfoCell:(NSTableView *)tableView row:(NSInteger)row {
    HWMInputInfoTitleCell *cell = [HWMInputInfoTitleCell inputInfoTitleCell:tableView ower:self];
    cell.delegate = self;
    cell.index = row;
    cell.title = self.titleDic[@(row)];
    if (row == HWMBookConfCellTypeSubject) {
        // 会议主题
        cell.placeholder = @"请输入会议主题";
        cell.content = self.confParam.confSubject;
        cell.enabled = YES;
    } else if (row == HWMBookConfCellTypeStartTime) {
        // 开始时间
        cell.placeholder = @"格式：yyyy-MM-dd HH:mm";
        cell.content = [NSString timeStringFromTimeInterval:self.confParam.startTimeStamp];
        cell.enabled = YES;
    } else if (row == HWMBookConfCellTypeDuration) {
        // 会议时长
        cell.placeholder = @"请输入会议时长(单位：分钟)";
        if (self.confParam.duration > 0) {
            cell.content = [NSString stringWithFormat:@"%lu", self.confParam.duration];
        }
        cell.enabled = YES;
    } else if (row == HWMBookConfCellTypePassword) {
        // 来宾密码
        cell.placeholder = @"不填使用随机密码";
        cell.content = self.confParam.guestPwd;
        cell.enabled = !self.useFixedId && !self.confParam.noPassword;
    } else if (row == HWMBookConfCellTypeCustomInfo) {
        // 自定义信息
        cell.placeholder = @"请输入自定义信息";
        cell.content = self.confParam.customInfo;
    } else if (row == HWMBookConfCellTypeParticipants) {
        // 最大与会人数
        cell.placeholder = @"默认0";
        cell.content = [NSString stringWithFormat:@"%ld", self.confParam.concurrentParticipants];
        cell.formatterStyle = HWMFormatterStyleNumber;
    } else if (row == HWMBookConfCellTypeTimeZone) {
        // 时区
        cell.placeholder = @"默认当前时区";
        if (self.confParam.timeZone > 0) {
            cell.content = [NSString stringWithFormat:@"%ld", self.confParam.timeZone];
        }
        cell.formatterStyle = HWMFormatterStyleNumber;
    }
    return cell;
}

/// switch cell
- (HWMSwitchCell *)switchCell:(NSTableView *)tableView row:(NSInteger)row {
    HWMSwitchCell *cell = [HWMSwitchCell initSwitchCell:tableView ower:self];
    cell.index = row;
    cell.delegate = self;
    cell.title = self.titleDic[@(row)];
    
    if (row == HWMBookConfCellTypeShareVmr) {
        // 启用共享云会议室
        cell.state = self.useShareVmr;
        cell.enabled = !self.detailModel && self.isEnableShareVmr;
    } else if (row == HWMBookConfCellTypeVmr) {
        // 启用云会议室
        cell.state = self.useCloudVmr;
        cell.enabled = !self.detailModel && !self.useShareVmr && self.vmrList.count > 1;;
    } else if (row == HWMBookConfCellTypeFixed) {
        // 使用个人会议ID（是否固定会议ID）
        NSString *title = [NSString stringWithFormat:@"%@ %@", self.useCloudVmr ? @"使用云会议室ID" : @"使用个人会议ID", self.vmrInfoModel.confId.length ? self.vmrInfoModel.confId : @""];
        if (self.useShareVmr) {
            title = @"使用共享云会议室资源时，会议号会随机生成";
        }
        cell.title = title;
        cell.state = self.useFixedId;
        cell.enabled = !self.detailModel && !self.useShareVmr;
        HWMSwitchCell *pwdCell = [self.listView.listView viewAtColumn:0 row:HWMBookConfCellTypeNeedPassword makeIfNecessary:YES];
        HWMInputInfoTitleCell *pwdTextCell = [self.listView.listView viewAtColumn:0 row:HWMBookConfCellTypePassword makeIfNecessary:YES];
        if (pwdCell) {
            pwdCell.enabled = !self.useFixedId;
        }
        if (pwdTextCell) {
            pwdTextCell.enabled = !self.useFixedId && !self.confParam.noPassword;
        }
    } else if (row == HWMBookConfCellTypeNeedAttendee) {
        // 是否需要携带与会者
        cell.state = self.needAttendee;
        cell.enabled = YES;
    } else if (row == HWMBookConfCellTypeAttendeesExcludeSelf) {
        // 与会者列表是否排除自己
        cell.state = self.confParam.attendeesExcludeSelf;
        cell.enabled = YES;
    } else if (row == HWMBookConfCellTypeAutoInvite) {
        // 会议开始自动呼叫与会者
        cell.state = self.isAutoInvite;
        cell.enabled = YES;
    } else if (row == HWMBookConfCellTypeAllowRecord) {
        // 允许录制
        cell.state = self.confParam.isRecordOn;
        cell.enabled = YES;
    } else if (row == HWMBookConfCellTypeAutoRecord) {
        // 自动录制
        cell.state = self.confParam.isAutoRecord;
        cell.enabled = YES;
    } else if (row == HWMBookConfCellTypeMail) {
        // 邮件通知
        cell.state = self.confParam.isMailOn;
        cell.enabled = YES;
    } else if (row == HWMBookConfCellTypeSms) {
        // 短信通知
        cell.state = self.confParam.isSmsOn;
        cell.enabled = YES;
    } else if (row == HWMBookConfCellTypeEmailCalender) {
        // 日历邮件通知
        cell.state = self.confParam.isEmailCalenderOn;
        cell.enabled = YES;
    } else if (row == HWMBookConfCellTypeNeedPassword) {
        // 是否设置来宾密码
        cell.state = !self.confParam.noPassword;
        cell.enabled = !self.useFixedId;
    } else if (row == HWMBookConfCellTypeAllowStartConf) {
        // 允许来宾在主持人之前入会
        cell.state = self.confParam.allowGuestStartConf;
        cell.enabled = YES;
    } else if (row == HWMBookConfCellTypeWaitingRoom) {
        // 是否开启等候室
        cell.state = self.confParam.isOpenWaitingRoom;
        cell.enabled = YES;
    } else if (row == HWMBookConfCellTypeSupportWatermark) {
        // 是否支持水印
        cell.state = self.confParam.supportWatermark;
        cell.enabled = YES;
    } else if (row == HWMBookConfCellTypeDefaultSummaryState) {
        // 录制时开启会议纪要
        cell.state = self.confParam.defaultSummaryState;
        cell.enabled = YES;
    } else if (row == HWMBookConfCellTypeAutoPublishSummary) {
        // 自动发布会议纪要
        cell.state = self.confParam.autoPublishSummary;
        cell.enabled = YES;
    }
    return cell;
}

- (HWMJoinConfLimitCell *)menuCell:(NSTableView *)tableView row:(NSInteger)row {
    HWMJoinConfLimitCell *cell = [HWMJoinConfLimitCell joinConfLimitCell:tableView ower:self];
    cell.title = self.titleDic[@(row)];
    if (row == HWMBookConfCellTypeAllowJoin) {
        // 允许入会
        cell.menuTitles = @[@"所有人", @"仅企业内人员", @"仅会议邀请人员"];
        cell.enable = YES;
        cell.currentIndex = self.confParam.callInRestrictionType > 0 ? self.confParam.callInRestrictionType - 1 : 0;
        @weakify(self)
        [cell setSelectMenuItemHandler:^(NSInteger index,NSString *_Nullable title) {
            @strongify(self)
            self.confParam.callInRestrictionType = index > 0 ? index + 1 : 0;
        }];
    } else if (row == HWMBookConfCellTypeAllowStartConfTime) {
        // 可在会议开始前多久入会
        NSArray *titles = @[@"任意时间", @"5分钟", @"10分钟",@"15分钟",@"30分钟"];
        cell.menuTitles = titles;
        cell.enable = !self.useFixedId && self.confParam.allowGuestStartConf;
        NSInteger currentIndex = 0;
        if (self.confParam.allowGuestStartConf > 0) {
            currentIndex = [titles indexOfObject:[NSString stringWithFormat:@"%ld分钟",self.confParam.allowGuestStartConfTime]];
        }
        cell.currentIndex = currentIndex;
        @weakify(self)
        [cell setSelectMenuItemHandler:^(NSInteger index,NSString *_Nullable title) {
            @strongify(self)
            NSInteger time = index > 0 ? [[title substringToIndex:[title rangeOfString:@"分钟"].location] integerValue] : 0;
            
            self.confParam.allowGuestStartConfTime = time;
        }];
    } else if (row == HWMBookConfCellTypeAutoMute) {
        // 个人客户端入会自动静音
        cell.menuTitles = @[@"默认", @"开启", @"关闭"];
        cell.currentIndex = self.confParam.autoMuteMode;
        @weakify(self)
        [cell setSelectMenuItemHandler:^(NSInteger index,NSString *_Nullable title) {
            @strongify(self)
            self.confParam.autoMuteMode = (HWMAutoMuteType)index;
        }];
    } else if (row == HWMBookConfCellTypeHardTerminalAutoMute) {
        // 会议室设备入会自动静音
        cell.menuTitles = @[@"默认", @"开启", @"关闭"];
        cell.currentIndex = self.confParam.hardTerminalAutoMuteMode;
        @weakify(self)
        [cell setSelectMenuItemHandler:^(NSInteger index,NSString *_Nullable title) {
            @strongify(self)
            self.confParam.hardTerminalAutoMuteMode = (HWMAutoMuteType)index;
        }];
    }
    return cell;
}

#pragma mark - Delegate

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

- (NSView *)tableView:(NSTableView *)tableView viewForTableColumn:(NSTableColumn *)tableColumn row:(NSInteger)row {
    if (row == HWMBookConfCellTypeSubject ||
        row == HWMBookConfCellTypeStartTime ||
        row == HWMBookConfCellTypeDuration ||
        row == HWMBookConfCellTypePassword ||
        row == HWMBookConfCellTypeCustomInfo ||
        row == HWMBookConfCellTypeParticipants ||
        row == HWMBookConfCellTypeTimeZone) {
        return [self inputInfoCell:tableView row:row];
    } else if (row == HWMBookConfCellTypeAllowJoin ||
               row == HWMBookConfCellTypeAllowStartConfTime ||
               row == HWMBookConfCellTypeAutoMute ||
               row == HWMBookConfCellTypeHardTerminalAutoMute) {
        return [self menuCell:tableView row:row];
    } else {
        return [self switchCell:tableView row:row];
    }
}

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

- (void)inputInfoCellDidEdite:(NSString *)content index:(NSInteger)index {
    if (index == HWMBookConfCellTypeSubject) {
        // 会议主题
        self.confParam.confSubject = content;
    } else if (index == HWMBookConfCellTypeStartTime) {
        // 开始时间
        NSTimeInterval timeStamp = [NSString getTimeStampWithDateString:content];
        if (!isnan(timeStamp)) {
            self.confParam.startTimeStamp = timeStamp;
        } else {
            self.confParam.startTimeStamp = 0;
        }
    } else if (index == HWMBookConfCellTypeDuration) {
        // 会议时长
        self.confParam.duration = content.integerValue;
    } else if (index == HWMBookConfCellTypePassword) {
        // 来宾密码
        self.confParam.guestPwd = content;
    } else if (index == HWMBookConfCellTypeCustomInfo) {
        // 自定义信息
        self.confParam.customInfo = content;
    } else if (index == HWMBookConfCellTypeParticipants) {
        // 最大与会人数
        self.confParam.concurrentParticipants = [content integerValue];
    } else if (index == HWMBookConfCellTypeTimeZone) {
        // 时区
        self.confParam.timeZone = [content integerValue];
    }
}

- (void)switchStateChanged:(BOOL)state index:(NSInteger)index {
    HWMSwitchCell *cell = [self.listView.listView viewAtColumn:0 row:index makeIfNecessary:YES];
    switch (index) {
        case HWMBookConfCellTypeShareVmr: {
            // 启用共享云会议室
            if (state) {
                self.useCloudVmr = NO;
                self.useFixedId = NO;
                self.confParam.vmrId = @"";
            }
            self.useShareVmr = state;
            self.confParam.confResType = state ? HWMSDKConfRestypeShareVmr : HWMSDKConfRestypeDefault;
            [self.listView reloadData];
        }
            break;
        case HWMBookConfCellTypeVmr: {
            // 启用云会议室
            if (state) {
                cell.state = NO;
                HWMSelectVrmViewController *selectVrm = [[HWMSelectVrmViewController alloc] init];
                NSMutableArray *vmrArr = [NSMutableArray arrayWithArray:self.vmrList];
                [vmrArr removeObjectAtIndex:0];
                selectVrm.vmrArr = vmrArr;
                @weakify(self)
                [selectVrm setSelectVrmInfoHandler:^(HWMVmrInfoModel *_Nonnull infoModel) {
                    @strongify(self)
                    if (infoModel) {
                        cell.state = YES;
                        self.vmrInfoModel = infoModel;
                        self.useCloudVmr = YES;
                        self.confParam.vmrId = infoModel.vmrId;
                        self.confParam.callInRestrictionType = infoModel.confAllowJoinUser;
                        self.confParam.isOpenWaitingRoom = infoModel.isOpenWaitingRoom;
                        [self.listView reloadData];
                    }
                }];
                [self presentViewControllerAsModalWindow:selectVrm];
            } else {
                self.vmrInfoModel = self.vmrList.firstObject;
                self.useCloudVmr = NO;
                self.confParam.vmrId = self.useFixedId ? self.vmrInfoModel.vmrId : @"";
                [self.listView reloadData];
            }
        }
            break;
        case HWMBookConfCellTypeFixed: {
            // 使用个人会议ID（是否固定会议ID）
            if (self.vmrList.count == 0) {
                [HWMConsoleManager shareInstance].console = @"没有可用个人会议ID";
                cell.state = NO;
            } else {
                self.confParam.vmrId = state || self.useCloudVmr ? self.vmrInfoModel.vmrId : @"";
                self.useFixedId = state;
                HWMSwitchCell *pwdCell = [self.listView.listView viewAtColumn:0 row:HWMBookConfCellTypeNeedPassword makeIfNecessary:YES];
                HWMInputInfoTitleCell *pwdTextCell = [self.listView.listView viewAtColumn:0 row:HWMBookConfCellTypePassword makeIfNecessary:YES];
                pwdCell.enabled = !self.useFixedId;
                pwdTextCell.enabled = !self.useFixedId && !self.confParam.noPassword;
                [self updateAllowGuestStartTimeCell];
                if (state) {
                    [self updateConfAllowJoinUser];
                    [self updateOpenWaitingRoom];
                }
            }
        }
            break;
        case HWMBookConfCellTypeNeedAttendee: {
            // 是否需要携带与会者
            if (!state) {
                self.needAttendee = NO;
                [self.attenteeArr removeAllObjects];
                return;
            }
            cell.state = NO;
            HWMSelectContactViewController *contact = [[HWMSelectContactViewController alloc] init];
            @weakify(self)
            [contact setSelectAttendeeInfoHandler:^(NSArray *_Nullable attendees) {
                @strongify(self)
                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 = self.isAutoInvite;
                    [self.attenteeArr addObject:info];
                }
                if (attendees.count > 0) {
                    self.needAttendee = YES;
                    cell.state = YES;
                } else {
                    self.needAttendee = NO;
                }
            }];
            [self presentViewControllerAsModalWindow:contact];
        }
            break;
        case HWMBookConfCellTypeAttendeesExcludeSelf:
            // 与会者列表是否排除自己
            self.confParam.attendeesExcludeSelf = state;
            break;
        case HWMBookConfCellTypeAutoInvite: {
            // 会议开始自动呼叫与会者
            self.isAutoInvite = state;
            for (HWMAttendeeInfo *info in self.attenteeArr) {
                info.isAutoInvite = self.isAutoInvite;
            }
        }
            break;
        case HWMBookConfCellTypeAllowRecord:
            // 允许录制
            self.confParam.isRecordOn = state;
            break;
        case HWMBookConfCellTypeAutoRecord:
            // 自动录制
            self.confParam.isAutoRecord = state;
            break;
        case HWMBookConfCellTypeMail:
            // 邮件通知
            self.confParam.isMailOn = state;
            break;
        case HWMBookConfCellTypeSms:
            // 短信通知
            self.confParam.isSmsOn = state;
            break;
        case HWMBookConfCellTypeEmailCalender:
            // 日历邮件通知
            self.confParam.isEmailCalenderOn = state;
            break;
        case HWMBookConfCellTypeNeedPassword: {
            // 是否设置来宾密码
            self.confParam.noPassword = !state;
            HWMInputInfoTitleCell *pwdCell = [self.listView.listView viewAtColumn:0 row:HWMBookConfCellTypePassword makeIfNecessary:YES];
            if (pwdCell && [pwdCell isKindOfClass:[HWMInputInfoTitleCell class]]) {
                pwdCell.enabled = !self.useFixedId && !self.confParam.noPassword;
            }
        }
            break;
        case HWMBookConfCellTypeAllowStartConf: {
            // 允许来宾在主持人之前入会
            self.confParam.allowGuestStartConf = state;
            [self updateAllowGuestStartTimeCell];
        }
            break;
        case HWMBookConfCellTypeWaitingRoom:
            // 是否开启等候室
            self.confParam.isOpenWaitingRoom = state;
            break;
        case HWMBookConfCellTypeSupportWatermark:
            // 是否支持水印
            self.confParam.supportWatermark = state;
            break;
        case HWMBookConfCellTypeDefaultSummaryState:
            // 录制时开启会议纪要
            self.confParam.defaultSummaryState = state;
            break;
        case HWMBookConfCellTypeAutoPublishSummary:
            // 自动发布会议纪要
            self.confParam.autoPublishSummary = state;
            break;
        default:
            break;
    }
}

- (void)updateAllowGuestStartTimeCell {
    HWMJoinConfLimitCell *timeCell = [self.listView.listView viewAtColumn:0 row:HWMBookConfCellTypeAllowStartConfTime makeIfNecessary:YES];
    if (timeCell && [timeCell isKindOfClass:[HWMJoinConfLimitCell class]]) {
        timeCell.enable = self.confParam.allowGuestStartConf && !self.useFixedId;
        timeCell.currentIndex = 0;
        self.confParam.allowGuestStartConfTime = 0;
    }
}

- (void)updateConfAllowJoinUser {
    self.confParam.callInRestrictionType = _vmrInfoModel.confAllowJoinUser;
    HWMJoinConfLimitCell *confAllowJoinUserCell = [self.listView.listView viewAtColumn:0 row:HWMBookConfCellTypeAllowJoin makeIfNecessary:YES];
    if (confAllowJoinUserCell && [confAllowJoinUserCell isKindOfClass:[HWMJoinConfLimitCell class]]) {
        confAllowJoinUserCell.currentIndex = self.confParam.callInRestrictionType > 0 ? self.confParam.callInRestrictionType - 1 : 0;
    }
}

- (void)updateOpenWaitingRoom {
    self.confParam.isOpenWaitingRoom = _vmrInfoModel.isOpenWaitingRoom;
    HWMSwitchCell *waitingRoomCell = [self.listView.listView viewAtColumn:0 row:HWMBookConfCellTypeAllowJoin makeIfNecessary:YES];
    if (waitingRoomCell && [waitingRoomCell isKindOfClass:[HWMSwitchCell class]]) {
        waitingRoomCell.state = self.confParam.isOpenWaitingRoom;
        waitingRoomCell.enabled = YES;
    }
}

#pragma mark - Event

- (void)confirmBtnClick {
    if (self.detailModel) {
        [self editeConf];
    } else {
        [self orderConf];
    }
}

- (void)orderConf {
    if (![HWMSdk hasInit]) {
        [HWMConsoleManager shareInstance].console = @"no init";
        return;
    }

    if (self.confParam.confSubject.length == 0) {
        [HWMConsoleManager shareInstance].console = @"请输入会议主题";
        return;
    }

    if (self.confParam.startTimeStamp <= 0) {
        [HWMConsoleManager shareInstance].console = @"请输入开始时间";
        return;
    }

    if (self.confParam.duration <= 0) {
        [HWMConsoleManager shareInstance].console = @"请输入时长";
        return;
    }

    self.confParam.attendee = self.attenteeArr;
    self.confParam.vmrConfIdType = self.useFixedId ? HWMVmrConfIdTypeFixed : HWMVmrConfIdTypeRandom;
    
    @weakify(self)
    [self updateVmrInfo:self.confParam callback:^(NSError * _Nullable vmrError) {
        if (vmrError) {
            [HWMConsoleManager shareInstance].error = vmrError;
        } else {
            @strongify(self)
            [[HWMBizSdk getBizOpenApi] bookConf:self.confParam callback:^(NSError *_Nullable error, id _Nullable result) {
                if (error) {
                    [HWMConsoleManager shareInstance].error = error;
                } else {
                    if (result && [result isKindOfClass:[HWMConfDetail class]]) {
                        HWMConfDetail *confdetail = (HWMConfDetail *)result;
                        NSString *confId = confdetail.vmrConferenceId.length > 0 ? confdetail.vmrConferenceId : confdetail.confId;
                        [HWMConsoleManager shareInstance].console = [NSString stringWithFormat:@"order conf succeeded. confid is %@, confSubject = %@", confId, confdetail.confSubject];
                    }
                }
            }];
        }
    }];
}

- (void)editeConf {
    if (![HWMSdk hasInit]) {
        [HWMConsoleManager shareInstance].console = @"no init";
        return;
    }

    if (self.confParam.confSubject.length == 0) {
        [HWMConsoleManager shareInstance].console = @"请输入会议主题";
        return;
    }

    if (self.confParam.startTimeStamp <= 0) {
        [HWMConsoleManager shareInstance].console = @"请输入开始时间";
        return;
    }

    if (self.confParam.duration <= 0) {
        [HWMConsoleManager shareInstance].console = @"请输入时长";
        return;
    }

    self.confParam.vmrConfIdType = self.useFixedId ? HWMVmrConfIdTypeFixed : HWMVmrConfIdTypeRandom;
    
    @weakify(self)
    [self updateVmrInfo:self.confParam callback:^(NSError * _Nullable vmrError) {
        if (vmrError) {
            [HWMConsoleManager shareInstance].error = vmrError;
        } else {
            @strongify(self)
            [[HWMBizSdk getBizOpenApi] editConf: self.confParam callback:^(NSError *_Nullable error, id _Nullable result) {
                if (error) {
                    [HWMConsoleManager shareInstance].error = error;
                } else {
                    [HWMConsoleManager shareInstance].console = @"edit conf succeeded";
                    if (self.editConfSuccessHandler) {
                        self.editConfSuccessHandler();
                    }
                    [self.customNavigationController popViewControllerAnimated:YES];
                }
            }];
        }
    }];
    

}

- (void)updateVmrInfo:(HWMOrderConfParam *)confParam callback:(void(^)(NSError * _Nullable error))completion {
    if (confParam.vmrConfIdType == HWMVmrConfIdTypeFixed && confParam.vmrId.length > 0 && [self.vmrInfoModel.vmrId isEqualToString:confParam.vmrId]) {
        if (self.vmrInfoModel.allowGuestStartConf != confParam.allowGuestStartConf) {
            HWMModifyVMRParam *param = [[HWMModifyVMRParam alloc] init];
            param.allowGuestStartConf = confParam.allowGuestStartConf;
            param.guestPwd = _vmrInfoModel.guestPwd;
            param.vmrId = confParam.vmrId;
            param.vmrName = _vmrInfoModel.name;
            param.chairPwd = _vmrInfoModel.chairmanPwd;
            param.confAllowJoinUser = _vmrInfoModel.confAllowJoinUser;
            param.isOpenWaitingRoom = _vmrInfoModel.isOpenWaitingRoom;
            [[HWMBizSdk getBizOpenApi] changeVmrInfo:param callback:^(NSError * _Nullable error, id  _Nullable result) {
                if (completion) {
                    completion(error);
                }
            }];
        } else {
            if(completion) completion(nil);
        }
    } else {
        if(completion) completion(nil);
    }
}

#pragma mark - Lazy

- (HWMOrderConfParam *)confParam {
    if (!_confParam) {
        _confParam = [[HWMOrderConfParam alloc] init];
    }
    return _confParam;
}

- (NSMutableArray<HWMAttendeeInfo *> *)attenteeArr {
    if (!_attenteeArr) {
        _attenteeArr = [NSMutableArray array];
    }
    return _attenteeArr;
}

@end
