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

#import "GMUserVideoTelephoneWindow.h"
#import "GMUserTelephoneFunctionView.h"
#import "GMVideoTelephoneRecommendShoppingView.h"
#import "GMTelephoneAttentionView.h"
#import "GMLinkPromptView.h"
#import "GMTelephoneAudioPlay.h"
#import "GMVideoPhobos.h"
#import <GMBase/GMBaseTool.h>


@interface GMUserVideoTelephoneWindow ()<TTTRtcEngineDelegate, GMTelephoneFunctionViewDelegate, GMRecommendShoppingDelegate, GMTelephoneAttentionViewDelegate>
{
    
    CGFloat _scele; //大小窗口的比例
    UIButton *_switchWindowBtn;//切换窗口
    GMVideoTelephoneRecommendShoppingView *_shoppingView;
    GMTelephoneAttentionView *_attentionView;//关注
    GMTTTUser *doctorUser;//加入进来的医生模型
    GMLinkPromptView *_linePrompView;
    GMTelephoneAudioPlay *_audioPlay;
}
@property (nonatomic, strong) GMRtcManager *TTManager;
@property (nonatomic, strong)GMUserTelephoneFunctionView *functionView;
@end

@implementation GMUserVideoTelephoneWindow

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        //医生拒绝 需要用户挂断
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(userJujue) name:@"gm_doctor_cancal" object:nil];
        
        //用户退出登录需要挂断
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(userLogout) name:@"userLogout" object:nil];
        
        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 {
                    [weakedSelf.TTManager muteLocalAudioStream:YES];
                    [weakedSelf.functionView changMutedSelf:YES];
                    NSLog(@"电话其他状态");
                }
            });
        };
        
        self.pageName = @"video_face_consultation_user";
        [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) {
        userFrame = self.bounds;
        doctorFrame = CGRectMake(MAINSCREEN_WIDTH - width - 4, OCNavigationBar.barHeight + 25, width, heigh);
        self.windowStatu = YES;
        _audioPlay = [[GMTelephoneAudioPlay alloc] initWithAudioSource:@"videoTelephone" ofType:@".mp3"];
        [_audioPlay startAudioPlay];
    }else {
        doctorFrame = self.bounds;
        userFrame = CGRectMake(MAINSCREEN_WIDTH - width - 4, OCNavigationBar.barHeight + 25, width, heigh);
        self.windowStatu = NO;
    }

    //医生图层
    self.doctorVideoView = [[GMAVRegionView alloc] initWithFrame:doctorFrame];
    self.doctorVideoView.backgroundColor = [UIColor blackColor];
    [self addSubview:self.doctorVideoView];
    //   设置用户图层
    self.userVideoView = [[GMAVRegionView alloc] initWithFrame:userFrame];
    self.userVideoView.backgroundColor = [UIColor blackColor];
    [self addSubview:self.userVideoView];
    [_TTManager.rtcEngine startPreview];
    [self.userVideoView configureRegion:_TTManager.me];

    [self layoutIfNeeded];
    [self layoutVideoView];
    
    
    //功能区
    _functionView = [[GMUserTelephoneFunctionView alloc] initWithFrame:CGRectMake(0, MAINSCREEN_HEIGHT - 135 - (UIView.safeAreaInsetsBottom + 30), MAINSCREEN_WIDTH, 135)];
    _functionView.delegate = self;
    [self addSubview:_functionView];
    
    //关注人头像
    _attentionView = [[GMTelephoneAttentionView alloc] initWithFrame:CGRectMake(20, OCNavigationBar.statusBarHeight + 10, 170, 50)];
    _attentionView.delegate = self;
    _attentionView.model = _TTManager.vidoeTelephoneModel;
    [self addSubview:_attentionView];
    
    //切换医生用户大小窗口按钮
    _switchWindowBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    _switchWindowBtn.hidden = YES;
    [_switchWindowBtn setImage:[UIImage imageNamed:@"telephone_switch"] forState:UIControlStateNormal];
    [_switchWindowBtn setImage:[UIImage imageNamed:@"telephone_switch"] forState:UIControlStateHighlighted];
    [_switchWindowBtn setImage:[UIImage imageNamed:@"telephone_switch"] forState:UIControlStateSelected];
    [_switchWindowBtn addTarget:self action:@selector(switchWindow:) forControlEvents:UIControlEventTouchUpInside];
    [self addSubview:_switchWindowBtn];
    [_switchWindowBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(25, 25));
        make.centerY.equalTo(_attentionView.mas_centerY);
        make.right.equalTo(self.mas_right).offset(-14);
    }];
    
    _linePrompView = [[GMLinkPromptView alloc] init];
    _linePrompView.hidden = YES;
    [self addSubview:_linePrompView];
    if (_TTManager.me.clientRole == TTTRtc_ClientRole_Anchor) {
        [self linePrompViewWarming:@"等待接通中..."];
    }
    

    //购物车View
    _shoppingView = [[GMVideoTelephoneRecommendShoppingView alloc] initWithFrame:self.bounds];
    _shoppingView.hidden = YES;
    _shoppingView.delegate = self;
    _shoppingView.recordId = _TTManager.consultationRecordId;
    [_shoppingView reloadTableMessage];
    [self addSubview:_shoppingView];
    
    //添加手势
    self.pan = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(panMiniVideoVidew:)];
    [self addVideoPan];
    
}

#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)userJujue {
    [self exitRoom:NO];
    [GMHudModule showWarning:@"接入失败，视频面诊将关闭，本次视频面诊订单金额将原路退还至您的账户中"];
    [GMVideoPhobos video_monitoringWithActionStep:@"phone_cancel" consultId:_TTManager.consultationRecordId traceId:nil];
}

#pragma mark - 超时（需要用户退出直播间）
- (void)userExitTime {
    [super userExitTime];
    [self exitRoom:NO];
    [GMHudModule showWarning:@"抱歉，对方暂时不在,本次视频面诊订单金额将原路退还至您的账户中"];
}

#pragma mark - 用户退出登录
- (void)userLogout {
    [self exitRoom:NO];
}
#pragma mark - 点击美购进入美购详情
- (void)selectedIndex:(NSInteger)index welfareId:(NSString *)welfareId {
    [self windowMini];
    [Phobos track:@"welfare_multiattribute_click_add" attributes:@{
        @"page_name":self.pageName,
        @"referrer_tab_name":SafeString(self.referrerTabName),
        @"service_id":welfareId,
        @"doctor_id":SafeString(_TTManager.vidoeTelephoneModel.counsellorInfo.doctorId) ,
        @"referrer":self.referer,
    }];
    NSString *url = [NSString stringWithFormat:@"gengmei://service?service_id=%@&referer=%@&customRefererLink=%@", welfareId,self.pageName,self.pageName];
    [[GMRouter sharedInstance] pushScheme:url];
}

#pragma mark - 关闭购物页面
- (void)closeShoppingView {
    _shoppingView.hidden = YES;
}

#pragma mark - 点击关注/取消关注按钮
- (void)clickGuanZhu:(BOOL)status {
    [self phobosName:@"attention" extent:nil];
    //2为面诊师
    NSString *type = _TTManager.vidoeTelephoneModel.counsellorInfo.counsellorType == 2 ? @"0":@"1";
    NSString *idStr = _TTManager.vidoeTelephoneModel.counsellorInfo.counsellorType == 2 ? _TTManager.vidoeTelephoneModel.counsellorInfo.userId : _TTManager.vidoeTelephoneModel.counsellorInfo.doctorId;
    [GMVideoTelephoneRequestTool followOrNot:status withUid:idStr type:type finishBlock:^(BOOL success, NSString *message) {
    }];
}

#pragma mark - 点击window
- (void)windowTap:(UITapGestureRecognizer *)tap {
    if (tap.state == UIGestureRecognizerStateEnded) {
        [self removeGestureRecognizer:tap];
    }
    self.layer.cornerRadius = 0.0;
    self.frame = [UIScreen mainScreen].bounds;
    _attentionView.hidden = NO;
    _functionView.hidden = NO;
    _switchWindowBtn.hidden = NO;
    [self addVideoPan];
}

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

#pragma mark - 切换医生用户大小试图
- (void)switchWindow:(UIButton *)sender {
    sender.selected = !sender.selected;
    [self switchVideoWindow:sender.selected];
}

#pragma mark - 功能区点击回调
- (void)clicBtnAction:(TelephoneFunctionType)type Status:(BOOL)status {
    switch (type) {
        case TelephoneFunctionType_shopping:{//购物
            _shoppingView.hidden = NO;
            NSMutableArray *array = _shoppingView.serviceIdArray;
            [self phobosName:@"shopping_bag" extent:@{
                @"service_num":@(array.count),
                @"service_id":array,
            }];

        }
            break;
        case TelephoneFunctionType_song:{//静音
            [_TTManager muteLocalAudioStream:status];
        }
            break;
        case TelephoneFunctionType_guaDuan:{//挂断
            [self phobosName:@"hangup" extent:nil];
            if (_TTManager.telephoneStatus == TelephoneVideoStatus_video) {
                //视频中
                [GMHudModule showWarning:@"通话结束"];
                [GMVideoPhobos video_monitoringWithActionStep:@"关闭通话页" consultId:_TTManager.consultationRecordId traceId:nil];
                [self closeRoom:YES];
            } else {
                //未接通的挽留弹框
                [self showAlert];
            }
        }
            break;
        case TelephoneFunctionType_minWindow:{//小窗口
            [self windowMini];
        }
            break;
        case TelephoneFunctionType_switchCamera:{//切换摄像头
            [_TTManager switchCamera];
        }
            break;
            
        default:
            break;
    }
}

#pragma mark - 更新记录通话时长
- (void)userTimeChange:(int)currentTime {
    _TTManager.totalTime = currentTime;
    [GMVideoTelephoneRequestTool telephoneMessageEventType:GMEventType_video consultationRecordId:_TTManager.consultationRecordId finishBlock:nil];
}

#pragma mark - 变成小窗口
- (void)windowMini {
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(windowTap:)];
    [self addGestureRecognizer:tap];
    _shoppingView.hidden = YES;
    _functionView.hidden = YES;
    _switchWindowBtn.hidden = YES;
    _attentionView.hidden = YES;
    self.layer.cornerRadius = 5;
    CGFloat width = MAINSCREEN_WIDTH * _scele;
    CGFloat heigh = MAINSCREEN_HEIGHT * _scele;
    self.frame = CGRectMake(MAINSCREEN_WIDTH - width - 4, 100, width, heigh);
    [self addGestureRecognizer:self.pan];
}

- (void)closeRoom:(BOOL) status {
    if (_TTManager.totalTime < 180) {
        NSString *title = _TTManager.vidoeTelephoneModel.counsellorInfo.counsellorType == 2 ? @"面诊师":@"医生";
        NSString *name = [NSString stringWithFormat:@"%@擅长很多项目，可以多咨询呦",title];
        UIAlertController *alert =  [UIAlertController alertControllerWithTitle:@"提示" message:name preferredStyle:UIAlertControllerStyleAlert];
        [alert addAction:[UIAlertAction actionWithTitle:@"再聊一会" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        }]];
        UIAlertAction *sureAction = [UIAlertAction actionWithTitle:@"结束面诊" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [GMHudModule showWarning:@"通话结束"];
            [self exitRoom:status];
        }];
        [alert addAction:sureAction];
        [[GMBaseTool getCurrentViewController] presentViewController:alert animated:YES completion:NULL];
    } else {
        [GMHudModule showWarning:@"通话结束"];
        [self exitRoom:status];
    }
}

#pragma mark - 未接通的页面挽留弹窗
- (void)showAlert {
    NSString *title = _TTManager.vidoeTelephoneModel.counsellorInfo.counsellorType == 2 ? @"面诊师":@"医生";
    NSString *alertTitle = [NSString stringWithFormat:@"等待接通中，再等一下，%@马上就来",title];
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:alertTitle preferredStyle:UIAlertControllerStyleAlert];
    [alert addAction:[UIAlertAction actionWithTitle:@"去意已决" style: UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self exitRoom:YES];
        [GMVideoPhobos video_monitoringWithActionStep:@"点击挂断按钮" consultId:_TTManager.consultationRecordId traceId:nil];
    }]];
    [alert addAction:[UIAlertAction actionWithTitle:@"继续等待" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {}]];
    UIAlertAction *action = alert.actions.firstObject;
    //这个key是用 runtime属性列表Ivar遍历得到的
    [action setValue:RGBCOLOR_HEX(0x282828) forKey:@"titleTextColor"];
    [[GMBaseTool getCurrentViewController] presentViewController:alert animated:YES completion:nil];
}

#pragma mark - 退出房间 yes 主动离线  no 被动
- (void)exitRoom:(BOOL)status {
    [_TTManager closeExcitRoom];
    [_functionView endTime];
    
    if ([[GMBaseTool getCurrentViewController] isKindOfClass:[UIAlertController class]]) {
        [[GMBaseTool getCurrentViewController] dismissViewControllerAnimated:YES completion:nil];
    }
    
    [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 (_TTManager.totalTime == 0 && status) {//没有接通并主动离开的时候会退款
                [[GMBaseTool getCurrentViewController] toast:@"视频面诊已取消，本次视频面诊订单金额将原路退还至您的账户中"];
            }
        }
        if ([self.delgate respondsToSelector:@selector(nomalExitRoom)]) {
            [self.delgate nomalExitRoom];
        }
    }];
}

#pragma mark - 有人进入直播间
- (void)rtcEngine:(TTTRtcEngineKit *)engine didJoinedOfUid:(int64_t)uid clientRole:(TTTRtcClientRole)clientRole isVideoEnabled:(BOOL)isVideoEnabled elapsed:(NSInteger)elapsed {
    doctorUser = [[GMTTTUser alloc] initWith:uid];
    doctorUser.clientRole = clientRole;
    _switchWindowBtn.hidden = NO;
    _linePrompView.hidden = YES;
    _TTManager.telephoneStatus = TelephoneVideoStatus_video;
    [_functionView startTime];
    
    if (clientRole == TTTRtc_ClientRole_Anchor) {
        [self.doctorVideoView configureRegion:doctorUser];
        [_TTManager setTelephoneVideoCompositingLayout:self.windowStatu userId:_TTManager.me.uid doctorId:uid];
    } else if (clientRole == TTTRtc_ClientRole_Broadcaster) {
        [self.doctorVideoView configureRegion:doctorUser];
        if (_TTManager.me.clientRole == TTTRtc_ClientRole_Anchor) {
            [self switchVideoWindow:NO];
            [_audioPlay stopAudioPlay];
        }
        [_TTManager setTelephoneVideoCompositingLayout:self.windowStatu userId:_TTManager.me.uid doctorId:uid];
        [GMHudModule toastInView:self text:@"已接通"];
    }
    
    if ([self.delgate respondsToSelector:@selector(videoLiveIn)]) {
        [self.delgate videoLiveIn];
    }
}

#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 (doctorUser.uid == uid && doctorUser.clientRole == TTTRtc_ClientRole_Broadcaster) {
        //医生离开房间
        [GMHudModule showWarning:@"通话结束"];
        [GMVideoPhobos video_monitoringWithActionStep:@"phone_cancel_issue" consultId:_TTManager.consultationRecordId traceId:nil];
        [self exitRoom:NO];
    }
}

#pragma mark - 错误回调
- (void)rtcEngine:(TTTRtcEngineKit *)engine didOccurError:(TTTRtcErrorCode)errorCod {
    
    if (errorCod != TTTRtc_Error_NoError) {
        [self exitRoom:NO];
        if (_TTManager.telephoneStatus == TelephoneVideoStatus_video) {
            [GMHudModule showWarning:@"通话中断"];
        } else {
            [GMHudModule showWarning:@"呼叫中断"];
        }
    }
}

- (void)phobosName:(NSString *)button_name extent:(NSDictionary *)params {
    NSMutableDictionary *dict = [[NSMutableDictionary alloc] initWithDictionary:@{
        @"page_name":self.pageName,
        @"button_name":button_name,
        @"doctor_id": SafeString(_TTManager.vidoeTelephoneModel.counsellorInfo.doctorId),
        @"referrer":SafeString(self.referer),
        @"referrer_tab_name":SafeString(self.referrerTabName),
    }];
    if (params) {
        [dict addEntriesFromDictionary:params];
    }

    [Phobos track:@"on_click_button" attributes:dict];
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
@end
