//
//  ERTCPlayerView.m
//  ERTCDemo
//
//  Created by wangjinlong23 on 2022/5/13.
//


#import "ERTCPlayerView.h"
#import "ERTCVideoMeetingTopView.h"
#import "ERTCVideoMeetingBottomView.h"
#import "ERTCVideoMeetingMinePlayerView.h"
#import "ERTCVideoMeetingViewController.h"
#import "ERTCPlayerViewManager.h"
#import "ERTCVideoRemoteShareView.h"
#import "ERTCVideoMeetingManager.h"
#import "EZConfGlobalConfig.h"
#import "ERTCVideoChatMsgEditView.h"
#import "ERTCOtherMembersContentView.h"
#import "ERTCBigPlayerView.h"
#import "EZConfGlobalConfig.h"
#import "ERTCMembersNetworkInfoView.h"
#import "ERTCMoreTipView.h"
#import "ERTCShareTipView.h"

@interface ERTCPlayerView ()<UIGestureRecognizerDelegate,ERTCVideoMeetingTopViewDelegate,ERTCVideoMeetingBottomViewDelegate,ERTCVideoChatMsgEditViewProcotol,ERTCVideoRemoteShareViewDelegate,ERTCVideoMeetingMinePlayerViewProtocol,ERTCOtherMembersContentViewProtocol,ERTCMoreTipViewProtocol,ERTCShareTipViewProtocol>

@property (nonatomic, strong) NSMutableArray *selectUserIdArray;
@property (nonatomic, strong) NSString *screenShareUserId;
@property (nonatomic, strong) NSString *currentSelectUserId;

@property (nonatomic, strong) ERTCBigPlayerView *bigPlayerView;//当前屏幕大图

@property (nonatomic, strong) ERTCOtherMembersContentView *membersContentView;

@property (nonatomic, strong) UIView *oneView;
@property (nonatomic, strong) UIView *twoView;
@property (nonatomic, strong) UIView *threeView;
@property (nonatomic, strong) UIView *fourView;

@property (nonatomic, assign) BOOL canShowPreviewBtn;
@property (nonatomic, assign) BOOL canShowNextBtn;
@property (nonatomic, strong) UIButton *previousBtn;
@property (nonatomic, strong) UIButton *nextBtn;

@property (nonatomic, assign) BOOL isSharing; //是否在共享中
@property (nonatomic, strong) NSTimer *timer;
@property (nonatomic, assign) BOOL isHiddenTopBottomView;
@property (nonatomic, strong) UIView *bottomSafeView;
@property (nonatomic, weak) ERTCMoreTipView *moreTipView;
@property (nonatomic, weak) ERTCShareTipView *shareTipView;

@end

@implementation ERTCPlayerView

-(void)dealloc {
    NSLog(@"ERTCPlayerView dealloc");
}

-(void)viewWillAppear:(BOOL)animated {
//    [[ERTCPlayerViewManager sharedInstance].engine setLocalPreview:self.minePlayerView withRegionID:0];
    if (self.mineModel.isVideoAvailable) {
        [[ERTCPlayerViewManager sharedInstance].engine enableLocalVideo:YES];
        [[ERTCPlayerViewManager sharedInstance].engine setEnableLocalVideoStreamPublishing:YES];
        self.bigPlayerView.playInfoModel = self.mineModel;
        [self.bigPlayerView onMemberInfoUpdate:self.mineModel];
    }
}

- (void)viewDidAppear:(BOOL)animated {
    [[ERTCPlayerViewManager sharedInstance].engine setLocalPreview:self.minePlayerView withRegionID:0];
}
-(void)viewWillDisappear:(BOOL)animated {
    [[ERTCPlayerViewManager sharedInstance].engine enableLocalVideo:NO];
    [[ERTCPlayerViewManager sharedInstance].engine setLocalPreview:nil withRegionID:0];
}

-(void)viewDidTransitionToSize:(CGSize)size {
    [self.topView relayout:(self.safeAreaInsetsTop == 0)];
    [[ERTCPlayerViewManager sharedInstance].engine setLocalPreview:self.minePlayerView withRegionID:0];
    [self.bigPlayerView viewWillTransitionToSize:size];
}

#pragma mark -初始化视图
+ (instancetype)initWithAction_VCS_PlayerView {
    CGRect a = CGRectMake(0, 0, [[UIScreen mainScreen] bounds].size.width, [[UIScreen mainScreen] bounds].size.height);
    ERTCPlayerView *playView = [[ERTCPlayerView alloc] initWithFrame:a];
    return playView;
}

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        self.backgroundColor = [UIColor clearColor];
        self.selectUserIdArray = [NSMutableArray array];
        self.safeAreaInsetsTop = 0;
        self.safeAreaInsetsBottom = 0;
        self.isToLand = [UIScreen mainScreen].bounds.size.width > [UIScreen mainScreen].bounds.size.height;
        if (@available(iOS 11.0, *)) {
            self.safeAreaInsetsTop = [UIApplication sharedApplication].delegate.window.safeAreaInsets.top;
            self.safeAreaInsetsBottom = [UIApplication sharedApplication].delegate.window.safeAreaInsets.bottom;
        }
        
        self.canShowPreviewBtn = NO;
        self.canShowNextBtn = NO;
        [self setupSubView];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(settingAudioModel:) name:@"ERTCSeetingAudioModelNotification" object:nil];
    }
    return self;
}

- (void)setupSubView {
    CGFloat width = (self.frame.size.width - 2*LEFT_BUTTON_LEADING - 3*LEFT_LEADING)/NUMOFVIEW;
    CGFloat height = width*self.memberViewScale;
    self.isHiddenTopBottomView = NO;
    UITapGestureRecognizer *tapGes = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapView:)];
    tapGes.delegate = self;
    [self addGestureRecognizer:tapGes];
    ////创建大图
    self.bigPlayerView = [ERTCBigPlayerView new];
    [self addSubview:self.bigPlayerView];
    [self.bigPlayerView ysmas_makeConstraints:^(YSMASConstraintMaker *make) {
        make.edges.equalTo(self);
    }];
    
    self.bigPlayerView.vcsPlayerView = self;
    self.bigPlayerView.hidden = YES;
    
    //远端屏幕共享
    self.remoteShareView = [ERTCVideoRemoteShareView new];
    self.remoteShareView.delegate = self;
    self.remoteShareView.hidden = YES;
    [self addSubview:self.remoteShareView];
    [self.remoteShareView ysmas_makeConstraints:^(YSMASConstraintMaker *make) {
        make.edges.equalTo(self);
    }];
    
    //高度、宽度参考视图
    UIView *oneView = [UIView new];
    [self addSubview:oneView];
    
    UIView *twoView = [UIView new];
    [self addSubview:twoView];
    
    UIView *threeView = [UIView new];
    [self addSubview:threeView];
    
    UIView *fourView = [UIView new];
    [self addSubview:fourView];
    
    [oneView ysmas_makeConstraints:^(YSMASConstraintMaker *make) {
        make.left.equalTo(kSafeMasLeft(self)).with.offset(LEFT_BUTTON_LEADING);
        make.right.equalTo(twoView.ysmas_left).with.offset(-LEFT_LEADING);
        make.bottom.equalTo(kSafeMasBottom(self)).with.offset(-10);
        make.height.equalTo(oneView.ysmas_width).multipliedBy(self.memberViewScale);
    }];
    [self.oneView layoutIfNeeded];
    
    [twoView ysmas_makeConstraints:^(YSMASConstraintMaker *make) {
        make.right.equalTo(threeView.ysmas_left).with.offset(-LEFT_LEADING);
        make.bottom.equalTo(oneView);
        make.width.height.equalTo(oneView);
    }];
    
    [threeView ysmas_makeConstraints:^(YSMASConstraintMaker *make) {
        make.right.equalTo(fourView.ysmas_left).with.offset(-LEFT_LEADING);
        make.bottom.equalTo(oneView);
        make.width.height.equalTo(oneView);
    }];
    
    [fourView ysmas_makeConstraints:^(YSMASConstraintMaker *make) {
        make.right.equalTo(kSafeMasRight(self)).with.offset(-LEFT_BUTTON_LEADING);;
        make.bottom.equalTo(oneView);
        make.width.height.equalTo(oneView);
    }];
    
    self.oneView = oneView;
    self.twoView = twoView;
    self.threeView = threeView;
    self.fourView = fourView;
    
    self.oneView.hidden = YES;
    self.twoView.hidden = self.oneView.hidden;
    self.threeView.hidden = self.oneView.hidden;
    self.fourView.hidden = self.oneView.hidden;
    
    
    //创建我的视图
    [self addSubview:self.minePlayerView];
    self.minePlayerView.isBigView = YES;
    self.minePlayerView.delegate = self;
    [self.minePlayerView ysmas_makeConstraints:^(YSMASConstraintMaker *make) {
        make.edges.equalTo(self);
    }];
    
    //底部成员视图
    self.membersContentView = [ERTCOtherMembersContentView new];
    self.membersContentView.delegate = self;
    [self addSubview:self.membersContentView];
    [self.membersContentView ysmas_makeConstraints:^(YSMASConstraintMaker *make) {
        make.left.top.bottom.equalTo(self.twoView);
        make.right.equalTo(self.fourView);
        make.height.equalTo(self.oneView);
    }];
    
    [self addSubview:self.previousBtn];
    [self addSubview:self.nextBtn];
    [self.previousBtn ysmas_makeConstraints:^(YSMASConstraintMaker *make) {
        make.height.centerY.equalTo(oneView);
        make.width.ysmas_equalTo(LEFT_BUTTON_LEADING);
        make.right.equalTo(oneView.ysmas_left);
    }];
    
    [self.nextBtn ysmas_makeConstraints:^(YSMASConstraintMaker *make) {
        make.height.centerY.equalTo(fourView);
        make.width.ysmas_equalTo(LEFT_BUTTON_LEADING);
        make.left.equalTo(fourView.ysmas_right);
    }];
    
    self.previousBtn.hidden = YES;
    self.nextBtn.hidden = YES;
    
    //添加顶部、底部功能视图
    self.topView = [ERTCVideoMeetingTopView new];
    self.topView.delegate = self;
    [self addSubview:self.topView];
    [self.topView switchCammerBtnEnable:YES];
    
    self.bigPlayerView.topView = self.topView;
    self.minePlayerView.topView = self.topView;
    
    self.bottomView = [ERTCVideoMeetingBottomView new];
    self.bottomView.delegate = self;
    [self addSubview:self.bottomView];
    
    self.bottomSafeView = [[UIView alloc] init];
    self.bottomSafeView.backgroundColor = [UIColor colorWithRed:0/255.0 green:0/255.0 blue:0/255.0 alpha:0.8/1.0];
    [self addSubview:self.bottomSafeView];
    
    height = TOP_VIEW_HEIGHT+self.safeAreaInsetsTop;
    [self.topView ysmas_makeConstraints:^(YSMASConstraintMaker *make) {
        make.left.right.equalTo(self);
        make.top.equalTo(self);
        make.height.ysmas_equalTo(height);
    }];
    
    [self.bottomView ysmas_makeConstraints:^(YSMASConstraintMaker *make) {
        make.left.right.equalTo(self);
        make.bottom.equalTo(kSafeMasBottom(self));
        make.height.ysmas_equalTo(BOTTOM_VIEW_HEIGHT);
    }];
    
    [self.bottomSafeView ysmas_makeConstraints:^(YSMASConstraintMaker *make) {
        make.left.right.equalTo(self);
        make.top.equalTo(self.bottomView.ysmas_bottom);
        make.height.ysmas_equalTo(self.safeAreaInsetsBottom);
    }];
    
    [self.topView relayout:NO];
    [self.bottomView relayout:NO];
    
    //添加消息发送视图
    self.msgEditView = [ERTCVideoChatMsgEditView new];
    self.msgEditView.delegate = self;
    [self addSubview:self.msgEditView];
    [self.msgEditView ysmas_makeConstraints:^(YSMASConstraintMaker *make) {
        make.left.equalTo(kSafeMasLeft(self));
        make.right.equalTo(kSafeMasRight(self));
        make.bottom.equalTo(kSafeMasBottom(self));
        make.height.ysmas_equalTo(80);
    }];
    
    self.msgEditView.hidden = YES;
    
    //消息发送按钮
    [self addSubview:self.msgSendBtn];
    [self.msgSendBtn ysmas_makeConstraints:^(YSMASConstraintMaker *make) {
        make.left.equalTo(self);
        make.bottom.equalTo(self).with.offset(-300);
        make.width.height.ysmas_equalTo(22);
    }];
    [self bringSubviewToFront:self.msgSendBtn];
    
    //新增定时消失工具栏定时器
    [self beginHiddenToolBarTimer];
    
}

- (void)setRoomId:(NSString *)roomId {
    _roomId = roomId;
    self.topView.meetingId = roomId;
}

-(CGFloat)memberViewScale {
    return self.isToLand == YES ? 9/16.f : 16/9.f;
}

#pragma mark - UIButton Event
-(void)previousBtnClick:(UIButton *)btn {
    [self.membersContentView previewPage];
    ERTCUserInfo *firstUserModel = [self.membersContentView getFirstUser];
    self.bigPlayerView.playInfoModel = firstUserModel;
}

-(void)nextBtnClick:(UIButton *)btn {
    [self.membersContentView nextPage];
    ERTCUserInfo *firstUserModel = [self.membersContentView getFirstUser];
    self.bigPlayerView.playInfoModel = firstUserModel;
}

#pragma mark -private
-(void)msgSendBtnClick:(UIButton *)btn {
    self.msgEditView.hidden = NO;
    [self.msgEditView beginEdit];
}


#pragma mark - UIViewController Delegate
-(void)viewSafeAreaInsetsDidChange
{
    if (@available(iOS 11.0, *)) {
        self.safeAreaInsetsTop = [UIApplication sharedApplication].delegate.window.safeAreaInsets.top;
        self.safeAreaInsetsBottom = [UIApplication sharedApplication].delegate.window.safeAreaInsets.bottom;
    }
    
    //兼容 ios 11 及以下 top 为 0 的问题
    if (self.safeAreaInsetsTop == 0) {
        if (self.isToLand == NO) {
            self.safeAreaInsetsTop = 30;
        }
    }
    
    NSLog(@"viewSafeAreaInsetsDidChange InsetsTop:%f InsetsBottom:%f", self.safeAreaInsetsTop, self.safeAreaInsetsBottom);
    [self.topView ysmas_updateConstraints:^(YSMASConstraintMaker *make) {
        make.height.ysmas_equalTo(TOP_VIEW_HEIGHT+self.safeAreaInsetsTop);
    }];
    
    [self.topView relayout:(self.safeAreaInsetsTop == 0)];
}


#pragma mark -public
- (void)enterRoomWithRoomId:(NSString *)roomId userId:(NSString *)userId completionBlock:(void (^)(NSError *error))completion{
    [[ERTCPlayerViewManager sharedInstance] creatConfig:^(NSError * _Nonnull error) {
        if (completion != nil) {
            completion(error);
        }
        if (error == nil) {
            [[ERTCPlayerViewManager sharedInstance] enterRoomWithRoomId:roomId userId:userId completion:^(NSError * _Nonnull error) {
                if (completion != nil) {
                    completion(error);
                }
               
            }];
        }
        
    }];
   
    
}

///默认开启本地麦克风、摄像头、扬声器
- (void)setDefaultParam {
    [[ERTCPlayerViewManager sharedInstance].engine enableAudioVolumeEvaluation:300];
    if ([ERTCPlayerViewManager sharedInstance].videoState) {
        [[ERTCPlayerViewManager sharedInstance].engine enableLocalVideo:YES];
        [[ERTCPlayerViewManager sharedInstance].engine setLocalPreview:self.minePlayerView withRegionID:0];
    } else {
        [[ERTCPlayerViewManager sharedInstance].engine enableLocalVideo:NO];
        [[ERTCPlayerViewManager sharedInstance].engine setLocalPreview:nil withRegionID:0];
    }
    if ([ERTCPlayerViewManager sharedInstance].audioState) {
        [[ERTCPlayerViewManager sharedInstance].engine enableLocalAudio:YES];
    } else {
        [[ERTCPlayerViewManager sharedInstance].engine enableLocalAudio:NO];
    }
   
    ERTCUserInfo *info = [[ERTCVideoMeetingManager sharedInstance] getMemberInfoByUserId:[ERTCVideoMeetingManager sharedInstance].localUserInfo.uid];
    info.isAudioAvailable = [ERTCPlayerViewManager sharedInstance].audioState;
    info.isVideoAvailable = [ERTCPlayerViewManager sharedInstance].videoState;
    ///开始计时
    [self.topView startTimer];
    
    //自己进入房间，变成大图
    ERTCUserInfo *model = [[ERTCUserInfo alloc] initWithUID:[ERTCVideoMeetingManager sharedInstance].localUserInfo.uid];
    model.type = ERTCPlayerViewType_Mine;
    model.isAudioAvailable = [ERTCPlayerViewManager sharedInstance].audioState;
    model.isVideoAvailable = [ERTCPlayerViewManager sharedInstance].videoState;
    model.netLevel = ERTCNetworkQuality_Good;
    self.minePlayerView.playInfoModel = model;
    self.mineModel = model;
    
    //更新状态
    [self updateMeetingMemberViewInfo:model];
    [self.bottomView setBottomViewMicrButtonState:![ERTCPlayerViewManager sharedInstance].audioState];
    [self.bottomView setBottomViewCammerButtonState:![ERTCPlayerViewManager sharedInstance].videoState];
}

///退出会议
-(void)exitMeeting {
    [self.topView exitMeeting];
}

///显示屏幕共享
- (void)showRemoteShare:(NSString *)userId avaliable:(BOOL)avaliable {
    if (!avaliable) {
        //结束屏幕共享
        self.isSharing = NO;
        self.screenShareUserId = nil;
        self.remoteShareView.hidden = YES;
//        [self.bottomView setBottomViewShareButtonEnableState:YES];
        [self.bottomView setBottomViewShareButtonState:NO];
        [[ERTCPlayerViewManager sharedInstance].engine subscribe:NO forUser:@"" withStream:ERTCVideoStreamTypeSub];
        [[ERTCPlayerViewManager sharedInstance].engine setRemoteView:nil forUser:@"" withRegionID:0];
    } else {
        //开始屏幕共享
        self.isSharing = YES;
        self.screenShareUserId = userId;
//        [self.bottomView setBottomViewShareButtonEnableState:NO];
        [self.bottomView setBottomViewShareButtonState:YES];
        //关闭摄像头
        [[ERTCPlayerViewManager sharedInstance].engine enableLocalVideo: NO];
        self.mineModel.isVideoAvailable = NO;
        [self updateMeetingMemberViewInfo:self.mineModel];
        self.remoteShareView.hidden = NO;
        [[ERTCPlayerViewManager sharedInstance].engine subscribe:YES forUser:@"" withStream:ERTCVideoStreamTypeSub];
        [[ERTCPlayerViewManager sharedInstance].engine setRemoteView:self.remoteShareView forUser:@"" withRegionID:0];
    }
}

- (void)updateVolume:(NSArray<ERTCVolumeInfo *> *)userVolumes {
//    [self.remoteView updateVolume:userVolumes];
}

-(void)settingAudioModel:(NSNotification *)ns {
    self.bigPlayerView.playInfoModel = self.mineModel;
    if ([ERTCVideoMeetingManager sharedInstance].enableAudioMode) {
        [self.membersContentView startAudioModel];
    } else {
        [self.membersContentView cancelAudioModel];
    }
}


#pragma mark-新接口
//远端用户进入房间
-(void)onMemberEnterRoom:(ERTCUserInfo *)notifyModel {
    __block ERTCUserInfo *hasItem = nil;
    [self.membersContentView.playerViewModels enumerateObjectsUsingBlock:^(ERTCUserInfo * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if ([obj.uid isEqualToString:notifyModel.uid]) {
            hasItem = obj;
            *stop = YES;
            ERTCLog(@"房间内用户已存在 先删除存在用户");
        }
    }];
    
    if (hasItem) {
        [self onMemberExitRoom:notifyModel];
    }
    [self.membersContentView onMemberEnterRoom:notifyModel];
    if (self.membersContentView.playerViewModels.count == 1) {
        
        ERTCUserInfo *model = [[ERTCUserInfo alloc] initWithUID:notifyModel.uid];
        model.type = ERTCPlayerViewType_Other;
        
        self.bigPlayerView.playInfoModel = model;
        self.bigPlayerView.hidden = NO;
        self.membersContentView.hidden = NO;
        
        [[ERTCPlayerViewManager sharedInstance].engine setLocalPreview:nil withRegionID:0];
        [self.minePlayerView ysmas_remakeConstraints:^(YSMASConstraintMaker *make) {
            make.edges.equalTo(self.oneView);
        }];
        [self layoutIfNeeded];
        [[ERTCPlayerViewManager sharedInstance].engine setLocalPreview:self.minePlayerView withRegionID:0];
        self.minePlayerView.isBigView = NO;
        [self.minePlayerView onMemberInfoUpdate:self.mineModel];
        [self.minePlayerView setNeedsLayout];
    }
    [EZSaaSRTCProgressHUD showSuccessWithStatus:[NSString stringWithFormat:@"%@加入会议成功",notifyModel.uid]];
}

//远端用户退出房间
-(void)onMemberExitRoom:(ERTCUserInfo *)notifyModel {
    self.bigPlayerView.playInfoModel = self.mineModel;
    [self.membersContentView onMemberExitRoom:notifyModel];
    if (self.membersContentView.playerViewModels.count == 0) {
        //房间内只剩当前用户一个人
        [[ERTCPlayerViewManager sharedInstance].engine setLocalPreview:nil withRegionID:0];
        [self.minePlayerView ysmas_remakeConstraints:^(YSMASConstraintMaker *make) {
            make.edges.equalTo(self);
        }];
        [self layoutIfNeeded];
        [[ERTCPlayerViewManager sharedInstance].engine setLocalPreview:self.minePlayerView withRegionID:0];
        
        self.minePlayerView.isBigView = YES;
        self.minePlayerView.hidden = NO;
        [self.minePlayerView onMemberInfoUpdate:self.mineModel];
        [self.minePlayerView setNeedsLayout];
        
        self.bigPlayerView.playInfoModel = nil;
        self.bigPlayerView.hidden = YES;
        self.membersContentView.hidden = YES;
    } else {
        if ([self.bigPlayerView.playInfoModel.uid isEqualToString:notifyModel.uid]) {
            //当前大窗口显示的成员退出房间
            if (self.membersContentView.playerViewModels.count > 0) {
                
            } else {
                [[ERTCPlayerViewManager sharedInstance].engine setLocalPreview:nil withRegionID:0];
                [self.minePlayerView ysmas_remakeConstraints:^(YSMASConstraintMaker *make) {
                    make.edges.equalTo(self);
                }];
                [self layoutIfNeeded];
                [[ERTCPlayerViewManager sharedInstance].engine setLocalPreview:self.minePlayerView withRegionID:0];
                
                self.minePlayerView.isBigView = YES;
                [self.minePlayerView onMemberInfoUpdate:self.mineModel];
                [self.minePlayerView setNeedsLayout];
                
                self.bigPlayerView.playInfoModel = nil;
                self.bigPlayerView.hidden = YES;
                self.membersContentView.hidden = YES;
            }
        }
    }
    [EZSaaSRTCProgressHUD showErrorWithStatus:[NSString stringWithFormat:@"%@ 已离开", notifyModel.uid]];
}

//更新远端用户状态信息(视频、音频、音量大小)
-(void)onMemberInfoUpdate:(ERTCUserInfo *)notifyModel {
    [self.bigPlayerView onMemberInfoUpdate:notifyModel];
    [self.membersContentView onMemberInfoUpdate:notifyModel];
}

//更新本地用户状态信息(麦克风、摄像头状态)
-(void)updateMeetingMemberViewInfo:(ERTCUserInfo *)notifyModel {
    [self.minePlayerView onMemberInfoUpdate:notifyModel];
    [self.bigPlayerView onMemberInfoUpdate:notifyModel];

}

//用户本地和远端用户网络状态信息
- (void)updateNetworkQuality:(ERTCUserInfo *)notifyModel {
    [self.minePlayerView onMemberInfoUpdate:notifyModel];
    [self.bigPlayerView onMemberInfoUpdate:notifyModel];
    [self.membersContentView onMemberInfoUpdate:notifyModel];
}

- (void)onDisplay:(ERTCUserInfo *)notifyModel {
    [self.membersContentView onDisplay:notifyModel];
}


-(void)tapView:(UIGestureRecognizer *)tapGes {
    if (self.isHiddenTopBottomView == YES) {
        [self showTopBottomView];
        [self beginHiddenToolBarTimer];
    } else {
        [self hiddenTopBottomView];
        [self endHiddenToolBarTimer];
    }
    self.isHiddenTopBottomView = !self.isHiddenTopBottomView;
    [self setNeedsUpdateConstraints];
}

-(void)hiddenTopBottomView {
    [UIView animateWithDuration:ANIMATION_DURATION animations:^{
        [self.topView ysmas_remakeConstraints:^(YSMASConstraintMaker *make) {
            make.left.right.equalTo(self);
            make.bottom.equalTo(self.ysmas_top);
            make.height.ysmas_equalTo(TOP_VIEW_HEIGHT+self.safeAreaInsetsTop);
        }];
        
        [self.bigPlayerView hiddenTopBottomView];
        [self.minePlayerView hiddenTopBottomView];
        
        [self.bottomView ysmas_remakeConstraints:^(YSMASConstraintMaker *make) {
            make.left.right.equalTo(self);
            make.top.equalTo(self.ysmas_bottom);
            make.height.ysmas_equalTo(BOTTOM_VIEW_HEIGHT);
        }];
        [self layoutIfNeeded];
    }];
}

-(void)showTopBottomView {
    [UIView animateWithDuration:ANIMATION_DURATION animations:^{
        [self.topView ysmas_remakeConstraints:^(YSMASConstraintMaker *make) {
            make.left.right.equalTo(self);
            make.top.equalTo(self);
            make.height.ysmas_equalTo(TOP_VIEW_HEIGHT+self.safeAreaInsetsTop);
        }];
        
        [self.bigPlayerView showTopBottomView];
        [self.minePlayerView showTopBottomView];
        
        [self.bottomView ysmas_remakeConstraints:^(YSMASConstraintMaker *make) {
            make.left.right.equalTo(self);
            make.bottom.equalTo(kSafeMasBottom(self));
            make.height.ysmas_equalTo(BOTTOM_VIEW_HEIGHT);
        }];
    }];
}

#pragma mark - NSTimer
-(void)beginHiddenToolBarTimer {
    [self endHiddenToolBarTimer];
    self.timer = [NSTimer timerWithTimeInterval:TOOLBAR_ANIMATION_DURATION target:self selector:@selector(timerSelector:) userInfo:nil repeats:NO];
    [[NSRunLoop mainRunLoop] addTimer:self.timer forMode:NSDefaultRunLoopMode];
}

-(void)endHiddenToolBarTimer {
    [self.timer invalidate];
    self.timer = nil;
}

-(void)timerSelector:(NSTimer *)timer {
    [self hiddenTopBottomView];
    self.isHiddenTopBottomView = YES;
}

#pragma mark - 屏幕旋转
-(void)viewWillTransitionToSize:(CGSize)size {
    if(size.width > size.height) {
          //横屏
        if ( self.minePlayerView.isShowMine) {
            [[ERTCPlayerViewManager sharedInstance].engine setLocalPreview:nil withRegionID:0];
            self.minePlayerView.frame = CGRectMake(0, 0, size.width, size.height);
            [[ERTCPlayerViewManager sharedInstance].engine setLocalPreview:self.minePlayerView withRegionID:0];
        } 
    } else {
        //竖屏
        if ( self.minePlayerView.isShowMine) {
            [[ERTCPlayerViewManager sharedInstance].engine setLocalPreview:nil withRegionID:0];
            self.minePlayerView.frame = CGRectMake(0, 0, size.width, size.height);
            [[ERTCPlayerViewManager sharedInstance].engine setLocalPreview:self.minePlayerView withRegionID:0];
        }
    }
}

#pragma mark -ERTCVideoMeetingTopViewDelegate
-(void)infoViewClick:(ERTCVideoMeetingTopView *)topView {
    [self hiddenTopBottomView];
    [self endHiddenToolBarTimer];
    
    ERTCMembersNetworkInfoView *view = [ERTCMembersNetworkInfoView new];
    [self addSubview:view];
    [view ysmas_makeConstraints:^(YSMASConstraintMaker *make) {
        make.edges.equalTo(self);
    }];
}

///扬声器开启或关闭
-(void)switchSpeakerBtnClick:(ERTCVideoMeetingTopView *)topView speaker:(int)speaker {
    if (speaker == 1) {
        [[ERTCPlayerViewManager sharedInstance].engine closeRoomSound:NO];
        [EZSaaSRTCProgressHUD showSuccessWithStatus:@"已开启扬声器"];
    } else {
        [[ERTCPlayerViewManager sharedInstance].engine closeRoomSound:YES];
        [EZSaaSRTCProgressHUD showSuccessWithStatus:@"已关闭扬声器"];
        
    }
}

///切换摄像头
-(void)switchCammerBtnClick:(ERTCVideoMeetingTopView *)topView camera:(BOOL)camera {
    [[ERTCPlayerViewManager sharedInstance].engine switchCamera];
}

///退出房间
-(void)exitMeetingBtnClick:(ERTCVideoMeetingTopView *)topView {
    [[ERTCVideoMeetingManager sharedInstance].firstPageDic removeAllObjects];
    if ([self.userDelegate respondsToSelector:@selector(play_exitMeeting)]) {
        [self.userDelegate play_exitMeeting];
    }
}


#pragma mark -ERTCVideoRemoteShareViewDelegate
- (void)scaleRemoteShare:(CGRect)rect {
    [[ERTCPlayerViewManager sharedInstance].engine setDisplayRegionOfUserId:self.screenShareUserId withRegionID:0 atRect:rect];
}

#pragma mark -ERTCVideoMeetingBottomViewDelegate
///麦克风开启或关闭
-(void)micrBtnClick:(ERTCVideoMeetingBottomView *)bottomView {
    [self.bottomView setBottomViewMicrButtonState:!bottomView.mircBtnSelected];
    [[ERTCPlayerViewManager sharedInstance].engine enableLocalAudio:!bottomView.mircBtnSelected];
}

///开启或关闭摄像头
-(void)cammerBtnClick:(ERTCVideoMeetingBottomView *)bottomView {
    if (self.isSharing) {
        [EZSaaSRTCProgressHUD showSuccessWithStatus:@"正在共享中，暂停使用视频"];
        return;;
    }
    [self.bottomView setBottomViewCammerButtonState:!bottomView.cammerBtnSelected];
    if (bottomView.cammerBtnSelected) {
        [EZSaaSRTCProgressHUD showSuccessWithStatus:@"已关闭摄像头"];
        [[ERTCPlayerViewManager sharedInstance].engine enableLocalVideo:NO];
        [[ERTCPlayerViewManager sharedInstance].engine setLocalPreview:nil withRegionID:0];
        self.mineModel.isVideoAvailable = NO;
    } else {
        [[ERTCPlayerViewManager sharedInstance].engine enableLocalVideo:YES];
        [[ERTCPlayerViewManager sharedInstance].engine setLocalPreview:self.minePlayerView withRegionID:0];
        self.mineModel.isVideoAvailable = YES;
        [EZSaaSRTCProgressHUD showSuccessWithStatus:@"已开启摄像头"];
    }
    [self updateMeetingMemberViewInfo:self.mineModel];

}

///共享屏幕
-(void)shareBtnClick:(ERTCVideoMeetingBottomView *)bottomView {
    if (bottomView.shareBtnSelected) {
        [self presentStopSharingAlert];
    } else {
        [self cancelAllTipView];
        
        int ability = 0;
        if (@available(iOS 12.0, *))
        {
            ability = ability | ERTCShareTipViewAbility_Screen;
        }
        ability = ability | ERTCShareTipViewAbility_Photo;
        ability = ability | ERTCShareTipViewAbility_WhiteBoard;
        
        ERTCShareTipView *shareTipView = [[ERTCShareTipView alloc] initWithAbility:ability];
        shareTipView.delegate = self;
        [self addSubview:shareTipView];
        
        [shareTipView ysmas_makeConstraints:^(YSMASConstraintMaker *make) {
            make.top.left.right.equalTo(self);
            make.bottom.equalTo(bottomView.ysmas_top);
        }];
        
        self.shareTipView = shareTipView;
        [self endHiddenToolBarTimer];
    }
}

-(void)presentStopSharingAlert {
    NSString *title = @"确定要停止共享吗?";
    if (self.screenShareUserId.length > 0) {
        title = @"确定要强制关闭他人的共享吗?";
    }
    UIAlertController *alertC = [UIAlertController alertControllerWithTitle:title message:nil preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
    }];
    
    UIAlertAction *confirmAction = [UIAlertAction actionWithTitle:@"停止" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        //关闭屏幕共享
        if (self.screenShareUserId.length > 0) {
            //强制关闭他人的共享
            [[ERTCPlayerViewManager sharedInstance].engine forceCloseOtherScreenShare];
        } else {
            //停止自己的屏幕共享
            [self closeScreenShare];
        }
    }];
    [alertC addAction:cancelAction];
    [alertC addAction:confirmAction];
    [self.superViewController presentViewController:alertC animated:YES completion:nil];
}

- (void)closeScreenShare {
    [self.bottomView setBottomViewShareButtonState:!self.bottomView.shareBtnSelected];
    [EZSaaSRTCProgressHUD showSuccessWithStatus:@"屏幕共享已结束"];
    self.isSharing = NO;
    [[ERTCPlayerViewManager sharedInstance].engine stopScreenShare];
    [ERTCVideoMeetingManager sharedInstance].screenShare = NO;
    [self.topView switchCammerBtnEnable:YES];
    [self.bottomView setBottomViewShareButtonState:NO];
}

///更多
-(void)moreBtnClick:(ERTCVideoMeetingBottomView *)bottomView {
    [self cancelAllTipView];
    ERTCMoreTipView *moreTipView = [[ERTCMoreTipView alloc] init];
    moreTipView.delegate = self;
    [self addSubview:moreTipView];
    
    [moreTipView ysmas_makeConstraints:^(YSMASConstraintMaker *make) {
        make.top.left.right.equalTo(self);
        make.bottom.equalTo(bottomView.ysmas_top);
    }];
    
    self.moreTipView = moreTipView;
    [self endHiddenToolBarTimer];
}

///成员管理
- (void)membersBtnClick:(ERTCVideoMeetingBottomView *)bottomView {
    if ([self.userDelegate respondsToSelector:@selector(play_membersManager)]) {
        [self.userDelegate play_membersManager];
    }
}

-(BOOL)cancelAllTipView {
    BOOL result = NO;
    if (self.moreTipView) {
        [self.moreTipView cancelMoreTipView];
        result = YES;
    }
    if (result == YES) {
        [self beginHiddenToolBarTimer];
    }
    
    return result;
}

#pragma mark - ERTCMoreTipViewProtocol
-(void)clickSettingModelTipView:(ERTCMoreTipView *)tipView {
    if ([self.userDelegate respondsToSelector:@selector(play_setting)]) {
        [self.userDelegate play_setting];
    }
    
}

-(void)clickBeautyTipView:(ERTCMoreTipView *)tipView {
    if ([self.userDelegate respondsToSelector:@selector(play_beautySetting)]) {
        [self.userDelegate play_beautySetting];
    }
}

#pragma mark -ERTCShareTipViewProtocol
- (void)clickScreenShare:(ERTCShareTipView *)tipView {
    __weak __typeof(self)weakSelf = self;
    if ([ERTCPlayerViewManager sharedInstance].videoState) {
        [self cammerBtnClick:self.bottomView];
    }
    self.isSharing = YES;
    self.screenShareUserId = nil;
    [[ERTCPlayerViewManager sharedInstance].engine startScreenShareWithName:@"屏幕共享" withResultBlock:^(NSInteger ret) {
        if (ret == noErr) {
            [weakSelf.topView switchCammerBtnEnable:NO];
            [self.bottomView setBottomViewShareButtonState:YES];
            [EZSaaSRTCProgressHUD showSuccessWithStatus:@"屏幕共享已开始"];
            [ERTCVideoMeetingManager sharedInstance].screenShare = YES;
            [weakSelf.bottomView setBottomViewShareButtonState:YES];
           
        } else {
            [EZSaaSRTCProgressHUD showSuccessWithStatus:@"屏幕共享失败"];
        }
    } andEndedBlock:^{
        [EZSaaSRTCProgressHUD showSuccessWithStatus:@"屏幕共享已结束"];
        [ERTCVideoMeetingManager sharedInstance].screenShare = NO;
        [weakSelf.topView switchCammerBtnEnable:YES];
        [weakSelf.bottomView setBottomViewShareButtonState:NO];
        weakSelf.isSharing = NO;
    }];
    [self beginHiddenToolBarTimer];
}


- (void)clickPhotoShare:(ERTCShareTipView *)tipView {
    [EZSaaSRTCProgressHUD showSuccessWithStatus:@"暂不支持，敬请期待"];
}

- (void)clickWhiteBoardShare:(ERTCShareTipView *)tipView {
    [EZSaaSRTCProgressHUD showSuccessWithStatus:@"暂不支持，敬请期待"];
}


#pragma mark - RTCOtherMembersContentViewProtocol
-(void)otherMembersContentViewClickWithModel:(ERTCUserInfo *)model {
    ERTCUserInfo *bigModel = [[ERTCUserInfo alloc] initWithUID:model.uid];
    bigModel.isVideoAvailable = model.isVideoAvailable;
    bigModel.isAudioAvailable = model.isAudioAvailable;
    bigModel.type = ERTCPlayerViewType_Other;
    self.bigPlayerView.playInfoModel = bigModel;
}

-(void)pageSwitchingStatus:(BOOL)canShowPreviewBtn canShowNextBtn:(BOOL)canShowNextBtn {
    self.canShowPreviewBtn = canShowPreviewBtn;
    self.canShowNextBtn = canShowNextBtn;
//    if (self.pipModelEnable == YES) {
//        self.previousBtn.hidden = !canShowPreviewBtn;
//        self.nextBtn.hidden = !canShowNextBtn;
//    }
}

-(void)resetBigWindow {
    
}
- (void)setBigWindow:(ERTCUserInfo *)model {
    
}

#pragma mark - EZSaaSRTCMinePlayerViewProtocol
-(void)didClickMinePlayerView:(BOOL)isBigView tapGes:(UITapGestureRecognizer *)tapGes {
    if (!isBigView ) {
        self.bigPlayerView.playInfoModel = self.mineModel;
    }
}

#pragma mark -ERTCVideoChatMsgEditViewProcotol
- (void)ERTCVideoChatMsgEditViewProtocol_keyboardWasShown:(NSNotification *)notification {
    // 获取键盘的高度
    CGRect frame = [[[notification userInfo] objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];

    NSDictionary *info = [notification userInfo];
    //取出动画时长
    CGFloat animationDuration = [[info valueForKey:UIKeyboardAnimationDurationUserInfoKey] floatValue];
    //下移动画options
    UIViewKeyframeAnimationOptions options = (UIViewKeyframeAnimationOptions)[[info valueForKey:UIKeyboardAnimationCurveUserInfoKey] integerValue] << 16;
    //回复动画
    [UIView animateKeyframesWithDuration:animationDuration delay:0 options:options animations:^{
        [self.msgEditView ysmas_updateConstraints:^(YSMASConstraintMaker *make) {
            make.bottom.equalTo(self).with.offset(-CGRectGetHeight(frame));
        }];

        [self layoutIfNeeded];
    } completion:^(BOOL finished) {
    }];
}

- (void)ERTCVideoChatMsgEditViewProtocol_keyboardWillBeHiden:(NSNotification *)notification {
    NSDictionary *info = [notification userInfo];
    //取出动画时长
    CGFloat animationDuration = [[info valueForKey:UIKeyboardAnimationDurationUserInfoKey] floatValue];
    //下移动画options
    UIViewKeyframeAnimationOptions options = (UIViewKeyframeAnimationOptions)[[info valueForKey:UIKeyboardAnimationCurveUserInfoKey] integerValue] << 16;
    //回复动画
    [UIView animateKeyframesWithDuration:animationDuration delay:0 options:options animations:^{
        [self.msgEditView ysmas_updateConstraints:^(YSMASConstraintMaker *make) {
            make.bottom.equalTo(kSafeMasBottom(self));
        }];

        [self layoutIfNeeded];
    } completion:^(BOOL finished) {
        self.msgEditView.hidden = YES;
        [self.msgEditView endEdit];
    }];
}

- (void)ERTCVideoChatMsgEditViewProtocol_keyBoardSendBtnClick:(NSString *)text {
    if (text.length > 0) {
        NSData * data = [text dataUsingEncoding:NSUTF8StringEncoding];
        [[ERTCPlayerViewManager sharedInstance].engine sendCustomMsg:data];
        [self.msgEditView endEdit];
    }
}

#pragma mark -getter
- (ERTCVideoMeetingMinePlayerView *)minePlayerView {
    if (!_minePlayerView) {
        _minePlayerView = [ERTCVideoMeetingMinePlayerView new];
    }
    return _minePlayerView;
}

#pragma mark -- UI Getter Method
-(UIButton *)previousBtn {
    if (!_previousBtn) {
        _previousBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        UIImageView *backImage = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"icon_list_next_saas"]];
        UIImage *flipImage = [UIImage imageWithCGImage:backImage.image.CGImage scale:backImage.image.scale orientation:UIImageOrientationUpMirrored];
        [_previousBtn setImage:flipImage forState:(UIControlStateNormal)];
        [_previousBtn addTarget:self action:@selector(previousBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    }
    
    return _previousBtn;
}

-(UIButton *)nextBtn
{
    if (!_nextBtn) {
        _nextBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_nextBtn setImage:[UIImage imageNamed:@"icon_list_next_saas"] forState:(UIControlStateNormal)];
        [_nextBtn addTarget:self action:@selector(nextBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    }
    
    return _nextBtn;
}
-(UIButton *)msgSendBtn {
    if (!_msgSendBtn) {
        _msgSendBtn = [UIButton buttonWithType:(UIButtonTypeCustom)];
        [_msgSendBtn setImage:[UIImage imageNamed:@"弹幕"] forState:(UIControlStateNormal)];
        [_msgSendBtn addTarget:self action:@selector(msgSendBtnClick:) forControlEvents:(UIControlEventTouchUpInside)];
        _msgSendBtn.backgroundColor = [UIColor blackColor];
        _msgSendBtn.layer.cornerRadius = 2;
    }
    
    return _msgSendBtn;
}

@end
