
//
//  BookConfViewController.m
//  HWMSDKDemo
//
//

#import "BookConfViewController.h"
#import "MediaTypeSwitchView.h"
#import "SelectDateView.h"
#import "DateUtil.h"
#import "CommonUtil.h"

static int marginLeft = 30;

@interface BookConfViewController ()

@property (nonatomic, strong) UIScrollView *scrollView;

@property (nonatomic, strong) UITextField *confSubjectTextField;
@property (nonatomic, strong) UITextField *customInfoTextField;
@property (nonatomic, strong) UITextField *startTimeTextField;
@property (nonatomic, strong) HWMUITextField *confDurationTextField;
@property (nonatomic, strong) HWMUITextField *concurrentParticipantsTextField;
@property (nonatomic, strong) UILabel *confIdTypeLabel;

@property (nonatomic, strong) UISwitch *personalIDSwitch;
@property (nonatomic, strong) HWMUITextField *pwdTextField;

@property (nonatomic, strong) UISwitch *generalPwdSwitch;
@property (nonatomic, strong) UISwitch *joinSwitch;
@property (nonatomic, strong) UITextView *memberView;

@property (nonatomic, strong) UILabel *joinConfRestrictionLabel;
@property (nonatomic, strong) UISwitch *recordSwitch;
@property (nonatomic, strong) UISwitch *autoRecordSwitch;
@property (nonatomic, strong) UISwitch *emailSwitch;
@property (nonatomic, strong) UISwitch *smsSwitch;
@property (nonatomic, strong) UISwitch *calendarSwitch;
@property (nonatomic, strong) UISwitch *autoInviteSwitch;
@property (nonatomic, strong) UISwitch *supportWatermarkSwitch;
@property (nonatomic, strong) HWMUITextField *timeZoneTextField;
@property (nonatomic, strong) UISwitch *vmrIdTypeSwitch;
@property (nonatomic, strong) UISwitch *waitingRoomSwitch;
@property (nonatomic, strong) UIView *vmrIdTypeView;
@property (nonatomic, strong) UISwitch *allowGuestStartConfSwitch;
@property (nonatomic, strong) UITextField *allowGuestStartConfTimeTextField;

@property (nonatomic, strong) UIButton *submitBtn;

@property (nonatomic, strong) NSArray <HWMContactSelectedModel *> *selectedMemebrs;
@property (nonatomic, strong) NSArray<HWMAttendeeInfo *> *attendee;

@property (nonatomic, strong) NSArray<HWMVmrInfoModel *> *vmrList;

@property (nonatomic, strong) SelectDateView *selectDateView;

@property (nonatomic, strong) MediaTypeSwitchView * selectView;
@property (nonatomic, assign) BOOL isEnableShareVmr;
@property (nonatomic, strong) UILabel *autoMuteLabel;
@property (nonatomic, strong) UILabel *hardTerminalAutoMuteLabel;
@property (nonatomic, strong) UISwitch *summarySwitch;
@property (nonatomic, strong) UISwitch *autoPublishSummarySwitch;
@property (nonatomic, strong) UISwitch *attendeesExcludeSelfSwitch;

@end

@implementation BookConfViewController

- (void)viewDidLoad {
    [self initData];
    [super viewDidLoad];
    self.title = self.isEditConf ? @"编辑会议" : @"预约会议";
}

- (void)initData {
    if ([HWMSdk hasInit]) {
        [[HWMBizSdk getBizOpenApi] getVmrInfoList:^(NSError * _Nullable error, HWMVmrInfoListModel * _Nullable result) {
            if (!error) {
                self.vmrList = result.vmrList;
                self.isEnableShareVmr = result.isEnableShareVmr;
                [self updateVmrInfoView];
            } else {
                [UIUtil showMessageWithError:error];
            }
        }];
    }
    if (self.confInfo.attendee) {
        self.attendee = self.confInfo.attendee.copy;
        NSMutableArray * selectedMemebrs = [NSMutableArray array];
        [self.confInfo.attendee enumerateObjectsUsingBlock:^(HWMAttendeeInfo * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            HWMContactSelectedModel * model = [[HWMContactSelectedModel alloc] init];
            model.number = obj.number;
            model.name = obj.name;
            model.email = obj.email;
            model.sms = obj.sms;
            model.accountId = obj.accountId;
            model.isHardTerminal = obj.isHardTerminal;
            [selectedMemebrs addObject:model];
        }];
        self.selectedMemebrs = selectedMemebrs;
    }
}

- (void)setupViews {
    [super setupViews];
    
    self.scrollView = [[UIScrollView alloc] init];
    [self.view addSubview:self.scrollView];
    [self.scrollView addTapAction:@selector(touchesBegan) target:self];
    [self.scrollView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.bottom.mas_equalTo(0);
        make.width.mas_equalTo(Screen_Width);
    }];
    
    // 会议主题
    self.confSubjectTextField = [self creatLabelAndTextFieldWithTopView:nil describe:@"会议主题" placeholder:@"请输入会议主题"];
    self.confSubjectTextField.text = self.confInfo.confSubject;
    self.confSubjectTextField.accessibilityIdentifier = HWMManageConfConfSubject;
    
    // 自定义信息
    self.customInfoTextField = [self creatLabelAndTextFieldWithTopView:self.confSubjectTextField describe:@"自定义信息" placeholder:@"请输入自定义信息"];
    self.customInfoTextField.text = self.confInfo.customInfo;
    self.customInfoTextField.accessibilityIdentifier = HWMManageConfConfCustomInfo;
    
    // 开始时间
    self.startTimeTextField = [self creatLabelAndTextFieldWithTopView:self.customInfoTextField describe:@"开始时间" placeholder:@"格式2020-08-16 12:00"];
    self.startTimeTextField.accessibilityIdentifier = HWMManageConfStartTime;
    NSTimeInterval timeInterval = self.confInfo.startTimeStamp ? : [NSDate date].timeIntervalSince1970;
    self.startTimeTextField.text = [DateUtil formatTimeStringWithTimeInterval:timeInterval isHasTimeZoneInterval:NO];
    [self.startTimeTextField addTapAction:@selector(selectStartTime) target:self];
    
    // 会议时长
    self.confDurationTextField =[self creatLabelAndTextFieldWithTopView:self.startTimeTextField describe:@"会议时长" placeholder:@"请输入会议时长"];
    self.confDurationTextField.accessibilityIdentifier = HWMManageConfConfDuration;
    self.confDurationTextField.keyboardType = UIKeyboardTypeNumberPad;
    if (self.confInfo.duration > 0) {
        self.confDurationTextField.text = [NSString stringWithFormat:@"%zd", self.confInfo.duration];
    }
    
    // 最大与会方数
    self.concurrentParticipantsTextField =[self creatLabelAndTextFieldWithTopView:self.confDurationTextField describe:@"最大与会人数" placeholder:@"默认0"];
    self.concurrentParticipantsTextField.accessibilityIdentifier = HWMManageConfConcurrentParticipant;
    self.concurrentParticipantsTextField.keyboardType = UIKeyboardTypeNumberPad;
    self.concurrentParticipantsTextField.text = [NSString stringWithFormat:@"%zd", self.confInfo.concurrentParticipants];
    
    // 会议类型
    MediaTypeSwitchView *selectView = [[MediaTypeSwitchView alloc] init];
    selectView.videoBtn.accessibilityIdentifier = HWMManageConfVideo;
    selectView.audioBtn.accessibilityIdentifier = HWMManageConfAudio;
    [self.scrollView addSubview:selectView];
    [selectView changeMediaSelectType:(SelectType)self.confInfo.confType];
    __weak __typeof(self) weakSelf = self;
    selectView.selectBlcok = ^(SelectType type) {
        __strong __typeof(weakSelf) strongSelf = weakSelf;
        strongSelf.confInfo.confType = (HWMOrderConfType)type;
    };
    [selectView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.concurrentParticipantsTextField.mas_bottom).mas_offset(20);
        make.left.mas_equalTo(marginLeft);
        make.height.mas_equalTo(50);
        make.right.mas_equalTo(self.confSubjectTextField);
    }];
    self.selectView = selectView;
    UIView * topView = selectView;
    
    // 与会者
    self.joinSwitch = [self creatLabelAndSwitchWithTopView:topView describe:@"是否携带与会者"];
    self.joinSwitch.accessibilityIdentifier = HWMManageConfJoinSwitch;
    [self.joinSwitch setOn:self.selectedMemebrs.count > 0];
    [self.joinSwitch addTarget:self action:@selector(joinSwitchChanged:) forControlEvents:(UIControlEventValueChanged)];
    
    // 允许入会
    UILabel *joinConfRestrictionLabel = [self newLabelWithTitle:@"允许入会"];
    [self.scrollView addSubview:joinConfRestrictionLabel];
    joinConfRestrictionLabel.userInteractionEnabled = YES;
    [joinConfRestrictionLabel addTapAction:@selector(selectJoinConfRestriction:) target:self];
    [joinConfRestrictionLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(marginLeft);
        make.right.mas_equalTo(self.confSubjectTextField);
        make.top.mas_equalTo(self.joinSwitch.mas_bottom).mas_offset(20);
    }];
    
    self.joinConfRestrictionLabel = [self newLabelWithTitle:@""];
    self.joinConfRestrictionLabel.accessibilityIdentifier = HWMManageConfJoinConfRestriction;
    [self.scrollView addSubview:self.joinConfRestrictionLabel];
    [self updateJoinConfRestrictionLabelText];
    [self.joinConfRestrictionLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(self.confSubjectTextField);
        make.centerY.mas_equalTo(joinConfRestrictionLabel);
    }];
    
    // 录制会议
    self.recordSwitch = [self creatLabelAndSwitchWithTopView:joinConfRestrictionLabel describe:@"打开会议录制"];
    self.recordSwitch.on = self.confInfo.isRecordOn;
    self.recordSwitch.accessibilityIdentifier = HWMManageConfRecordSwitch;
    
    // 自动录制会议
    self.autoRecordSwitch = [self creatLabelAndSwitchWithTopView:self.recordSwitch describe:@"打开自动录制会议"];
    self.autoRecordSwitch.on = self.confInfo.isAutoRecord;
    self.autoRecordSwitch.accessibilityIdentifier = HWMManageConfAutoRecordSwitch;
    
    // 发送邮件通知
    self.emailSwitch = [self creatLabelAndSwitchWithTopView:self.autoRecordSwitch describe:@"邮件通知"];
    self.emailSwitch.on = self.confInfo.isMailOn;
    [self.emailSwitch setEnabled:!(self.isEditConf && self.confInfo.isMailOn)];
    self.emailSwitch.accessibilityIdentifier = HWMManageConfEmailSwitch;
    
    // 发送短信通知
    self.smsSwitch = [self creatLabelAndSwitchWithTopView:self.emailSwitch describe:@"短信通知"];
    self.smsSwitch.on = self.confInfo.isSmsOn;
    [self.smsSwitch setEnabled:!(self.isEditConf && self.confInfo.isSmsOn)];
    self.smsSwitch.accessibilityIdentifier = HWMManageConfSmsSwitch;
    
    // 发送日历通知
    self.calendarSwitch = [self creatLabelAndSwitchWithTopView:self.smsSwitch describe:@"日历邮件通知"];
    self.calendarSwitch.on = self.confInfo.isEmailCalenderOn;
    [self.calendarSwitch setEnabled:!(self.isEditConf && self.confInfo.isEmailCalenderOn)];
    self.calendarSwitch.accessibilityIdentifier = HWMManageConfCalendarSwitch;
    
    self.autoInviteSwitch = [self creatLabelAndSwitchWithTopView:self.calendarSwitch describe:@"会议开始自动呼叫与会者"];
    [self.autoInviteSwitch setOn:YES];
    self.autoInviteSwitch.accessibilityIdentifier = HWMManageConfAutoInviteSwitch;
    
    self.supportWatermarkSwitch = [self creatLabelAndSwitchWithTopView:self.autoInviteSwitch describe:@"是否提供水印"];
    [self.supportWatermarkSwitch setOn:self.confInfo.supportWatermark];
    self.supportWatermarkSwitch.accessibilityIdentifier = HWMManageConfSupportWatermarkSwitch;
    
    self.waitingRoomSwitch = [self creatLabelAndSwitchWithTopView:self.supportWatermarkSwitch describe:@"开启等候室"];
    self.waitingRoomSwitch.on = NO;
    
    UILabel *autoMuteTitleLabel = [self newLabelWithTitle:@"个人客户端入会自动静音"];
    [self.scrollView addSubview:autoMuteTitleLabel];
    autoMuteTitleLabel.userInteractionEnabled = YES;
    [autoMuteTitleLabel addTapAction:@selector(selectAutoMuteMode:) target:self];
    [autoMuteTitleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(marginLeft);
        make.right.mas_equalTo(self.waitingRoomSwitch);
        make.top.mas_equalTo(self.waitingRoomSwitch.mas_bottom).mas_offset(20);
    }];
    
    self.autoMuteLabel = [self newLabelWithTitle:@""];
    [self.scrollView addSubview:self.autoMuteLabel];
    [self.autoMuteLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.right.mas_equalTo(autoMuteTitleLabel);
    }];
    
    UILabel *hardTerminalAutoMuteTitleLabel = [self newLabelWithTitle:@"会议室设备入会自动静音"];
    [self.scrollView addSubview:hardTerminalAutoMuteTitleLabel];
    hardTerminalAutoMuteTitleLabel.userInteractionEnabled = YES;
    [hardTerminalAutoMuteTitleLabel addTapAction:@selector(selectHardTerminalAutoMuteMode:) target:self];
    [hardTerminalAutoMuteTitleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(marginLeft);
        make.right.mas_equalTo(autoMuteTitleLabel);
        make.top.mas_equalTo(autoMuteTitleLabel.mas_bottom).mas_offset(20);
    }];
    
    self.hardTerminalAutoMuteLabel = [self newLabelWithTitle:@""];
    [self.scrollView addSubview:self.hardTerminalAutoMuteLabel];
    [self.hardTerminalAutoMuteLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.centerY.mas_equalTo(hardTerminalAutoMuteTitleLabel);
    }];
    [self updateAutoMuteLabelText];
    
    topView = self.hardTerminalAutoMuteLabel;
    
    self.allowGuestStartConfSwitch = [self creatLabelAndSwitchWithTopView:topView describe:@"允许来宾在主持人之前入会"];
    [self.allowGuestStartConfSwitch setOn:self.confInfo.allowGuestStartConf];
    self.allowGuestStartConfSwitch.accessibilityIdentifier = HWMManageConfAllowGuestStartConfSwitch;
    
    self.allowGuestStartConfTimeTextField =  [self creatLabelAndTextFieldWithTopView:self.allowGuestStartConfSwitch describe:@"可提前" placeholder:@"0:任意时间"];
    self.allowGuestStartConfTimeTextField.accessibilityIdentifier = HWMManageConfAllowGuestStartConfTime;
    self.timeZoneTextField.keyboardType = UIKeyboardTypeNumberPad;
    self.timeZoneTextField.accessibilityIdentifier = HWMManageConfTimeZone;
    self.allowGuestStartConfTimeTextField.text = [NSString stringWithFormat:@"%zd", self.confInfo.allowGuestStartConfTime];
    [self.allowGuestStartConfTimeTextField mas_updateConstraints:^(MASConstraintMaker *make) {
        make.width.mas_equalTo(Screen_Width - marginLeft - 200);
        make.left.mas_equalTo(self.scrollView).mas_offset(120);
    }];
    topView = self.allowGuestStartConfTimeTextField;
    
    UILabel *allowGuestStartConfLable = [self newLabelWithTitle:@"分钟入会"];
    [self.scrollView addSubview:allowGuestStartConfLable];
    [allowGuestStartConfLable mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.allowGuestStartConfTimeTextField.mas_right).offset(10);
        make.right.mas_equalTo(self.scrollView);
        make.height.mas_equalTo(30);
        make.centerY.mas_equalTo(self.allowGuestStartConfTimeTextField);
    }];
    
    self.timeZoneTextField =  [self creatLabelAndTextFieldWithTopView:topView describe:@"时区" placeholder:@"范围1-77。 56中国"];
    self.timeZoneTextField.keyboardType = UIKeyboardTypeNumberPad;
    if (self.isEditConf) {
        self.timeZoneTextField.text = [NSString stringWithFormat:@"%zd", self.confInfo.timeZone];
    }
    topView = self.timeZoneTextField;
    
    self.summarySwitch = [self creatLabelAndSwitchWithTopView:topView describe:@"录制时开启会议纪要"];
    self.summarySwitch.on = self.confInfo.defaultSummaryState;
    topView = self.summarySwitch;
    
    self.autoPublishSummarySwitch = [self creatLabelAndSwitchWithTopView:topView describe:@"自动发布会议纪要"];
    self.autoPublishSummarySwitch.on = self.confInfo.autoPublishSummary;
    topView = self.autoPublishSummarySwitch;
    
    // 预约会议时显示“去掉预定者开关”，编辑会议时隐藏该开关
    if (!self.isEditConf) {
        self.attendeesExcludeSelfSwitch = [self creatLabelAndSwitchWithTopView:topView describe:@"与会者列表是否去掉预定者"];
        self.attendeesExcludeSelfSwitch.on = self.confInfo.attendeesExcludeSelf;
        topView = self.attendeesExcludeSelfSwitch;
    }
    
    // 时区
    if (!self.isEditConf) {
        
        self.vmrIdTypeView = [[UIView alloc] init];
        self.vmrIdTypeView.hidden = YES;
        [self.scrollView addSubview:self.vmrIdTypeView];
        self.vmrIdTypeSwitch = [self creatLabelAndSwitchWithTopView:topView superView:self.vmrIdTypeView describe:@"云会议室是否随机会议id"];
        self.vmrIdTypeSwitch.accessibilityIdentifier = HWMManageConfVmrIdTypeSwitch;
        [self.vmrIdTypeView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(0);
            make.right.mas_equalTo(self.confSubjectTextField.mas_right);
            make.top.mas_equalTo(topView.mas_bottom);
            make.bottom.mas_equalTo(self.vmrIdTypeSwitch.mas_bottom);
        }];
        topView = self.vmrIdTypeView;
    }
    
    self.memberView = [[UITextView alloc] init];
    self.memberView.textColor = HexColor(0x333333);
    self.memberView.font = [UIFont systemFontOfSize:14];
    self.memberView.hidden = YES;
    self.memberView.accessibilityIdentifier = HWMManageConfMemberInfo;
    [self.scrollView addSubview:self.memberView];
    [self.memberView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(topView.mas_bottom).mas_offset(20);
        make.left.mas_equalTo(marginLeft);
        make.right.mas_equalTo(self.confSubjectTextField);
        make.height.mas_equalTo(50);
    }];
    
    UIButton *submitBtn = [UIButton newButtonWithTitle:self.isEditConf ? @"编辑会议" : @"预约会议"];
    submitBtn.accessibilityIdentifier = HWMManageConfSubmit;
    [self.scrollView addSubview:submitBtn];
    [submitBtn addTarget:self action:@selector(submitBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [submitBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(topView.mas_bottom).mas_offset(50);
        make.left.mas_equalTo(marginLeft);
        make.right.mas_equalTo(self.confSubjectTextField);
        make.height.mas_equalTo(50);
    }];
    self.submitBtn = submitBtn;
    [self.scrollView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.mas_equalTo(submitBtn.mas_bottom).mas_offset(150);
    }];
    
    if (self.selectedMemebrs.count > 0) {
        [self isShowMemberView:YES];
        [self refreshMemberView];
    }
}

- (void)updateVmrInfoView {
    UIView * topView = self.selectView;
    if (!self.isEditConf) {
        // 个人会议ID
        if (self.vmrList.count == 1 && !self.isEnableShareVmr) {
            self.personalIDSwitch = [self creatLabelAndSwitchWithTopView:topView describe:[NSString stringWithFormat:@"使用个人会议ID %@", self.vmrList[0].confId]];
            self.personalIDSwitch.accessibilityIdentifier = HWMManageConfPersonalIDSwitch;
            [self.personalIDSwitch setOn:self.confInfo.isNeedConfPwd];
            [self.personalIDSwitch addTarget:self action:@selector(personalIDSwitchChange:) forControlEvents:UIControlEventValueChanged];
            topView = self.personalIDSwitch;
        } else {
            // 会议ID类型
            UILabel *confIdTypeLabel = [self newLabelWithTitle:@"会议ID类型"];
            [self.scrollView addSubview:confIdTypeLabel];
            confIdTypeLabel.userInteractionEnabled = YES;
            [confIdTypeLabel addTapAction:@selector(selectConfIdType:) target:self];
            [confIdTypeLabel mas_makeConstraints:^(MASConstraintMaker *make) {
                make.left.mas_equalTo(topView);
                make.right.mas_equalTo(self.confSubjectTextField);
                make.top.mas_equalTo(topView.mas_bottom).mas_offset(20);
            }];
            
            self.confIdTypeLabel = [self newLabelWithTitle:@"随机会议ID"];
            self.confIdTypeLabel.accessibilityIdentifier = HWMManageConfConfIdTypeInfo;
            [self.scrollView addSubview:self.confIdTypeLabel];
            [self.confIdTypeLabel mas_makeConstraints:^(MASConstraintMaker *make) {
                make.right.mas_equalTo(self.confSubjectTextField);
                make.centerY.mas_equalTo(confIdTypeLabel);
            }];
            topView = confIdTypeLabel;
        }
        
        // 来宾密码
        self.generalPwdSwitch = [self creatLabelAndSwitchWithTopView:topView describe:@"来宾密码"];
        self.generalPwdSwitch.on = self.confInfo.isNeedConfPwd;
        self.generalPwdSwitch.accessibilityIdentifier = HWMManageConfGeneralPwdSwitch;
        topView = self.generalPwdSwitch;
    }

    if (self.isEditConf && self.confInfo.vmrId.length > 0) {
        UILabel * label = [[UILabel alloc] init];
        label.text = @"会议密码不能编辑";
        [self.scrollView addSubview:label];
        [label mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.mas_equalTo(topView.mas_bottom).mas_offset(20);
            make.left.mas_equalTo(marginLeft);
        }];
        topView = label;
    }
    
    // 密码输入
    self.pwdTextField = [self creatLabelAndTextFieldWithTopView:topView describe:@"会议密码" placeholder:@"会议密码"];
    self.pwdTextField.accessibilityIdentifier = HWMManageConfPwd;
    self.pwdTextField.keyboardType = UIKeyboardTypeNumberPad;
    [self.pwdTextField setEnabled:self.isEditConf ? self.confInfo.vmrId.length == 0 : !self.personalIDSwitch.isOn];
    self.pwdTextField.text = self.confInfo.guestPwd;
    topView = self.pwdTextField;
    
    [self.joinSwitch mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(topView.mas_bottom).offset(20);
        make.right.mas_equalTo(self.confSubjectTextField);
    }];
}

- (void)submitBtnClick {
    if (self.isEditConf) {
        [self handleEditConf];
    } else {
        [self handleBookConf];
    }
}

- (void)handleBookConf {
    [self updateConfInfo];
    HWMModifyVMRParam *vmrInfo = [self needModifyVmrInfoWithVmrId:self.confInfo.vmrId vmrIdType:self.confInfo.vmrIdType allowGuestStartConf:self.confInfo.allowGuestStartConf];
    if (vmrInfo) {
        [[HWMBizSdk getBizOpenApi] changeVmrInfo:vmrInfo callback:^(NSError * _Nullable error, id  _Nullable result) {
            if (error) {
                [UIUtil showMessageWithError:error];
            } else {
                [self bookConf];
            }
        }];
    } else {
        [self bookConf];
    }
}

- (void)bookConf {
    [[HWMBizSdk getBizOpenApi] bookConf:self.confInfo callback:^(NSError *_Nullable error, HWMConfDetail* _Nullable result) {
        NSLog(@"预约会议结果：%@", error);
        if (error) {
            [UIUtil showMessageWithError:error];
        } else {
            [UIUtil showMessage:[NSString stringWithFormat:@"预约会议成功 会议ID:%@ 会议标题:%@", result.confId, result.confSubject]];
        }
    }];
}

- (void)handleEditConf {
    [self updateConfInfo];
    HWMModifyVMRParam *vmrInfo = [self needModifyVmrInfoWithVmrId:self.confInfo.vmrId vmrIdType:self.confInfo.vmrIdType allowGuestStartConf:self.confInfo.allowGuestStartConf];
    if (vmrInfo) {
        [[HWMBizSdk getBizOpenApi] changeVmrInfo:vmrInfo callback:^(NSError * _Nullable error, id  _Nullable result) {
            if (error) {
                [UIUtil showMessageWithError:error];
            } else {
                [self editConf];
            }
        }];
    } else {
        [self editConf];
    }
}

- (void)editConf {
    [[HWMBizSdk getBizOpenApi] editConf:self.confInfo callback:^(NSError *_Nullable error, id _Nullable result) {
        NSLog(@"编辑会议结果：%@", error);
        if (error) {
            [UIUtil showMessageWithError:error];

        } else {
            [UIUtil showMessage:@"编辑会议成功"];
        }
    }];
}

- (void)updateConfInfo {
    self.confInfo.confSubject = self.confSubjectTextField.text;
    // 计算utc时间戳
    self.confInfo.startTimeStamp = [DateUtil formatTimeIntervalWithTime:self.startTimeTextField.text];
    self.confInfo.duration = [self.confDurationTextField.text integerValue];
    self.confInfo.isRecordOn = self.recordSwitch.isOn;
    self.confInfo.isAutoRecord = self.autoRecordSwitch.isOn;
    self.confInfo.isMailOn = self.emailSwitch.isOn;
    self.confInfo.isSmsOn = self.smsSwitch.isOn;
    self.confInfo.isEmailCalenderOn = self.calendarSwitch.isOn;
    self.confInfo.allowGuestStartConf = self.allowGuestStartConfSwitch.isOn;
    self.confInfo.allowGuestStartConfTime = [self.allowGuestStartConfTimeTextField.text integerValue];
    self.confInfo.timeZone = [self.timeZoneTextField.text integerValue];
    if (!self.isEditConf) {
        self.confInfo.isNeedConfPwd = self.generalPwdSwitch.isOn;
        self.confInfo.vmrIdType = [self getVmrIDType];
    }
    self.confInfo.guestPwd = self.pwdTextField.text;
    self.confInfo.attendee = self.joinSwitch.isOn ? self.attendee : nil;
    if ([self.confInfo.attendee count] > 0) {
        BOOL autoInvite = self.autoInviteSwitch.isOn;
        [self.confInfo.attendee enumerateObjectsUsingBlock:^(HWMAttendeeInfo * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            obj.isAutoInvite = autoInvite;
        }];
    }
    self.confInfo.isOpenWaitingRoom = self.waitingRoomSwitch.isOn;
    self.confInfo.customInfo = self.customInfoTextField.text;
    self.confInfo.supportWatermark = self.supportWatermarkSwitch.on;
    self.confInfo.concurrentParticipants = [self.concurrentParticipantsTextField.text integerValue];
    self.confInfo.defaultSummaryState = self.summarySwitch.isOn ? HWMSDKSummaryStateOpen : HWMSDKSummaryStateClose;
    self.confInfo.autoPublishSummary = self.autoPublishSummarySwitch.isOn;
    self.confInfo.attendeesExcludeSelf = self.attendeesExcludeSelfSwitch.isOn;
}

/// 如果是固定vmrid 且 “allowGuestStartConf”值变了需要在预约会议和编辑会议之前调用changeVmrInfo接口修改vmr信息，否则固定vmrid的预约会议和编辑会议“allowGuestStartConf”不生效
- (HWMModifyVMRParam *)needModifyVmrInfoWithVmrId:(NSString *)vmrId vmrIdType:(HWMVmrIdType)vmrIdType allowGuestStartConf:(BOOL)allowGuestStartConf {
    BOOL needCheck = vmrId && vmrId.length > 0 && vmrIdType == HWMVmrIdTypeFixed;
    NSLog(@"check need modifyVmr, vmrId:%@, vmrIdType:%zd", vmrId, vmrIdType);
    if (!needCheck) {
        return nil;
    }
    
    __block HWMVmrInfoModel *vmrInfo = nil;
    [self.vmrList enumerateObjectsUsingBlock:^(HWMVmrInfoModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if ([vmrId isEqualToString:obj.vmrId] && obj.allowGuestStartConf != allowGuestStartConf) {
            *stop = YES;
            vmrInfo = obj;
        }
    }];
    
    if (vmrInfo) {
        NSLog(@"new allowGuestStartConf:%d", vmrInfo.allowGuestStartConf);
        HWMModifyVMRParam *modifyVmrParam = [[HWMModifyVMRParam alloc] init];
        modifyVmrParam.vmrId = vmrInfo.vmrId;
        modifyVmrParam.vmrName = vmrInfo.name;
        modifyVmrParam.guestPwd = vmrInfo.chairmanPwd;
        modifyVmrParam.guestPwd = vmrInfo.guestPwd;
        modifyVmrParam.allowGuestStartConf = allowGuestStartConf;
        return modifyVmrParam;
    }

    return nil;
}

- (HWMVmrIdType)getVmrIDType {
   BOOL isVmrMeetingRoom = self.confInfo.vmrId.length > 0 && ![self.confInfo.vmrId isEqualToString:self.vmrList[0].vmrId];
   if (isVmrMeetingRoom) {
       return self.vmrIdTypeSwitch.isOn ? HWMVmrIdTypeRandom : HWMVmrIdTypeFixed;
   }
   return HWMVmrIdTypeFixed;
}

- (void)touchesBegan {
    [self endEdit];
}

- (void)endEdit {
    [self.view endEditing:YES];
}

- (void)selectStartTime {
    [self touchesBegan];
    [self.view addSubview:self.selectDateView];
    [self.selectDateView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(self.view);
    }];
    weakify(self)
    self.selectDateView.dateChange = ^(NSString * _Nonnull dataText) {
        strongify(self)
        self.startTimeTextField.text = dataText;
    };
}

- (void)joinSwitchChanged:(UISwitch *)swt {
    [self isShowMemberView:swt.isOn];
    if (swt.on) {
        __weak __typeof(self) weakSelf = self;
        __block NSMutableArray *numbers = [NSMutableArray array];
        [self.selectedMemebrs enumerateObjectsUsingBlock:^(HWMContactSelectedModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            HWMConfContactModel * model = [[HWMConfContactModel alloc] init];
            model.number = obj.number;
            model.accountId = obj.accountId;
            model.isHardTerminal = obj.isHardTerminal;
            [numbers addObject:model];
        }];
        
        [[HWMSdk getPrivateApi] openContactSelectPage:numbers scene:HWMSelectedContactBookConf completeHander:^(NSArray<HWMContactSelectedModel *> * _Nonnull result, NSError * _Nonnull error) {
            NSMutableArray * selectedMemebrs = [NSMutableArray arrayWithArray:self.selectedMemebrs];
            [selectedMemebrs addObjectsFromArray:result];
            weakSelf.selectedMemebrs = selectedMemebrs;
            [weakSelf refreshMemberView];
            [weakSelf updateConfInfoAttendee:result];
        }];
    }
}

- (void)isShowMemberView:(BOOL)show {
    self.memberView.hidden = !show;
    [self.submitBtn mas_remakeConstraints:^(MASConstraintMaker *make) {
        if(show) {
            make.top.mas_equalTo(self.memberView.mas_bottom).mas_offset(50);
        } else {
            make.top.mas_equalTo(self.memberView.mas_top).mas_offset(30);
        }
        make.left.mas_equalTo(marginLeft);
        make.right.mas_equalTo(self.confSubjectTextField);
        make.height.mas_equalTo(50);
    }];
}

- (void)refreshMemberView{
    __block NSMutableString *memberString = [[NSMutableString alloc] init];
    [self.selectedMemebrs enumerateObjectsUsingBlock:^(HWMContactSelectedModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        [memberString appendFormat:@"%@,", obj.name];
    }];
    self.memberView.text = memberString;
}

- (void)updateConfInfoAttendee:(NSArray <HWMContactSelectedModel *> *)selectedMemebrs {
    NSMutableArray * attendee = [NSMutableArray arrayWithArray:self.attendee];
    NSArray * newSelectAttendee = [HWMAttendeeInfo convertAttendeesFromContactList:selectedMemebrs];
    [attendee addObjectsFromArray:newSelectAttendee];
    self.attendee = attendee.copy;
}

- (void)personalIDSwitchChange:(UISwitch *)swt {
    HWMVmrInfoModel * model = self.vmrList[0];
    [self updatePwdTextFeild:swt.isOn ? self.vmrList[0].guestPwd : @""];
    self.confInfo.vmrId = swt.isOn ? model.vmrId : @"";
    [self.pwdTextField setEnabled:!swt.isOn];
    if (swt.isOn) {
        [self updateCallInRestrictionAndWaitingRoom:self.vmrList[0]];
    }
}

- (void)updateCallInRestrictionAndWaitingRoom:(HWMVmrInfoModel *)vmrInfo {
    self.confInfo.callInRestrictionType = (HWMJoinConfRestrictionType)vmrInfo.confAllowJoinUser;
    [self updateJoinConfRestrictionLabelText];
    self.confInfo.isOpenWaitingRoom = vmrInfo.isOpenWaitingRoom;
    [self.waitingRoomSwitch setOn:vmrInfo.isOpenWaitingRoom animated:YES];
}

- (void)selectConfIdType:(UITapGestureRecognizer *)tap {
    [self endEdit];
    if (self.vmrList.count == 1 && !self.isEnableShareVmr) {
        return;
    }
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"会议类型" message:@"" preferredStyle:UIAlertControllerStyleActionSheet];
    if (Is_Ipad) {
        alertController.popoverPresentationController.sourceView = self.scrollView;
        alertController.popoverPresentationController.sourceRect = tap.view.frame;
    }
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    [alertController addAction:cancelAction];
    
    [self.vmrList enumerateObjectsUsingBlock:^(HWMVmrInfoModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        UIAlertAction *action;
        if (idx == 0) {
            NSString * title = @"个人会议ID";
            action = [UIAlertAction actionWithTitle:title style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                [self changeVmrIdTypeViewHidden:YES];
                [self updateConfIdTypeLabelText:title confPwd:obj.guestPwd vmrId:obj.vmrId];
                [self updateCallInRestrictionAndWaitingRoom:obj];
            }];
            action.accessibilityIdentifier = HWMManageConfVmrIdTypePersonal;
        } else {
            NSString * title = [NSString stringWithFormat:@"%@(%zd)%@", obj.name, obj.maxParties, obj.confId];
            action = [UIAlertAction actionWithTitle:title style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                [self changeVmrIdTypeViewHidden:NO];
                [self updateConfIdTypeLabelText:title confPwd:obj.guestPwd vmrId:obj.vmrId];
                [self updateCallInRestrictionAndWaitingRoom:obj];
            }];
            action.accessibilityIdentifier = [NSString stringWithFormat:@"%@%zd", HWMManageConfVmrIdTypePrivate, idx];
        }
        [alertController addAction:action];
    }];
    
    NSString * title = @"随机会议ID";
    UIAlertAction *action = [UIAlertAction actionWithTitle:title style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self changeVmrIdTypeViewHidden:YES];
        [self updateConfIdTypeLabelText:title confPwd:@"" vmrId:@""];
    }];
    action.accessibilityIdentifier = HWMManageConfVmrIdTypeRandom;
    [alertController addAction:action];
    if (self.isEnableShareVmr) {
        UIAlertAction *action = [UIAlertAction actionWithTitle:@"共享云会议室" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [self changeVmrIdTypeViewHidden:YES];
            [self updateConfIdTypeLabelText:@"共享云会议室" confPwd:@"" vmrId:@""];
            self.confInfo.confResType = HWMSDKConfRestypeShareVmr;
            self.confInfo.vmrIdType = HWMVmrIdTypeRandom;
        }];
        action.accessibilityIdentifier = HWMManageConfVmrIdTypeShareVmr;
        [alertController addAction:action];
    }
    [self presentViewController:alertController animated:YES completion:nil];
}

- (void)updatePwdTextFeild:(NSString *)pwd {
    self.pwdTextField.text = pwd;
}

- (void)changeVmrIdTypeViewHidden:(BOOL)hidden {
    self.vmrIdTypeView.hidden = hidden;
}

- (void)updateConfIdTypeLabelText:(NSString *)text confPwd:(NSString *)pwd vmrId:(NSString *)vmrId {
    self.confIdTypeLabel.text = text;
    [self updatePwdTextFeild:pwd];
    self.confInfo.vmrId = vmrId;
}

- (void)selectJoinConfRestriction:(UITapGestureRecognizer *)tap {
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"允许入会" message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    if (Is_Ipad) {
        alertController.popoverPresentationController.sourceView = self.scrollView;
        alertController.popoverPresentationController.sourceRect = tap.view.frame;
    }
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    cancelAction.accessibilityIdentifier = HWMManageConfJoinConfRestrictionCancel;
    
    UIAlertAction *allAction = [UIAlertAction actionWithTitle:@"所有人" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        self.confInfo.callInRestrictionType = HWMJoinConfRestrictionAll;
        [self updateJoinConfRestrictionLabelText];
    }];
    allAction.accessibilityIdentifier = HWMManageConfJoinConfRestrictionAll;
    UIAlertAction *companyAction = [UIAlertAction actionWithTitle:@"仅企业内人员" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        self.confInfo.callInRestrictionType = HWMJoinConfRestrictionCompany;
        [self updateJoinConfRestrictionLabelText];
    }];
    companyAction.accessibilityIdentifier = HWMManageConfJoinConfRestrictionCompany;
    UIAlertAction *invitedAction = [UIAlertAction actionWithTitle:@"仅会议邀请人员" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        self.confInfo.callInRestrictionType = HWMJoinConfRestrictionInvited;
        [self updateJoinConfRestrictionLabelText];
    }];
    invitedAction.accessibilityIdentifier = HWMManageConfJoinConfRestrictionInvited;
    [alertController addAction:cancelAction];
    [alertController addAction:allAction];
    [alertController addAction:companyAction];
    [alertController addAction:invitedAction];
    [self presentViewController:alertController animated:YES completion:nil];
}

- (void)selectAutoMuteMode:(UITapGestureRecognizer *)tap {
    [self handleSelectAutoMuteMode:tap handler:^(HWMAutoMuteType type) {
        self.confInfo.autoMuteMode = type;
        [self updateAutoMuteLabelText];
    }];
}

- (void)selectHardTerminalAutoMuteMode:(UITapGestureRecognizer *)tap {
    [self handleSelectAutoMuteMode:tap handler:^(HWMAutoMuteType type) {
        self.confInfo.hardTerminalAutoMuteMode = type;
        [self updateAutoMuteLabelText];
    }];
}

- (void)handleSelectAutoMuteMode:(UITapGestureRecognizer *)tap handler:(void(^)(HWMAutoMuteType type))handler {
    UIAlertController *alertController = [CommonUtil createAutoMuteAlertController:handler];
    if (Is_Ipad) {
        alertController.popoverPresentationController.sourceView = self.scrollView;
        alertController.popoverPresentationController.sourceRect = tap.view.frame;
    }
    [self presentViewController:alertController animated:YES completion:nil];
}

- (void)updateAutoMuteLabelText {
    self.autoMuteLabel.text = [CommonUtil getTitleAutoMute:self.confInfo.autoMuteMode];
    self.hardTerminalAutoMuteLabel.text = [CommonUtil getTitleAutoMute:self.confInfo.hardTerminalAutoMuteMode];
}

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

-(SelectDateView *)selectDateView {
    if (!_selectDateView) {
        _selectDateView = [[SelectDateView alloc] init];
    }
    return _selectDateView;
}

- (HWMUITextField *)creatLabelAndTextFieldWithTopView:(UIView *)topView describe:(NSString *)describe placeholder:(NSString *)placeholder {
    UILabel *describeLabel = [self newLabelWithTitle:describe];
    [self.scrollView addSubview:describeLabel];
    [describeLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        if (topView) {
            make.top.mas_equalTo(topView.mas_bottom).mas_offset(20);
        } else {
            make.top.mas_equalTo(100);
        }
        make.left.mas_equalTo(marginLeft);
        make.height.mas_equalTo(30);
        make.width.mas_equalTo(100);
    }];
    
    HWMUITextField *textField = [[HWMUITextField alloc] init];
    [self.scrollView addSubview:textField];
    textField.placeholder = placeholder;
    [textField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.mas_equalTo(describeLabel);
        make.height.mas_equalTo(30);
        make.left.mas_equalTo(describeLabel.mas_right).mas_offset(20);
        make.width.mas_equalTo(Screen_Width - marginLeft - 140);
    }];
    [UIView addBottomLineWithView:textField parentView:self.scrollView];
    return textField;
}

- (UISwitch *)creatLabelAndSwitchWithTopView:(UIView *)topView describe:(NSString *)describe {
    return [self creatLabelAndSwitchWithTopView:topView superView:self.scrollView describe:describe];
}

- (UISwitch *)creatLabelAndSwitchWithTopView:(UIView *)topView superView:(UIView *)superView describe:(NSString *)describe {
    
    UISwitch *swt = [[UISwitch alloc] init];
    [superView addSubview:swt];
    [swt mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(topView.mas_bottom).mas_offset(20);
        make.right.mas_equalTo(self.confSubjectTextField);
    }];
    
    UILabel *describeLabel = [self newLabelWithTitle:describe];
    [superView addSubview:describeLabel];
    [describeLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.mas_equalTo(swt);
        make.left.mas_equalTo(superView.mas_left).mas_offset(marginLeft);
    }];
    return swt;
}

- (UILabel *)newLabelWithTitle:(NSString *)title {
    UILabel *label = [[UILabel alloc] init];
    label.text = title;
    label.font = [UIFont systemFontOfSize:16];
    label.textColor = HexColor(0x333333);
    return label;
}


- (void)updateJoinConfRestrictionLabelText {
    self.joinConfRestrictionLabel.text = [self getTitleAllowInComming:self.confInfo.callInRestrictionType];
}

- (NSString *)getTitleAllowInComming:(HWMJoinConfRestrictionType)callInRestrictionType
{
    switch (callInRestrictionType) {
        case HWMJoinConfRestrictionAll:
            return @"所有人";
            break;
        case HWMJoinConfRestrictionCompany:
            return @"仅企业内人员";
            break;
        case HWMJoinConfRestrictionInvited:
            return @"仅会议邀请人员";
            break;
        default:
            return @"";
            break;
    }
}

@end
