//
//  GMDoctorVideoTelephoneWindow.m
//  Gengmei
//
//  Created by 卢悦明 on 2020/2/20.
//  Copyright © 2020 更美互动信息科技有限公司. All rights reserved.
//

#import "GMDoctorVideoTelephoneWindow.h"
#import "GMDoctorTelephoneFunctionView.h"
#import "GMDoctorRecommendShoppingView.h"
#import "GMLinkPromptView.h"
#import "GMUserFillMessageView.h"
#import "GMVideoPhobos.h"
@interface GMDoctorVideoTelephoneWindow ()<TTTRtcEngineDelegate, GMDoctorTelephoneFunctionViewDelegate>
@property (nonatomic, strong) GMDoctorRecommendShoppingView *shoppingView;
@property (nonatomic, strong) GMRtcManager *TTManager;
@property (nonatomic, strong) GMDoctorTelephoneFunctionView *functionView;
@end

@implementation GMDoctorVideoTelephoneWindow
{
    CGFloat _scele;
    GMTTTUser *_user;//加入进来的医生模型
    GMLinkPromptView *_linePrompView;
    GMUserFillMessageView *_userMessagLabel; //用户信息
}

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        self.windowStatu = YES;
        self.pageName = @"video_face_consultation_doctor";
        
        self.callCenter = [[CTCallCenter alloc] init];
             __weak typeof(self) weakedSelf = self;
             self.callCenter.callEventHandler = ^(CTCall * call){
                 dispatch_async(dispatch_get_main_queue(), ^{
                     if ([call.callState isEqualToString:CTCallStateDialing]) {
                         NSLog(@"电话主动拨打电话");
                         [weakedSelf.TTManager muteLocalAudioStream:YES];
                         [weakedSelf.functionView changMutedSelf:YES];
                     } else if ([call.callState isEqualToString:CTCallStateConnected]) {
                         NSLog(@"电话接通");
                         [weakedSelf.TTManager muteLocalAudioStream:YES];
                         [weakedSelf.functionView changMutedSelf:YES];
                     } else if ([call.callState isEqualToString:CTCallStateDisconnected]) {
                         NSLog(@"电话挂断");
                         [weakedSelf.TTManager muteLocalAudioStream:NO];
                         [weakedSelf.functionView changMutedSelf:NO];
                     } else if ([call.callState isEqualToString:CTCallStateIncoming]) {
                         NSLog(@"电话被叫");
                         [weakedSelf.TTManager muteLocalAudioStream:YES];
                         [weakedSelf.functionView changMutedSelf:YES];
                     } else {
                         NSLog(@"电话其他状态");
                     }
                 });
                     
             };
        
        [self setupUI];
    }
    return self;
}

- (void)setupUI {
    _TTManager = [GMRtcManager sharedRtcManager];
    _TTManager.rtcEngine.delegate = self;
    _scele = 0.3;
    
    CGRect userFrame;
    CGRect doctorFrame;
    CGFloat width = MAINSCREEN_WIDTH * _scele;
    CGFloat heigh = MAINSCREEN_HEIGHT * _scele;
    if (_TTManager.me.clientRole ==TTTRtc_ClientRole_Anchor) {
        doctorFrame = self.bounds;
        userFrame = CGRectMake(MAINSCREEN_WIDTH - width - 4, OCNavigationBar.barHeight + 35, width, heigh);
        self.windowStatu = NO;
    }else {
        userFrame = self.bounds;
        doctorFrame = CGRectMake(MAINSCREEN_WIDTH - width - 4, OCNavigationBar.barHeight + 35, width, heigh);
        self.windowStatu = YES;
    }
    //医生图层
    self.userVideoView = [[GMAVRegionView alloc] initWithFrame:userFrame];
    [self insertSubview:self.userVideoView atIndex:0];
    self.userVideoView.backgroundColor = [UIColor blackColor];
    [self layoutIfNeeded];
    
//   设置用户图层
    self.doctorVideoView = [[GMAVRegionView alloc] initWithFrame:doctorFrame];
    self.doctorVideoView.backgroundColor = [UIColor blackColor];
    self.doctorVideoView.layer.masksToBounds = YES;
    self.doctorVideoView.layer.cornerRadius = 4;
    [self addSubview:self.doctorVideoView];
    [_TTManager.rtcEngine startPreview];
    [self.doctorVideoView configureRegion:_TTManager.me];
    
    //用户信息
    _userMessagLabel = [[GMUserFillMessageView alloc] initWithFrame:CGRectMake(0, OCNavigationBar.barHeight - 10, MAINSCREEN_WIDTH, 80)];
    _userMessagLabel.model = _TTManager.vidoeTelephoneModel;
    [self addSubview:_userMessagLabel];
    
    //功能区
    _functionView = [[GMDoctorTelephoneFunctionView alloc] initWithFrame:CGRectMake(0, MAINSCREEN_HEIGHT - 135 - (UIView.safeAreaInsetsBottom + 32), MAINSCREEN_WIDTH, 135)];
    _functionView.delegate = self;
    [self addSubview:_functionView];
    
    //购物袋
    _shoppingView = [[GMDoctorRecommendShoppingView alloc] initWithFrame:CGRectMake(0, MAINSCREEN_HEIGHT - 500, MAINSCREEN_WIDTH, 500)];
    self.shoppingView.model = _TTManager.vidoeTelephoneModel;
    _shoppingView.hidden = YES;
    [self addSubview:_shoppingView];

    //提示语
    _linePrompView = [[GMLinkPromptView alloc] init];
    _linePrompView.hidden = YES;
    [self addSubview:_linePrompView];
    if (_TTManager.me.clientRole == TTTRtc_ClientRole_Anchor) {
        [self linePrompViewWarming:@"用户正在接入中，一个良好的面诊环境会更专业哦~"];
    }
    
    //添加手势
    self.pan = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(panMiniVideoVidew:)];
    [self addVideoPan];
    [self layoutVideoView];

}


#pragma mark - 提示语
- (void)linePrompViewWarming:(NSString *)text {
    _linePrompView.hidden = NO;
    _linePrompView.text = text;
    CGFloat labelW = [self getWidth:_linePrompView.text font:14 LimitHeight:15];
    [_linePrompView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.mas_centerX);
        make.centerY.equalTo(self.mas_centerY);
        make.size.mas_equalTo(CGSizeMake(labelW + 60, 50));
    }];
}

#pragma mark - 超时退出直播间
- (void)userExitTime {
    [super userExitTime];
    [GMHudModule showWarning:@"用户取消，连线结束"];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self exitRoom:NO];
    });
}

#pragma mark - 拖拽shoushi
- (void)panMiniVideoVidew:(UIPanGestureRecognizer *)pan {
    if (pan.state == UIGestureRecognizerStateEnded) {
        [self touchEnd:pan];
    }else {
        [self touchMove:pan];
    }
}

#pragma mark - 功能区点击回调
- (void)doctorClicBtnAction:(DoctorTelephoneFunctionType)type Status:(BOOL)status
{
    switch (type) {
        case DoctorTelephoneFunctionType_shopping:{//购物
            _shoppingView.hidden = NO;
            [self phobosName:@"shopping_bag"];
        }
            break;
        case DoctorTelephoneFunctionType_song:{//静音
            [_TTManager muteLocalAudioStream:status];
        }
            break;
        case DoctorTelephoneFunctionType_guaDuan:{//挂断
            [self phobosName:@"hangup"];
            [self closeRoom:YES];
            [GMVideoPhobos video_monitoringWithActionStep:@"关闭通话页" consultId:_TTManager.consultationRecordId traceId:nil];
        }
            break;
        case DoctorTelephoneFunctionType_meiyan:{//美颜
            [_TTManager beautyStatus:status];
        }
            break;
        case DoctorTelephoneFunctionType_switchCamera:{//切换摄像头
            [_TTManager switchCamera];
        }
            break;
            
        default:
            break;
    }
}

- (void)phobosName:(NSString *)button_name {

    [Phobos track:@"on_click_button" attributes:@{
        @"page_name":self.pageName,
        @"button_name":button_name,
        @"doctor_id": SafeString(_TTManager.vidoeTelephoneModel.counsellorInfo.doctorId),
        @"user_id":SafeString(_TTManager.vidoeTelephoneModel.userInfo.userId),
        @"referrer":SafeString(self.referer),
    }];
}
#pragma mark - 记录通话时长
- (void)doctorTimeChange:(int)currentTime {
    _TTManager.totalTime = currentTime;
    [GMVideoTelephoneRequestTool telephoneMessageEventType:GMEventType_video consultationRecordId:_TTManager.consultationRecordId finishBlock:nil];
}

#pragma mark - 退出房间 status yes 正常退出 no 异常退出
- (void)exitRoom:(BOOL) status {
    [_functionView endTime];
    [_TTManager closeExcitRoom];
    [UIView animateWithDuration:0.4 animations:^{
        self.transform = CGAffineTransformTranslate(self.transform, 0,MAINSCREEN_HEIGHT);
    } completion:^(BOOL finished) {
        self.hidden = YES;
        [self removeFromSuperview];
    }];
    GMEventType type = status ? GMEventType_zhuDongExit :GMEventType_beiDongExit;

    [GMVideoTelephoneRequestTool telephoneMessageEventType:type consultationRecordId:_TTManager.consultationRecordId finishBlock:^(BOOL success, NSDictionary *message) {
        if (success) {
            GMTelphoneStatusModel *model = message[@"model"];
            _TTManager.totalTime = [model.callDuration intValue];
        }
        if ([self.delgate respondsToSelector:@selector(nomalExitRoom)]) {
            [self.delgate nomalExitRoom];
        }
    }];
}

- (void)closeRoom:(BOOL) status {
    if (_TTManager.totalTime < 180) {
        UIViewController *alertVC = [[UIViewController alloc]init];
        [self addSubview:alertVC.view];
        UIAlertController *alert =  [UIAlertController alertControllerWithTitle:@"提示" message:@"本次视频面诊时间貌似有点短，确定不再聊会儿？" preferredStyle:UIAlertControllerStyleAlert];
        [alert addAction:[UIAlertAction actionWithTitle:@"再聊一会" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            alertVC.view = nil;
        }]];
        UIAlertAction *sureAction = [UIAlertAction actionWithTitle:@"结束面诊" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            alertVC.view = nil;
            [GMHudModule showWarning:@"通话结束"];
            [self exitRoom:status];
        }];
        [alert addAction:sureAction];
        [alertVC presentViewController:alert animated:YES completion:NULL];
    } else {
        [GMHudModule showWarning:@"通话结束"];
        [self exitRoom:status];
    }

}

#pragma mark - 协议方法
#pragma mark -  有人进入直播间
- (void)rtcEngine:(TTTRtcEngineKit *)engine didJoinedOfUid:(int64_t)uid clientRole:(TTTRtcClientRole)clientRole isVideoEnabled:(BOOL)isVideoEnabled elapsed:(NSInteger)elapsed {
    _user = [[GMTTTUser alloc] initWith:uid];
    _user.clientRole = clientRole;
    _TTManager.telephoneStatus = TelephoneVideoStatus_video;
    if (clientRole == TTTRtc_ClientRole_Anchor) {//主播进入
        [self.userVideoView configureRegion:_user];
        [_TTManager setTelephoneVideoCompositingLayout:self.windowStatu userId:uid doctorId:_TTManager.me.uid];
        [_functionView startTime];
    } else if (clientRole == TTTRtc_ClientRole_Broadcaster) {//副播进入
        if (_TTManager.me.clientRole == TTTRtc_ClientRole_Anchor) {
            [self switchVideoWindow:YES];
        }
        _linePrompView.hidden = YES;
        [self.userVideoView configureRegion:_user];
        [_TTManager setTelephoneVideoCompositingLayout:self.windowStatu userId:uid doctorId:_TTManager.me.uid];
        [GMHudModule toastInView:self text:@"已接通"];
        
        [GMVideoTelephoneRequestTool telephoneMessageEventType:GMEventType_video consultationRecordId:_TTManager.consultationRecordId finishBlock:^(BOOL success, NSDictionary *message) {
                   if (success) {
                       // 在医生抢单的瞬间，用户取消派单会出现 医生进入视频页面一直不取消，所以加此处理逻辑
                       if ([message.allKeys containsObject:@"model"]) {
                           GMTelphoneStatusModel *model = message[@"model"];
                           if (model.status == 3) { // 已结束
                               [self userExitTime];
                           }
                       }
                   }

               }];

        
        [_functionView startTime];
    }
    
    if ([self.delgate respondsToSelector:@selector(videoLiveIn)]) {
        [self.delgate videoLiveIn];
    }
}
#pragma mark - 错误回调
- (void)rtcEngine:(TTTRtcEngineKit *)engine didOccurError:(TTTRtcErrorCode)errorCod {
    if (errorCod == TTTRtc_Error_NoError) {
        //没错误
    } else if (errorCod == TTTRtc_Error_InvalidChannelName) {
        [self exitRoom:NO];
        [GMHudModule showWarning:@"超时未接听,对方已取消"];
    } else {
        [self exitRoom:NO];
        [GMHudModule showWarning:@"通话中断"];
    }
}

#pragma mark - 主播退出房间(自己是副播的时候调用)
- (void)rtcEngine:(TTTRtcEngineKit *)engine didKickedOutOfUid:(int64_t)uid reason:(TTTRtcKickedOutReason)reason {
    
    if (reason == TTTRtc_KickedOut_MasterExit) {
        //主播退出房间
        [GMHudModule showWarning:@"通话结束"];
    } else {
        [GMHudModule showWarning:@"通话中断"];
    }
    [self exitRoom:NO];
}

#pragma mark -  副播离线回调(自己是主播的时候调用)
- (void)rtcEngine:(TTTRtcEngineKit *)engine didOfflineOfUid:(int64_t)uid reason:(TTTRtcUserOfflineReason)reason {
    if (_user.uid == uid && _user.clientRole == TTTRtc_ClientRole_Broadcaster) {
        //医生离开房间
        [GMHudModule showWarning:@"通话结束"];
        [self exitRoom:NO];
    }
}

@end
