//
//  JSGController.m
//  AIIM
//
//  Created by gan on 2025/4/21.
//

#import <Foundation/Foundation.h>
#import <AVFoundation/AVFoundation.h>
#import "JSGController.h"
#import "WebRTCStore.h"
#import "GWebSocket.h"
#import "UDManager.h"
#import "AppDelegate.h"
#import "AFNetworking/AFNetworkReachabilityManager.h"
#import <SystemConfiguration/SystemConfiguration.h>
#import "CustomJitsiLogger.h"
#import <Bugly/Bugly.h>

@interface JSGController()<WebRTCStoreDelegate,AVAudioPlayerDelegate>
@property (nonatomic,strong) JitsiMeetView *jitsiView;
@property (nonatomic) NSInteger startTime;
@property (nonatomic) BOOL isClose;
@property (nonatomic,strong) AVPlayer *player;
@property (nonatomic, strong) AFNetworkReachabilityManager *reachabilityManager;
@property (nonatomic, assign) BOOL isInConference;
@property (nonatomic, assign) BOOL isReconnecting;
@property (nonatomic, strong) JitsiMeetConferenceOptions * currentOptions;
@property (nonatomic, assign) NSUInteger reconnectAttempt;
@property (nonatomic,strong) AVAudioPlayer * audioPlayer;
@property (nonatomic, strong) UIButton *hangupButton;
@property (nonatomic, strong) UIButton *speackerBt;
@property (nonatomic, strong) UIButton *scanBt;
@property (nonatomic, strong) UILabel *FloadNote;

@property (nonatomic) BOOL isSpeacker;
@property (nonatomic) BOOL isjoin;

@property (nonatomic) BOOL hadCall;

@property (nonatomic) BOOL floadViewState;

@property (nonatomic) BOOL startLison;

@end

@implementation JSGController


- (void)viewDidLoad {
    [super viewDidLoad];
    NSLog(@"JSGController----------viewDidLoad");
    _isjoin = false;
    _isClose=YES;
    _floadViewState=NO;
    _startLison=NO;
    _hadCall = NO;
    
    WebRTCStore.shareInstance.isBusy=true;
    WebRTCStore.shareInstance.PeerId =self.chatId;
    WebRTCStore.shareInstance.delegate = self;
    _jitsiView = (JitsiMeetView*)self.view;
    _jitsiView.delegate = self;
   

    CustomJitsiLogger *handler = [CustomJitsiLogger sharedHandler];
    handler.errorCount = 0;
    [handler.criticalErrors removeAllObjects];
    weakSelf(self);
    handler.WebsocketErrorBlock = ^{
        [weakself reconnectConference];
    };
    
    
    //挂断按钮
    _hangupButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [_hangupButton setImage:[UIImage imageNamed:@"hangup_icon"] forState:UIControlStateNormal];
    [_hangupButton addTarget:self action:@selector(hangupButtonTapped) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_hangupButton];
    //扩音器按钮
    _speackerBt = [UIButton buttonWithType:UIButtonTypeCustom];
    [_speackerBt setImage:[UIImage imageNamed:@"speaker_on_icon"] forState:UIControlStateNormal];
    [_speackerBt addTarget:self action:@selector(speackerC) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_speackerBt];
    
    
    //悬浮按钮
    _scanBt = [UIButton buttonWithType:UIButtonTypeCustom];
    [_scanBt setImage:[UIImage imageNamed:@"huazhonghua_icon"] forState:UIControlStateNormal];
    [_scanBt addTarget:self action:@selector(scanToFload) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_scanBt];
    
    
    _FloadNote = [[UILabel alloc] init];
    _FloadNote.text = NSLocalizedString(@"JSmeet-connectNote", @"");
    _FloadNote.textColor = [UIColor whiteColor];
    _FloadNote.font = [UIFont systemFontOfSize:14.f];
    _FloadNote.textAlignment = NSTextAlignmentCenter;
    [self.view addSubview:_FloadNote];
    
    //悬浮按钮
}

-(void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:YES];
    
    if ([UIApplication sharedApplication].applicationState == UIApplicationStateActive) {
        // 应用已经解锁并且在前台
        NSLog(@"应用已经解锁并且在前台viewWillDisappear-----1111-----");
        
    }
}


#pragma mark 应用被唤醒时判断解锁状态
- (void)GapplicationDidBecomeActive:(NSNotification *)notification {
    // 应用进入前台
    if ([UIApplication sharedApplication].applicationState == UIApplicationStateActive) {
        // 应用已经解锁并且在前台
        _startLison=NO;
//        [[NSNotificationCenter defaultCenter] removeObserver:self name:notification.name object:notification.object];
//        [AppDelegate closeVoip];
        NSLog(@"GapplicationDidBecomeActive---------------");
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            if(self->_isjoin == false){
                self->_isjoin =true;
                [self startJitsiMeetCall];
            }
        });
    }
}

#pragma mark 切换扬声器按钮
-(void)speackerC{
    _isSpeacker=!_isSpeacker;
    if(_isSpeacker){
        [_speackerBt setImage:[UIImage imageNamed:@"speaker_off_icon"] forState:UIControlStateNormal];
    }
    else{
        [_speackerBt setImage:[UIImage imageNamed:@"speaker_on_icon"] forState:UIControlStateNormal];
    }
    [_jitsiView changeAudioSession:_isSpeacker];
    
    
}
#pragma mark 挂断按钮
- (void)hangupButtonTapped{
    [self endJitsiMeetCall];
}

#pragma mark 悬浮按钮
- (void)scanToFload{
    if(self.audioOnly){
        [[AppDelegate sharedInstance] floadinSmWindow:1];
    }
    else{
        [[AppDelegate sharedInstance] floadinSmWindow:2];
    }
    
}


#pragma mark 开始JitsiMeet 发起呼叫流程

-(void)startJitsiMeetCall{
    NSLog(@"startJitsiMeetCall--------1--------");
    _isClose=NO;
    _isjoin=false;
    _isSpeacker = NO;
    _hadCall = NO;
    [self.view bringSubviewToFront:_hangupButton];
    [_hangupButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(50, 50));
        make.bottom.mas_equalTo(-SCREEN_X_BTM);
        make.centerX.mas_equalTo(self.view.mas_centerX);
    }];
    [self.view bringSubviewToFront:_speackerBt];
    [_speackerBt mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(40, 40));
        make.bottom.mas_equalTo(-SCREEN_X_BTM);
        make.right.mas_equalTo(_hangupButton.mas_left).offset(-12);
    }];
    
    [self.view bringSubviewToFront:_scanBt];
    [_scanBt mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(40, 40));
        make.bottom.mas_equalTo(-SCREEN_X_BTM);
        make.left.mas_equalTo(_hangupButton.mas_right).offset(12);
    }];
    
    [self.view bringSubviewToFront:_FloadNote];
    [_FloadNote mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view.mas_left).offset(26);
        make.width.mas_lessThanOrEqualTo(self.view.mas_width).offset(-52);
        make.bottom.equalTo(self.view.mas_bottom).offset(-150);
    }];
    
    
    
    if ([UIApplication sharedApplication].applicationState == UIApplicationStateActive) {
        // 应用已经解锁并且在前台
        NSLog(@"应用已经解锁并且在前台viewWillDisappear-----1111");
    }
    else{
        if(!_startLison){
            _startLison=YES;
            [[NSNotificationCenter defaultCenter] addObserver:self
                                                         selector:@selector(GapplicationDidBecomeActive:)
                                                             name:UIApplicationDidBecomeActiveNotification
                                                           object:nil];
        }
        return;
    }
    
    if (self.chatId == nil) {//聊天框参数异常
        NSLog(@"Room is nul!");
        [self endJitsiMeetCall];
        return;
    }
    NSLog(@"startJitsiMeetCall--------2--------");
    NSLog(@"%@:%@",self.room,self.chatId);
    [AppDelegate JitsiMeetState:YES];
    [AppDelegate closeVoip];
    //初始化状态参数
    _startTime = 0;//通话时长
    _reconnectAttempt = 0;//重连次数
    _isReconnecting = NO;//是否重连
    if(self.isCaller){
        NSDate *now = [NSDate date];
        NSTimeInterval trt = [now timeIntervalSince1970];
        NSInteger time = trt*1000;
        self.room = [NSString stringWithFormat:@"%@_%ld",self.chatId,(long)time];
    }
    else{
        [self sendBusy];
    }
    
    [self initjsView];//初始化 房间页面
    
    _isjoin =true;
    if(self.currentOptions){
        [_jitsiView join:self.currentOptions];//进入房间
    }
    else{
        //初始化失败
        NSString *bgMark = @"initjsView 初始化失败";
        [Bugly reportException:[NSException exceptionWithName:[NSString stringWithFormat:@"voip：%@",bgMark] reason:@"" userInfo:nil]];
        [self endJitsiMeetCall];
        return;
    }
    
    [self.audioPlayer play];
    _FloadNote.alpha = 1;
    [_jitsiView changeAudioSession:NO];
    
}


#pragma mark 结束JitsiMeet 隐藏界面 释放资源

-(void)endJitsiMeetCall{
    [self.audioPlayer stop];
    [self.jitsiView leave];
    [_jitsiView closeChat];
    [AppDelegate JitsiMeetState:NO];
    [self endCall];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}



#pragma mark 重连操作，待完善
- (void)reconnectConference {
    NSLog(@"reconnectConference---------1");
    if (_isReconnecting) return;
    _isReconnecting = YES;
    _reconnectAttempt++;
    if (_reconnectAttempt > 3) {
        _isReconnecting = NO;
        return;
    }
    NSLog(@"reconnectConference---------2");
    // 1. 先离开当前会议
    [self.jitsiView leave];
    // 2. 等待清理完成
    NSLog(@"reconnectConference---------3");
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        // 3. 重新加入会议
//        [self initjsView];
        [self.jitsiView join:self.currentOptions];//进入房间
        NSLog(@"reconnectConference---------4");
//        if(self.startTime==0){
//            NSDate *now = [NSDate date];
//            NSTimeInterval trt = [now timeIntervalSince1970];
//            self.startTime = trt*1000;
//        }
        
        // 4. 重置重连状态
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            self->_isReconnecting = NO;
        });
    });
}


-(void)sendBusy{
    NSDictionary *userinfo = [UDManager.shareInstance getDDManager:dkuserinfo];
    
    NSLog(@"userinfo:%@",userinfo);
    if (userinfo == nil) {
        NSLog(@"Room is nul!");
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self dismissViewControllerAnimated:YES completion:nil];
        });
        return;
    }
    NSString *userId = userinfo[@"id"];
    NSString *username = userinfo[@"name"];
    NSString *useravatar = userinfo[@"avatar"];
    NSDate *now = [NSDate date];
    NSTimeInterval trt = [now timeIntervalSince1970];
    NSInteger time = trt*1000;
    NSString *strtime = [NSString stringWithFormat:@"%ld",(long)time];
    BOOL conetType=true;
    if (self.audioOnly) {
        conetType=false;
    }
    NSDictionary *callMsg = @{
        @"code":SendCode_WEBRTC_BUSY,
        @"message": @{
            @"chatId":self.chatId,
            @"fromId":userId,
            @"type":@"0",
            @"msgtype":@"busy",
            @"conetType":[NSNumber numberWithBool:conetType],
            @"timestamp":strtime,
            @"fromName":username,
            @"fromAvatar":useravatar,
            @"payload":self.room?:@""
        }
    };
    NSError *error;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:callMsg options:0 error:&error];
    if (!jsonData) {
        NSLog(@"Got an error: %@", error);
    } else {
        NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
        NSLog(@"%@", jsonString); // 输出: {"name":"John","age":25}
        [GWebSocket.shareInstance sendMsg:jsonString];
    }
}


-(void)sendCall{
    NSDictionary *userinfo = [UDManager.shareInstance getDDManager:dkuserinfo];
    NSLog(@"userinfo:%@",userinfo);
    NSString *userId = userinfo[@"id"];
    NSString *username = userinfo[@"name"];
    NSString *useravatar = userinfo[@"avatar"];
    NSLog(@"-------拨打-------");
    NSDate *now = [NSDate date];
    NSTimeInterval trt = [now timeIntervalSince1970];
    NSInteger time = trt*1000;
    NSString *strtime = [NSString stringWithFormat:@"%ld",(long)time];
    BOOL conetType=true;
    if (self.audioOnly) {
        conetType=false;
    }
    NSDictionary *callMsg = @{
        @"code":@"8",
        @"message": @{
            @"chatId":self.chatId,
            @"fromId":userId,
            @"type":@"0",
            @"msgtype":@"calling",
            @"conetType":[NSNumber numberWithBool:conetType],
            @"timestamp":strtime,
            @"fromName":username,
            @"fromAvatar":useravatar,
            @"payload":self.room
        }
    };
    NSError *error;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:callMsg options:0 error:&error];
    if (!jsonData) {
        NSLog(@"Got an error: %@", error);
    } else {
        NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
        NSLog(@"%@", jsonString); // 输出: {"name":"John","age":25}
        [GWebSocket.shareInstance sendMsg:jsonString];
    }
    
}

-(void)endCall{
    if (_isClose) {
        return;
    }
    NSLog(@"-------挂断-------");
    NSDictionary *userinfo = [UDManager.shareInstance getDDManager:dkuserinfo];
    if(userinfo==nil){
        return;
    }
    NSString *userId = userinfo[@"id"];
    NSString *username = userinfo[@"name"];
    NSString *useravatar = userinfo[@"avatar"];
    NSDate *now = [NSDate date];
    NSTimeInterval trt = [now timeIntervalSince1970];
    NSInteger time = trt*1000;
    NSString *strtime = [NSString stringWithFormat:@"%ld",(long)time];
    
    
    if(self.isCaller){
        NSString *result = @"false";
        NSString *duration = @"0";
        
        if (_startTime>0) {
            result = @"true";
            _startTime=time-_startTime;
            duration=[NSString stringWithFormat:@"%ld",(long)_startTime];
        }
        BOOL conetType=true;
        NSString *content;
        if (self.audioOnly) {
            conetType=false;
            content = @"【语音通话】";
        }
        else{
            content = @"【视频通话】";
        }
        NSDictionary *callMsg = @{
            @"code":@"2",
            @"message": @{
                //@"id":strtime,
                @"localtime":strtime,
                @"mine":[NSNumber numberWithBool:YES],
                @"messageType":@"7",
                @"chatId":self.chatId,
                @"fromId":userId,
                @"fromName":username,
                @"fromAvatar":useravatar,
                @"type":@"0",
                @"result":result,
                @"timestamp":strtime,
                @"video":[NSNumber numberWithBool:conetType],
                @"duration":duration,
                @"content":content,
            }
        };
        NSError *error;
        NSData *jsonData = [NSJSONSerialization dataWithJSONObject:callMsg options:0 error:&error];
        if (!jsonData) {
            NSLog(@"Got an error: %@", error);
        } else {
            NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
            NSLog(@"%@", jsonString); // 输出: {"name":"John","age":25}
            [GWebSocket.shareInstance sendMsg:jsonString];
        }
    }
    
    NSDictionary *callMsg = @{
        @"code":@"9",
        @"message": @{
            @"chatId":self.chatId,
            @"fromId":userId,
            @"type":@"0",
            @"msgtype":@"close",
            @"timestamp":strtime,
            @"fromName":username,
            @"fromAvatar":useravatar,
            @"payload":self.room?:@""
        }
    };
    NSError *error;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:callMsg options:0 error:&error];
    if (!jsonData) {
        NSLog(@"Got an error: %@", error);
    } else {
        NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
        NSLog(@"%@", jsonString); // 输出: {"name":"John","age":25}
        [GWebSocket.shareInstance sendMsg:jsonString];
    }
    
    
    WebRTCStore.shareInstance.isBusy=false;
    WebRTCStore.shareInstance.PeerId =nil;
    
    _isClose=YES;
}


#pragma mark  拨打、挂断、重拨 WebRTCStoreDelegate
-(void)WebRTCStoreAct:(NSDictionary *)actData{
    
    NSLog(@"WebRTCStoreAct----msgtype:%@",actData);
    
    NSString *messageType =actData[@"messageType"]?:@"";
    if([messageType isEqualToString:MessageType_DFBUSY]){
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"Common_tips", @"提示")
                                                                      message:NSLocalizedString(@"JSGController-mang", @"對方正忙")
                                                               preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"Common_confirm", @"確定")
                                                         style:UIAlertActionStyleDefault
                                                       handler:^(UIAlertAction * action) {
            
            // 点击确定后的操作
            [self endJitsiMeetCall];
        }];
        [alert addAction:okAction];
        [self presentViewController:alert animated:YES completion:nil];
        return;
    }
    
    NSString *msgtype = actData[@"msgtype"]?:@"";
    if([msgtype isEqualToString:@"close"]){
        NSString *chatId =actData[@"fromId"]?:@"";
        if([self.chatId isEqualToString:chatId]){//对方挂断
            if(self.startTime>0){
                
            }else{
                [self endJitsiMeetCall];
            }
        }
        else{//非对方挂断的其他干扰数据
            
        }
        
    }
}


#pragma mark JitsiMeetView act

-(void)initjsView{
    // Attach this controller as the delegate.

    JitsiMeetConferenceOptions *options=nil;
    if(self.isCaller){
        NSLog(@"initjsView---00000---");
        // create the room.JitsiMeetConferenceOptions
        options = [JitsiMeetConferenceOptions fromBuilder:^(JitsiMeetConferenceOptionsBuilder *builder) {
            builder.serverURL = [NSURL URLWithString:JitsiMeetSV];
            builder.room = self.room;
            builder.audioOnly = self.audioOnly;
            [builder setFeatureFlag:@"ios.screensharing.enabled" withBoolean:YES];
            
            //界面优化 - 隐藏不必要的会议功能
            [builder setFeatureFlag:@"welcomepage.enabled" withBoolean:NO];
            [builder setFeatureFlag:@"pip.enabled" withBoolean:NO];
            [builder setFeatureFlag:@"live-streaming.enabled" withBoolean:NO];
            [builder setFeatureFlag:@"recording.enabled" withBoolean:NO];
            [builder setFeatureFlag:@"kick-out.enabled" withBoolean:NO];
            [builder setFeatureFlag:@"security-options.enabled" withBoolean:NO];
            [builder setFeatureFlag:@"chat.enabled" withBoolean:NO];
            [builder setFeatureFlag:@"invite.enabled" withBoolean:NO];
            [builder setFeatureFlag:@"add-people.enabled" withBoolean:NO];
            [builder setFeatureFlag:@"video-share.enabled" withBoolean:NO];
            [builder setFeatureFlag:@"call-integration.enabled" withBoolean:NO];
            [builder setFeatureFlag:@"startWithAudioMuted" withBoolean:NO];
            [builder setFeatureFlag:@"prejoinpage.enabled" withBoolean:NO];
            
            [builder setFeatureFlag:@"reconnect.enabled" withBoolean:YES];
            [builder setConfigOverride:@"iceTransportPolicy" withValue:@"relay"];
            [builder setConfigOverride:@"enableNetworkMonitor" withBoolean:YES];
            [builder setConfigOverride:@"toolbarButtons" withArray:@[@"microphone",@"camera"]];
            

//            
//            // 界面简化 - 更适合一对一场景
//            [builder setFeatureFlag:@"toolbox.alwaysVisible" withBoolean:NO];
//            [builder setFeatureFlag:@"filmstrip.enabled" withBoolean:NO];
//            [builder setFeatureFlag:@"thumbnail.enabled" withBoolean:NO];
//            [builder setFeatureFlag:@"disableRtx" withBoolean:YES];// 一对一不需要RTX
//            [builder setFeatureFlag:@"disableNS" withBoolean:YES];     // 降噪可关闭
//            
//            [builder setFeatureFlag:@"ios.audio-handler" withBoolean:NO];
            
            [builder setConfigOverride:@"toolbarButtons" withArray:@[@"microphone",@"camera"]];
        }];
    }
    else{
        // Join the room.
        NSLog(@"initjsView---111---");
        options
            = [JitsiMeetConferenceOptions fromBuilder:^(JitsiMeetConferenceOptionsBuilder *builder) {
                builder.room = self.room;
                builder.audioOnly = self.audioOnly;
                [builder setFeatureFlag:@"welcomepage.enabled" withBoolean:NO];
                [builder setFeatureFlag:@"pip.enabled" withBoolean:NO];
                [builder setFeatureFlag:@"ios.screensharing.enabled" withBoolean:YES];
                [builder setFeatureFlag:@"chat.enabled" withBoolean:NO];
                [builder setFeatureFlag:@"invite.enabled" withBoolean:NO];
                [builder setFeatureFlag:@"add-people.enabled" withBoolean:NO];
                [builder setFeatureFlag:@"video-share.enabled" withBoolean:NO];
                [builder setFeatureFlag:@"call-integration.enabled" withBoolean:NO];
                [builder setFeatureFlag:@"startWithAudioMuted" withBoolean:NO];
                [builder setFeatureFlag:@"prejoinpage.enabled" withBoolean:NO];
                
                
                [builder setFeatureFlag:@"reconnect.enabled" withBoolean:YES];
                [builder setConfigOverride:@"iceTransportPolicy" withValue:@"relay"];
                [builder setConfigOverride:@"enableNetworkMonitor" withBoolean:YES];
                [builder setConfigOverride:@"toolbarButtons" withArray:@[@"microphone",@"camera"]];
            }];
    }
    NSLog(@"initjsView---2---:%@",options);


    self.currentOptions = options;
    
    
}

- (void)conferenceWillJoin:(NSDictionary *)data {
    NSLog(@"About to join conference---- %@", self.room);
    self.isInConference = NO;
    if (self.isCaller) {//拨打方进入房间成功，开始通知对方
        if(_hadCall){
            return;
        }
        _hadCall = YES;
        [self sendCall];
    }
    else{//接听方进入房间，播放等待接通铃声
        NSLog(@"self.audioPlayer-----------");
//        [self.audioPlayer play];
//        [self reconnectConference];
    }
    

    [self.view bringSubviewToFront:_hangupButton];
    [_hangupButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(50, 50));
        make.bottom.mas_equalTo(-SCREEN_X_BTM);
        make.centerX.mas_equalTo(self.view.mas_centerX);
    }];
    [self.view bringSubviewToFront:_speackerBt];
    [_speackerBt mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(40, 40));
        make.bottom.mas_equalTo(-SCREEN_X_BTM);
        make.right.mas_equalTo(_hangupButton.mas_left).offset(-12);
    }];
    [self.view bringSubviewToFront:_scanBt];
    [_scanBt mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(40, 40));
        make.bottom.mas_equalTo(-SCREEN_X_BTM);
        make.left.mas_equalTo(_hangupButton.mas_right).offset(12);
    }];
    
    [self.view bringSubviewToFront:_FloadNote];
    [_FloadNote mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view.mas_left).offset(26);
        make.width.mas_lessThanOrEqualTo(self.view.mas_width).offset(-52);
        make.bottom.equalTo(self.view.mas_bottom).offset(-150);
    }];
}

- (void)conferenceJoined:(NSDictionary *)data {
    _reconnectAttempt = 0;
    _isInConference = YES;
    NSLog(@"Conference %@ joined----11222-------", self.room);
    if(!self.isCaller){//接听方接通成功
        [self.audioPlayer stop];//停止铃声
        _FloadNote.alpha = 0;
    }
}

- (void)conferenceTerminated:(NSDictionary *)data {//连接错误，重连处理待验证
    NSLog(@"conferenceTerminated----------------------:%@",data);
    _isInConference = NO;
    
    NSString *error = data[@"error"];
    if (error) {
        if ([error isEqualToString:@"connection.otherError"]) {
            [self reconnectConference];
        } else {
            NSLog(@"%@",error);
        }
    }
}

- (void)readyToClose:(NSDictionary *)data {
    NSLog(@"readyToClose-----:%@",data);
    
    if (_isReconnecting) {
        return;
    }

}

- (void)customButtonPressed:(NSDictionary *)data {
    NSLog(@"---------Custom button pressed %@", data);
}

-(void)participantJoined:(NSDictionary *)data{
    NSLog(@"------1-------participantJoined");
    if(_startTime==0){
        NSDate *now = [NSDate date];
        NSTimeInterval trt = [now timeIntervalSince1970];
        _startTime = trt*1000;
    }
    _FloadNote.alpha = 0;
    [self.audioPlayer stop];
    // 使用GCD创建一个在3秒后执行的定时器
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        NSLog(@"Timer fired using GCD!");
        [self inispeacker];
    });
    
}

- (void)participantLeft:(NSDictionary *)data{
    NSLog(@"participantLeft:%@",data);
    //p2p 一方退出，就挂掉
    [self endJitsiMeetCall];
    [_jitsiView closeChat];
//    [self dismissViewControllerAnimated:YES completion:nil];
}


-(void)inispeacker{
    if(self.audioOnly){
        _isSpeacker=NO;
        [_jitsiView changeAudioSession:NO];
    }
    else{
        _isSpeacker=YES;
        [_jitsiView changeAudioSession:YES];
    }
    if(_isSpeacker){
        [_speackerBt setImage:[UIImage imageNamed:@"speaker_off_icon"] forState:UIControlStateNormal];
    }
    else{
        [_speackerBt setImage:[UIImage imageNamed:@"speaker_on_icon"] forState:UIControlStateNormal];
    }
    
}



- (UIStatusBarStyle)preferredStatusBarStyle {
    return UIStatusBarStyleLightContent; // 返回白色状态栏
}

#pragma mark lazy
- (AVAudioPlayer *)audioPlayer{
    
    if (!_audioPlayer) {
        NSURL *ringtoneURL = [[NSBundle mainBundle] URLForResource:@"ring" withExtension:@"wav"];
        _audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:ringtoneURL error:nil];
        _audioPlayer.delegate = self;
        [_audioPlayer setNumberOfLoops:-1];
    }
    NSLog(@"audioPlayer1122----");
   
    return _audioPlayer;
}
- (void)enterPictureInPicture:(NSDictionary *)data{
    NSLog(@"enterPictureInPicture-------------");
}


@end
