//
//  GMPlayerView.m
//  Gengmei
//
//  Created by 翟国钧 on 2016/12/13.
//  Copyright © 2016年 更美互动信息科技有限公司. All rights reserved.
//

#import "GMPlayerView.h"
//
//@implementation GMPlayerView
////临时...
//@end

#import "GMPlayerView.h"
#import <AVFoundation/AVFoundation.h>
#import <MediaPlayer/MediaPlayer.h>
#import <PLPlayerKit/PLPlayerKit.h>
//#import "GMFloatWindow.h"
#import "UIViewController+HUD.h"
#import "GMVideoBottomView.h"
#import "GMPlayerControlView.h"
#import "Alpha-Swift.h"
#import <MediaPlayer/MediaPlayer.h>
#import "UIView+SafeArea.h"
#import "IQUIView+Hierarchy.h"
#import "UIViewController+HUD.h"


@import GMNetworking;

@interface GMPlayerVolumeAndBrightView()
@property (nonatomic, strong) GMLabel *titleLabel;
@property (nonatomic, strong) GMImageView *imageView;
@end
@implementation GMPlayerVolumeAndBrightView
-(instancetype)initWithFrame:(CGRect)frame title:(NSString *)title image:(UIImage *)image {
    if (self == [super initWithFrame:frame]) {
        self.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.8];
        self.layer.cornerRadius = 2;
        self.layer.masksToBounds = YES;

        _titleLabel = [GMLabel labelWithTextColor:UIColor.whiteColor fontSize:14];
        _titleLabel.text = title;
        _titleLabel.textAlignment = NSTextAlignmentCenter;
        [self addSubview:_titleLabel];

        _imageView = [[GMImageView alloc] initWithImage:image];
        [self addSubview:_imageView];

        _progressView = [[UIProgressView alloc] init];
        _progressView.progressTintColor = UIColor.whiteColor;
        _progressView.trackTintColor = [UIColor.whiteColor colorWithAlphaComponent:.3];
        [self addSubview:_progressView];

        [self.progressView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(self).offset(20);
            make.right.equalTo(self).offset(-20);
            make.bottom.equalTo(self).offset(-17 - ONE_PIXEL);
            make.height.mas_equalTo(1 + ONE_PIXEL);
        }];
        [self.titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.height.mas_equalTo(14);
            make.width.mas_equalTo(28);
            make.centerX.mas_equalTo(self.progressView.mas_centerX);
            make.top.equalTo(self).offset(15);
        }];
        [self.imageView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.titleLabel.mas_bottom).offset(10);
            make.centerX.mas_equalTo(self.progressView.mas_centerX);
        }];

    }
    return self;
}
@end

@implementation GMPlayerFastSpeedView
- (instancetype)init {
    if (self == [super init]) {
        self.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.8];
        self.layer.cornerRadius = 2;
        self.layer.masksToBounds = YES;

        _timeLabel = [GMLabel labelWithTextColor:UIColor.whiteColor fontSize:14];
        _timeLabel.textAlignment = NSTextAlignmentCenter;
        [self addSubview:_timeLabel];

        _imageView = [[GMImageView alloc] init];
        [self addSubview:_imageView];

        [self.imageView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.height.mas_equalTo(16);
            make.width.mas_equalTo(24);
            make.centerY.mas_equalTo(self.mas_centerY);
            make.left.equalTo(self).offset(22);
        }];
        [self.timeLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerY.mas_equalTo(self.imageView.mas_centerY);
            make.left.equalTo(self.imageView.mas_right).offset(5);
        }];
    }
    return self;
}


@end

@interface GMPlayerView()<PLPlayerDelegate, GMVideoBottomViewDelegate, GMPlayerControlViewDelegate, UIGestureRecognizerDelegate>
@property (nonatomic, assign) CGRect initialPlayerFrame;
@property (nonatomic, strong) UIActivityIndicatorView *indicator;

@property (nonatomic, strong) GMPlayerControlView *controlView;
@property (nonatomic, strong) GMVideoBottomView *bottomView;
@property (nonatomic, assign) float currentTime;
@property (nonatomic, strong) UIView *mySuperView;

@property (nonatomic, strong) UIPanGestureRecognizer *panGesture;
@property (nonatomic, strong) UITapGestureRecognizer *tapGesture;
@property (nonatomic, assign) UIDeviceOrientation deviceOrientation;

@property (nonatomic, assign) CGPoint startPoint;
@property (nonatomic, assign) CGFloat startVB;
@property (nonatomic, assign) CGFloat startVideoRate;
@property (nonatomic, assign) TouchDirection direction;
@property (nonatomic, assign) CGFloat currentRate;//当期视频播放的进度

@property (nonatomic, strong) GMPlayerVolumeAndBrightView *volumeView;//音量的view
@property (nonatomic, strong) GMPlayerVolumeAndBrightView* brightView;//亮度
@property (nonatomic, strong) GMPlayerFastSpeedView* fastSpeedView;//快进快推

// 埋点使用
@property (nonatomic, copy) NSString *startTime;
@property (nonatomic, copy) NSString *endTime;

// 系统的音量
@property (strong, nonatomic) MPVolumeView *systemVolumeView;//控制音量的view
@property (strong, nonatomic) UISlider* volumeViewSlider;//控制音量



@property (nonatomic, strong) AVAsset *movieAsset;
@property (nonatomic, strong) AVPlayerItem *playerItem;
@property (nonatomic, strong) AVPlayer *player;
@property (nonatomic, strong) AVPlayerLayer *playerLayer;
@property (nonatomic, strong) GMView *voiceView;
@property (nonatomic, strong) GMView *backView;

@end

@implementation GMPlayerView {
    GMImageView *_imageView;
    GMButton *_closeButton;
    id _observer;
    BOOL _isUserStop; // 用户是否点击暂停
}

- (instancetype)init{
    self = [super init];
    [self setup];
    return self;
}
- (instancetype)initNoTopicId {
    self = [super init];
    [self setup];
    _topicId = @"";
    _from = @"";
    return self;
}

- (void)setup {
    self.clipsToBounds = YES;
    self.frame = CGRectMake(MAINSCREEN_WIDTH/2 , MAINSCREEN_HEIGHT/2, 0, 0);
    self.userInteractionEnabled = YES;

    self.deviceOrientation = UIDeviceOrientationPortrait;
    self.systemVolumeView.hidden = NO;
    [self addSubview:self.systemVolumeView];

    _backView = [[GMView alloc] init];
    _backView.backgroundColor = [UIColor headlineText];
    [self addSubview:_backView];
    [_backView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.right.left.bottom.mas_equalTo(0);
    }];

    self.indicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
    [self addSubview:self.indicator];
    [self.indicator startAnimating];
    [self.indicator mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.equalTo(self);
        make.width.mas_equalTo(MAINSCREEN_WIDTH - 100);
        make.height.mas_equalTo(MAINSCREEN_HEIGHT - 200);
    }];

    _voiceView = [[GMView alloc] init];
    [self addSubview:_voiceView];
    [_voiceView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.right.left.bottom.mas_equalTo(0);
    }];

    _controlView = [[GMPlayerControlView alloc] init];
    _controlView.touchDelegate = self;
    [self addSubview:_controlView];

    self.volumeView = [[GMPlayerVolumeAndBrightView alloc] initWithFrame:self.bounds title:@"音量" image:[UIImage imageNamed:@"player_volume"]];
    [self addSubview:self.volumeView];
    [self.volumeView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.center.equalTo(self);
        make.width.mas_equalTo(110);
        make.height.mas_equalTo(110);
    }];

    self.brightView = [[GMPlayerVolumeAndBrightView alloc] initWithFrame:self.bounds title:@"亮度" image:[UIImage imageNamed:@"player_bright"]];
    [self addSubview:self.brightView];
    [self.brightView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.center.equalTo(self);
        make.width.mas_equalTo(110);
        make.height.mas_equalTo(110);
    }];

    self.fastSpeedView = [[GMPlayerFastSpeedView alloc] init];
    [self addSubview:self.fastSpeedView];
    [self.fastSpeedView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.center.equalTo(self);
        make.width.mas_equalTo(110);
        make.height.mas_equalTo(57);
    }];

    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(videoClickedEvent:)];
    // 当值为YES的时候，系统会识别手势，并取消触摸事件；为NO的时候，手势识别之后，系统将触发触摸事件。
    tap.cancelsTouchesInView = NO;
    [_controlView addGestureRecognizer:tap];

    _closeButton = [GMButton buttonWithType:UIButtonTypeCustom];
    [_closeButton setBackgroundImage:[UIImage imageNamed:@"player_back"] forState:UIControlStateNormal];
    [self addSubview:_closeButton];
    _closeButton.enableAdaptive = YES;
    [_closeButton mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(OCNavigationBar.statusBarHeight + 10);
        make.left.mas_equalTo(15);
        make.height.mas_equalTo(40);
        make.width.mas_equalTo(40);
    }];
    [_closeButton addTarget:self action:@selector(dismissSelf) forControlEvents:UIControlEventTouchUpInside];

    _bottomView = [[GMVideoBottomView alloc] init];
    _bottomView.delegate = self;
    [_bottomView.playButton addTarget:self action:@selector(clickPlayVideo:) forControlEvents:UIControlEventTouchUpInside];
    [_bottomView.processSlider addTarget:self action:@selector(changeProcessValue:) forControlEvents:UIControlEventValueChanged];
    [_bottomView.processSlider addTarget:self action:@selector(sliderTouchDown:) forControlEvents:UIControlEventTouchDown];
    [_bottomView.processSlider addTarget:self action:@selector(sliderTouchCancel:) forControlEvents:UIControlEventTouchCancel | UIControlEventTouchUpInside | UIControlEventTouchUpOutside];

    [self addSubview:_bottomView];

    [self sendSubviewToBack:self.volumeView];
    [self sendSubviewToBack:self.brightView];
    [self sendSubviewToBack:self.fastSpeedView];
}
- (MPVolumeView *)systemVolumeView {
    if (_systemVolumeView == nil) {
        _systemVolumeView  = [[MPVolumeView alloc] initWithFrame:CGRectMake(-1000, -1000, 10, 10)];
        _systemVolumeView.showsRouteButton = NO;
        //默认YES，这里为了突出，故意设置一遍
        _systemVolumeView.showsVolumeSlider = YES;
        [_systemVolumeView sizeToFit];
        for (UIView *view in [_systemVolumeView subviews]){
            if ([view.class.description isEqualToString:@"MPVolumeSlider"]){
                self.volumeViewSlider = (UISlider*)view;
                break;
            }
        }

    }
    return _systemVolumeView;
}

#pragma mark - 播放
- (void)play:(NSString *)url animationRect:(CGRect)rect {
    self.initialPlayerFrame = rect;
    if (CGRectIsEmpty(self.initialPlayerFrame)) {
        self.initialPlayerFrame = CGRectMake(MAINSCREEN_WIDTH/2, MAINSCREEN_HEIGHT/2, 0, 0);
    }

    _isUserStop = NO;
    [self play:url];
}

- (void)play:(NSString *)videoUrl {
    self.startTime = [PhobosUtil currentTime]; // 埋点使用
    // 直播的时候需要先关闭回放或者看直播的小窗口，但是不需要动画效果
//    [[AppDelegate shareInstance].videoFloatView hideWithNoAnimation];
    [self addViewNumber];
    [self showBottom];
    [[AppDelegate shareInstance].window addSubview:self];

    NSURL *sourceMovieURL = [NSURL URLWithString:videoUrl];
    _movieAsset = [AVURLAsset URLAssetWithURL:sourceMovieURL options:nil];
    _playerItem = [AVPlayerItem playerItemWithAsset:_movieAsset];
    _player = [AVPlayer playerWithPlayerItem:_playerItem];
    _playerLayer = [AVPlayerLayer playerLayerWithPlayer:_player];
    _playerLayer.videoGravity = AVLayerVideoGravityResizeAspect;
//    _player.volume = 1.f;

    if (_voiceView.layer.sublayers.count == 1) {
        [_voiceView.layer replaceSublayer:_voiceView.layer.sublayers.firstObject with:_playerLayer];
    } else {
        [_voiceView.layer addSublayer:_playerLayer];
    }
    [_player play];
    [self addProgressObserver];
    [self addActiveObserver];
    [self isHideSubviews:NO];

    // 动画
    [self mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(self.initialPlayerFrame.size);
        make.top.mas_equalTo(self.initialPlayerFrame.origin.y);
        make.left.mas_equalTo(self.initialPlayerFrame.origin.x);
    }];

    [self setNeedsUpdateConstraints];
    [self updateConstraintsIfNeeded];
    [self layoutIfNeeded];

    [UIView animateWithDuration:0.25 delay:0.2 options:UIViewAnimationOptionCurveEaseOut animations:^{
        [self reloadSubViewsWithSuperView:[AppDelegate shareInstance].window];
    } completion:nil];
}
// 卡片上自动播放视频的时候用这个方法
- (void)play:(NSString *)videoUrl backView:(UIView *)backView {
    [self.indicator startAnimating];
    _backView.backgroundColor = [UIColor bodyText];
    _isUserStop = NO;
    CGRect rect = [backView convertRect:backView.bounds toView:[AppDelegate shareInstance].window];
    self.initialPlayerFrame = rect;
    _mySuperView = backView;
    self.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
    NSURL *sourceMovieURL = [NSURL URLWithString:videoUrl];
    _movieAsset = [AVURLAsset URLAssetWithURL:sourceMovieURL options:nil];
    _playerItem = [AVPlayerItem playerItemWithAsset:_movieAsset];
    _player = [AVPlayer playerWithPlayerItem:_playerItem];
    _playerLayer = [AVPlayerLayer playerLayerWithPlayer:_player];
    _playerLayer.videoGravity = AVLayerVideoGravityResizeAspect;
    _player.volume = 0.f;

    if (_voiceView.layer.sublayers.count == 1) {
        [_voiceView.layer replaceSublayer:_voiceView.layer.sublayers.firstObject with:_playerLayer];
    } else {
        [_voiceView.layer addSublayer:_playerLayer];
    }
    [_player play];
    [self isHideSubviews:YES];
    [self addProgressObserver];
    [self addActiveObserver];
    [backView addSubview:self];
    [self reloadSubViewsWithSuperView:backView];
}

- (void)stop {
        if (!self.player) {
            return;
        }
        [_player pause];
        [_player cancelPendingPrerolls];
        [_player.currentItem cancelPendingSeeks];
        [_player.currentItem.asset cancelLoading];
        [_player removeTimeObserver:_observer];
        _playerLayer = nil;
        _movieAsset = nil;
        _playerItem = nil;
        _player = nil;
}
#pragma mark - AVPlayer
- (void)addActiveObserver {



    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(didBecomeActive)
                                                 name:UIApplicationDidBecomeActiveNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(willResignActive)
                                                 name:UIApplicationWillResignActiveNotification
                                               object:nil];

    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(volumeChanged:) name:@"AVSystemController_SystemVolumeDidChangeNotification"
                                               object:nil];
    // 因耳机也可控制远程音量
    [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
}

- (void)willResignActive {
    _bottomView.playButton.selected = YES;
    if (self.player) {
        [self.player pause];
    }
}

- (void)didBecomeActive{
    if (!_isUserStop) {
        if ([AFNetworkReachabilityManager sharedManager].networkReachabilityStatus == AFNetworkReachabilityStatusNotReachable) {
//            [self.viewController toast:@"网络情况欠佳，请检查网络"];
            return;
        }
        _bottomView.playButton.selected = NO;
        // [self.player seekToTime:self.time toleranceBefore:kCMTimeZero toleranceAfter:kCMTimeZero completionHandler: 这个方法会有一些问题，例如在刚启动播放的时候，以及在播放到最后一帧的时候，首先是其有可能会出现异常并crash.所以用了@try@catch来捕获这个异常，当出现异常的时候直接调用play让播放器自己决定播放的进度。
        @try {
            [self.player seekToTime:CMTimeMakeWithSeconds(self.currentTime, 600) toleranceBefore:kCMTimeZero toleranceAfter:kCMTimeZero completionHandler:^(BOOL finished) {
                if (finished) {
                    [self.player play];
                }
            }];
        } @catch (NSException *exception) {
            [self.player play];
        }
    }
}

// 远程控制变化通知
- (void)volumeChanged:(NSNotification *)notifi {

    // 判断当前通知是否是因改变音量的通知
    NSString *systemVolumeType = [notifi.userInfo objectForKey:@"AVSystemController_AudioCategoryNotificationParameter"]?:@"";
    BOOL isVideo = [systemVolumeType isEqualToString:@"Audio/Video"];
    if (isVideo) {
        // 音量变化后的值
        CGFloat volume = [[notifi.userInfo objectForKey:@"AVSystemController_AudioVolumeNotificationParameter"] floatValue];

        // 因更改音量值均会发出通知，此处只做View上的音量进度变化
        [self bringSubviewToFront:self.volumeView];
        self.volumeView.progressView.progress = volume;

        // 取消之前注册延迟.5f秒hiddenVolume方法
        [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(hiddenVolume) object:nil];

        // 添加延迟.5f秒hiddenVolume方法
        [self performSelector:@selector(hiddenVolume) withObject:nil afterDelay:0.5f];

    }
}

// 隐藏音量视图
- (void)hiddenVolume {
    [self sendSubviewToBack:_volumeView];
}

- (void)addProgressObserver {
    __weak typeof(self)weakSelf = self;
    _observer = [_player addPeriodicTimeObserverForInterval:CMTimeMake(1.0, 1.0) queue:dispatch_get_global_queue(0, 0) usingBlock:^(CMTime time) {
        if ([AFNetworkReachabilityManager sharedManager].networkReachabilityStatus == AFNetworkReachabilityStatusNotReachable) {
            [weakSelf clickPlayVideo:weakSelf.bottomView.playButton];
            return;
        }
        if (CMTIME_IS_INDEFINITE(weakSelf.playerItem.duration)) {
            return;
        }
        weakSelf.currentTime = CMTimeGetSeconds(weakSelf.playerItem.currentTime);
        float totalTime = CMTimeGetSeconds(weakSelf.playerItem.duration);
        float f = weakSelf.currentTime / totalTime;
        if (f == 1) { // 播放完整个视频
            [weakSelf.player seekToTime:CMTimeMakeWithSeconds(0, 1) toleranceBefore:kCMTimeZero toleranceAfter:kCMTimeZero completionHandler:^(BOOL finished) {
                [weakSelf.player play]; // 循环播放
                if ([weakSelf.superview isEqual:[AppDelegate shareInstance].window]) { // 放大的的视频，需要缩小或者remove
                    [weakSelf dismissSelf];
                }
            }];
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            weakSelf.bottomView.processSlider.value = f;
            weakSelf.bottomView.playerTime.text = [weakSelf getMMSSFromSS:weakSelf.currentTime];
            weakSelf.bottomView.totalTime.text = [weakSelf getMMSSFromSS:totalTime];
        });
    }];
}
#pragma mark - 视图隐藏，更新等
// 卡片视频自动播放的时候隐藏关闭按钮等
- (void)isHideSubviews:(BOOL)isHide {
    _imageView.hidden = isHide;
    _closeButton.hidden = isHide;
    _bottomView.hidden = isHide;
    if (isHide) {
        self.player.volume = 0;
    } else {
        self.player.volume = 1.f;
    }
}

// self的frame改变以后，子view的frame相应也要更改
- (void)reloadSubViewsWithSuperView:(UIView *)view{
    // 第一次进视频tab的时候，backview的size有可能为（0，0），视频frame也会没有值，给它添加一个默认大小防止第一次进来无法播放
    if (CGRectEqualToRect(view.bounds, CGRectZero)) { // 初始值为（0，0，0，0）时给它设置一个默认值
        self.playerLayer.frame = CGRectMake(0, 0, MAINSCREEN_WIDTH - 40, ceil((MAINSCREEN_WIDTH - 40) * 9 / 16));
    } else {
        self.playerLayer.frame = view.bounds;
    }
    [self mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.top.right.left.bottom.equalTo(view);
    }];
    [self.controlView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.top.right.left.bottom.equalTo(self);
    }];

    [self.indicator mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.center.equalTo(self);
        make.width.mas_equalTo(MAINSCREEN_WIDTH - 100);
        make.height.mas_equalTo(MAINSCREEN_HEIGHT - 200);
    }];

    // 自动播放时不需要动画
    if ([self.superview isEqual:[AppDelegate shareInstance].window]) {
        [self doConstraintAnimation];
    }
}

- (void)showIndicator:(BOOL)isShow {
    if (isShow) {
        [self.indicator startAnimating];
    } else {
        [self.indicator stopAnimating];
    }
}

- (void)showBottom {
    [self.bottomView mas_remakeConstraints:^(MASConstraintMaker *make) {
        if (self.deviceOrientation == UIDeviceOrientationPortrait) {
            if ([UIDevice resolutionType] == iPhone58Inches) {
                make.height.mas_equalTo(40 + UIView.safeAreaInsetsBottom * 2);
            } else {
                make.height.mas_equalTo(40);
            }
        } else {
            make.height.mas_equalTo(40);
        }
        make.left.right.mas_equalTo(0);
        make.bottom.mas_equalTo(self);
    }];
    BOOL isFull = !UIDeviceOrientationIsPortrait(self.deviceOrientation);
    [self.bottomView enterFullScreen:isFull];
    if (_isUserStop) {
        self.controlView.bigPlayerBtn.hidden = NO;
        self.controlView.coverView.hidden = NO;
        // 用户点击暂停以后，bottomview不用3秒消失（播放状态下才会3秒后消失）
        [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(hideBottom) object:nil];
    } else {
        self.controlView.bigPlayerBtn.hidden = YES;
        self.controlView.coverView.hidden = YES;
        [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(hideBottom) object:nil];
        [self performSelector:@selector(hideBottom) withObject:nil afterDelay:3];
    }

}

- (void)hideBottom {
    self.controlView.bigPlayerBtn.hidden = YES;
    self.controlView.coverView.hidden = YES;
    [self.bottomView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_equalTo(0);
        make.top.equalTo(self.mas_bottom);
        make.height.mas_equalTo(40);
    }];
}

- (void)doConstraintAnimation {
    [self setNeedsUpdateConstraints];
    [self updateConstraintsIfNeeded];

    [UIView animateWithDuration:.3 animations:^{
        [self layoutIfNeeded];
    }];
}

#pragma mark - slider
- (void)changeProcessValue:(UISlider *)slider {
    float value = slider.value;
    CMTime duration = self.playerItem.asset.duration;
    float max = CMTimeGetSeconds(duration);
    long long l = ceil(max*value);
    [_playerLayer.player seekToTime:CMTimeMake(l, 1)];

}
- (void)sliderTouchDown:(UISlider *)slider {
    _isUserStop = NO;
    [_player pause];
    _bottomView.playButton.selected = YES;
}
- (void)sliderTouchCancel:(UISlider *)slider {
    if (_isUserStop) {
        [_player pause];
        _bottomView.playButton.selected = YES;
    } else {
        [_player play];
        _bottomView.playButton.selected = NO;
        self.controlView.bigPlayerBtn.hidden = YES;
        self.controlView.coverView.hidden = YES;
        _isUserStop = NO;
    }
}
#pragma mark - 视图消失
- (void)dismissSelf {
    if (self.deviceOrientation != UIDeviceOrientationPortrait) {
        [self didClickExitFullScreen];
    }
    if (_mySuperView) { // 正在播放的
        // 埋点
        [self full_stack_click_video_card_full_screen_play];
        if (_isUserStop) { // 点击了暂停
            [self.player play];
            _isUserStop = NO;
            _bottomView.playButton.selected = NO;
            self.controlView.bigPlayerBtn.hidden = NO;
            self.controlView.coverView.hidden = NO;
        }
        [self isHideSubviews:YES];
        self.controlView.bigPlayerBtn.hidden = YES;
        self.controlView.coverView.hidden = YES;
        [_mySuperView addSubview:self];
        _backView.backgroundColor = [UIColor bodyText];

        // 动画
        [self reloadSubViewsWithSuperView:_mySuperView];
        [self doConstraintAnimation];

    } else {
        [self isHideSubviews:YES];
        self.volumeView.hidden = YES;
        self.fastSpeedView.hidden = YES;
        self.brightView.hidden = YES;
        // 埋点
        [self full_stack_click_video_card_full_screen_play];

        // 动画
        [self mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.size.mas_equalTo(self.initialPlayerFrame.size);
            make.top.mas_equalTo(self.initialPlayerFrame.origin.y);
            make.left.mas_equalTo(self.initialPlayerFrame.origin.x);
        }];
        [self setNeedsUpdateConstraints];
        [self updateConstraintsIfNeeded];
        [UIView animateWithDuration:0.25 delay:0 options:UIViewAnimationOptionCurveEaseOut animations:^{
            [self layoutIfNeeded];
        } completion:^(BOOL finished) {
            [self removeFromSuperview];
            [self stop];
        }];
    }
}

#pragma mark - Action
- (void)singleTap:(UIGestureRecognizer *)gesture {
    if (!_isUserStop) { // 用户未暂停视频的时候
        if (self.bottomView.frame.origin.y >= self.bounds.size.height) {
            [self showBottom];
        } else {
            [self hideBottom];
        }
    }
}
- (void)clickPlayVideo:(GMButton *)button {
    if ([AFNetworkReachabilityManager sharedManager].networkReachabilityStatus == AFNetworkReachabilityStatusNotReachable) {
        dispatch_async(dispatch_get_main_queue(), ^{
            // UI更新代码
//            [self.viewController toast:@"网络情况欠佳，请检查网络"];
        });
        return;
    }
    button.selected = !button.selected;
    _isUserStop = button.selected;
    if (button.selected) {
        [self.player pause];
        [self showBottom];
    } else {
        [self.player play];
        [self hideBottom];
    }
}
- (void)videoClickedEvent:(UIGestureRecognizer *)gesture {
    if ([self.superview isEqual:[AppDelegate shareInstance].window]) { // 当前视频view是全屏状态
        [self singleTap:gesture];
        return;
    }
    _bottomView.playButton.selected = NO;
    self.controlView.bigPlayerBtn.hidden = YES;
    self.controlView.coverView.hidden = YES;
    self.startTime = [PhobosUtil currentTime]; // 埋点使用
    [self isHideSubviews:NO];
    [self showBottom];
    [self addViewNumber]; // 告诉后台观看过
    _backView.backgroundColor = [UIColor headlineText];
    [[AppDelegate shareInstance].window addSubview:self];
    [self mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(self.initialPlayerFrame.size);
        make.top.mas_equalTo(self.initialPlayerFrame.origin.y);
        make.left.mas_equalTo(self.initialPlayerFrame.origin.x);
    }];
    [self reloadSubViewsWithSuperView:[AppDelegate shareInstance].window];
}

#pragma mark - 旋转
- (void)transformWithOrientation:(UIDeviceOrientation)or {
    BOOL isFullScreen = NO;
    if (or == self.deviceOrientation) return;
    if (!(UIDeviceOrientationPortrait == or || UIDeviceOrientationLandscapeLeft == or || UIDeviceOrientationLandscapeRight == or)) return;
    if (or == UIDeviceOrientationPortrait) {
        isFullScreen = NO;
        [self.bottomView enterFullScreen:NO];
        UIView *superView = [AppDelegate shareInstance].window;
        self.playerLayer.frame = superView.bounds;

        [self mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.edges.equalTo(superView);
        }];
        [self.indicator mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.center.equalTo(self);
            make.width.mas_equalTo(MAINSCREEN_WIDTH - 100);
            make.height.mas_equalTo(MAINSCREEN_HEIGHT - 200);
        }];
        [_controlView.bigPlayerBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.center.equalTo(self);
            make.width.mas_equalTo(MAINSCREEN_WIDTH - 100);
            make.height.mas_equalTo(MAINSCREEN_HEIGHT - 300);
        }];

        [_closeButton mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.top.mas_equalTo(OCNavigationBar.statusBarHeight + 10);
            make.left.mas_equalTo(15);
            make.height.mas_equalTo(40);
            make.width.mas_equalTo(40);
        }];
        [UIView animateWithDuration:.3 animations:^{
            self.transform = CGAffineTransformMakeRotation(0);
        }];
    } else {
        isFullScreen = YES;
        CGFloat duration = .5;
        if (!UIDeviceOrientationIsLandscape(self.deviceOrientation)) {
            duration = .3;

            [self.bottomView enterFullScreen:YES];
            UIView *superView = [AppDelegate shareInstance].window;
            self.playerLayer.frame = CGRectMake(0, 0, MAINSCREEN_HEIGHT, MAINSCREEN_WIDTH);
            [self mas_remakeConstraints:^(MASConstraintMaker *make) {
                make.width.equalTo(superView.mas_height);
                make.height.equalTo(superView.mas_width);
                make.center.equalTo(superView);
            }];
            [self.indicator mas_remakeConstraints:^(MASConstraintMaker *make) {
                make.center.equalTo(self);
                make.width.mas_equalTo(MAINSCREEN_HEIGHT - 200);
                make.height.mas_equalTo(MAINSCREEN_WIDTH - 100);
            }];
            [_controlView.bigPlayerBtn mas_makeConstraints:^(MASConstraintMaker *make) {
                make.center.equalTo(self);
                make.width.mas_equalTo(MAINSCREEN_HEIGHT - 200);
                make.height.mas_equalTo(MAINSCREEN_WIDTH - 200);
            }];
            [_closeButton mas_remakeConstraints:^(MASConstraintMaker *make) {
                make.top.mas_equalTo(30);
                if ([UIDevice resolutionType] == iPhone58Inches) {
                    make.left.mas_equalTo(15 + OCNavigationBar.statusBarHeight);
                } else {
                    make.left.mas_equalTo(15);
                }
                make.height.mas_equalTo(40);
                make.width.mas_equalTo(40);
            }];
        }


        [UIView animateWithDuration:duration animations:^{
            self.transform = UIDeviceOrientationLandscapeLeft == or ? CGAffineTransformMakeRotation(M_PI / 2) : CGAffineTransformMakeRotation(3 * M_PI / 2);

        }];
    }

    AppDelegate.visibleController.isFullScreen = isFullScreen;
    //调用隐藏statusbar方法
    [AppDelegate.visibleController prefersStatusBarHidden];
    [AppDelegate.visibleController setNeedsStatusBarAppearanceUpdate];
//    if ([AppDelegate.visibleController isKindOfClass:[GMHomeV6Controller class]]) {
//        AppDelegate.tabBarController.isFullScreen = isFullScreen;
//        [AppDelegate.tabBarController prefersStatusBarHidden];
//        [AppDelegate.tabBarController setNeedsStatusBarAppearanceUpdate];
//    } else {
//        //调用隐藏statusbar方法
//        [AppDelegate.visibleController prefersStatusBarHidden];
//        [AppDelegate.visibleController setNeedsStatusBarAppearanceUpdate];
//    }

    self.deviceOrientation = or;
    // 重新布局bottom
    [self showBottom];
}

#pragma mark - 请求接口
- (void)addViewNumber {
//    NSAssert(self.topicId != nil, @"GMPlayerView.topicId默认为nil，如果不需要topicID，请设置为空字符串");
//    NSAssert(self.from != nil, @"GMPlayerView.from默认为nil，如果不需要from，请设置为空字符串");
//    if ([_topicId isNonEmpty] && ![_topicId isEqualToString:@"0"]) {
//        NSDictionary *param = @{@"topic_id": SafeString(_topicId),@"play_from": SafeString(_from)};
//        [GMNetworking requestOCWithApi:API_TOPIC_ADDVIEW method:GMHTTPMethodGet parameters:param completion:NULL];
//    }
}

#pragma mark - 时间格式化
-(NSString *)getMMSSFromSS:(float)totalTime{
    NSInteger seconds = totalTime;
    //format of minute
    NSString *str_minute = [NSString stringWithFormat:@"%02d", (int)((seconds%3600)/60)];
    //format of second
    NSString *str_second = [NSString stringWithFormat:@"%02d", (int)(seconds%60)];
    //format of time
    NSString *format_time = [NSString stringWithFormat:@"%@:%@",str_minute,str_second];

    return format_time;
}

#pragma mark - 埋点
// 全屏播放
- (void)full_stack_click_video_card_full_screen_play {
    self.endTime = [PhobosUtil currentTime];
    if (self.video) { // 如果值不为nil，埋点
        NSDictionary *dic = @{@"play_from": SafeString(self.video.pageName),
                              @"tab_name": SafeString(self.video.tabName),
                              @"card_type": SafeString(self.video.cardType),
                              @"tag_id": SafeString(self.video.tagId),
                              @"business_id": SafeString(self.video.businessId),
                              @"start_time": SafeString(self.startTime),
                              @"end_time": SafeString(self.endTime)
                              };
        [Phobos track:@"full_stack_click_video_card_full_screen_play" attributes:dic];
    }
}

#pragma mark - GMPlayerControlViewDelegate
#pragma mark 点击播放按钮
- (void)didClickPlayerBtn:(GMButton *)sender {
    [self clickPlayVideo:self.bottomView.playButton];
}

#pragma mark 开始触摸
- (void)touchesBeganWithPoint:(CGPoint)point {
    //记录首次触摸坐标
    self.startPoint = point;
    //检测用户是触摸屏幕的左边还是右边，以此判断用户是要调节音量还是亮度，左边是亮度，右边是音量
    if (self.startPoint.x <= self.controlView.frame.size.width / 2.0) {
        //亮度
        self.startVB = [UIScreen mainScreen].brightness;
    } else {
        //音/量
        self.startVB = self.volumeViewSlider.value;
    }
    //方向置为无
    self.direction = TouchDirectionNone;
    //记录当前视频播放的进度
    CMTime ctime = self.player.currentTime;
    self.startVideoRate = ctime.value / ctime.timescale / CMTimeGetSeconds(self.playerItem.asset.duration);

}

#pragma mark 结束触摸
- (void)touchesEndWithPoint:(CGPoint)point {
    [self sendSubviewToBack:self.volumeView];
    [self sendSubviewToBack:self.brightView];
    [self sendSubviewToBack:self.fastSpeedView];

    if (self.direction == TouchDirectionLeftOrRight) {
        [self.player seekToTime:CMTimeMakeWithSeconds(CMTimeGetSeconds(self.playerItem.asset.duration) * self.currentRate, 600) toleranceBefore:kCMTimeZero toleranceAfter:kCMTimeZero];
        // 暂停的时候，快进或者快退完也要继续播放
        if (_isUserStop) {
            self.controlView.bigPlayerBtn.hidden = YES;
            self.controlView.coverView.hidden = YES;
            _bottomView.playButton.selected = NO;
            _isUserStop = NO;
            [self.player play];
        }
    }
}

#pragma mark 拖动
- (void)touchesMoveWithPoint:(CGPoint)point {
    //得出手指在view上移动的距离
    CGPoint panPoint = CGPointMake(point.x - self.startPoint.x, point.y - self.startPoint.y);
    //分析出用户滑动的方向
    if (self.direction == TouchDirectionNone) {
        if (panPoint.x >= 30 || panPoint.x <= -30) {
            if (panPoint.x >= 30) {
                self.fastSpeedView.imageView.image = [UIImage imageNamed:@"player_ahead"];
            } else {
                self.fastSpeedView.imageView.image = [UIImage imageNamed:@"player_playBack"];
            }
            //进度
            self.direction = TouchDirectionLeftOrRight;
        } else if (panPoint.y >= 30 || panPoint.y <= -30) {
            //音量和亮度
            self.direction = TouchDirectionUpOrDown;
        }
    }

    if (self.direction == TouchDirectionNone) {
        return;
    } else if (self.direction == TouchDirectionUpOrDown) {
        //音量和亮度
        if (self.startPoint.x <= self.controlView.frame.size.width / 2.0) {
            [self bringSubviewToFront:self.brightView];
            //调节亮度
            [[UIScreen mainScreen] setBrightness:self.startVB - (panPoint.y / 30.0 / 10)];
            self.brightView.progressView.progress = self.startVB - (panPoint.y / 30.0 / 10);
        } else {
            //音量
            CGFloat volume;
            volume = self.startVB - panPoint.y / 30.0 / 10;
            if (volume < 0.0001) {
                volume = 0;
            } else if (volume > 1) {
                volume = 1;
            }

            if (volume == self.volumeViewSlider.value) {
                // 不更改音量值不会发出通知，此处需要做View上的音量进度展示
                [self bringSubviewToFront:self.volumeView];
            } else {
                self.volumeViewSlider.value = volume;
            }
        }
    } else if (self.direction == TouchDirectionLeftOrRight ) {
        [self bringSubviewToFront:self.fastSpeedView];
        //进度
        CGFloat rate = self.startVideoRate + (panPoint.x / 30.0 / 20.0);
        if (rate >= 1) {
            rate = 0.95;
        } else if (rate < 0) {
            rate = 0;
        }
        self.currentRate = rate;
        self.fastSpeedView.timeLabel.text = [self getMMSSFromSS:CMTimeGetSeconds(self.playerItem.asset.duration) * self.currentRate];
    }
}

#pragma mark - GMVideoBottomViewDelegate
- (void)didClickExitFullScreen {
    [self transformWithOrientation:UIDeviceOrientationPortrait];
}

-(void)didClickEnterFullScreen {
    if (UIDeviceOrientationLandscapeRight == [[UIDevice currentDevice]orientation]) {
        [self transformWithOrientation:UIDeviceOrientationLandscapeRight];
    } else {
        [self transformWithOrientation:UIDeviceOrientationLandscapeLeft];
    }
}

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